@calimero-network/mero-react 9.16.0 → 10.0.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["#style-inject:#style-inject","../src/components/styles.css","../src/types.ts","../src/auth/node-trust.ts","../src/auth/token-adoption.ts","../src/storage/index.ts","../src/context/MeroContext.tsx","../src/components/CalimeroLogo.tsx","../src/theme.ts","../src/components/AccountSignInPanel.tsx","../src/delegated/useAccountEnrolment.ts","../src/utils/desktop.ts","../src/components/LoginModal.tsx","../src/components/ConnectButton.tsx","../src/components/ConnectButtonAccount.tsx","../src/utils/base58.ts","../src/hooks/index.ts","../src/components/MigrationPendingBanner.tsx","../src/components/MigrationAdminPanel.tsx","../src/delegated/useDelegatedBootstrap.ts","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/bridge/index.js","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/deep-link/link.js","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/deep-link/pending-intent.js","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/deep-link/index.js","../src/invitations/capture.ts","../src/invitations/describeInviteFailure.ts","../src/invitations/justJoined.ts","../src/invitations/useInviteRedemption.ts","../src/invitations/useJoinSync.ts","../src/invitations/InvitationDialog.tsx","../src/invitations/JoinSyncBanner.tsx","../src/invitations/InvitationGate.tsx","../src/join/useJoinInvitation.ts"],"names":["AppMode","ConnectionType","current","refreshToken","createContext","useMemo","LocalStorageTokenStore","useState","readDelegatedSession","useRef","parseAuthCallback","useCallback","MeroJs","buildAuthLoginUrl","saveDelegatedSession","saveDelegatedCredential","clearDelegatedSession","clearDelegatedCredential","useEffect","relayForContext","buildDelegatedClient","readPinnedRelayNodeKey","learnRelayNodeKey","resolveApplicationIdFromRegistry","listDelegatedContexts","AuthRevokedError","HTTPError","joinAsAccount","foundDelegatedNamespace","CloudClient","createAccountAdmin","createNodeAdmin","useContext","jsxs","jsx","readEnrolmentCallback","completeDeviceEnrolment","deviceEnrolmentUrl","DEFAULT_LOCAL_NODE_PORTS","controller","discoverLocalNodes","nodeEndpoint","Fragment","selected","createPortal","classifyError","createDelegatedContext","createDelegatedPrivateContext","governRoot","memberJoinedOpenOp","signerFromSecret","listDelegatedNamespaces","compareSemver","read","readDelegatedCredential","bootstrapFromInvitation","rememberRelay","carryExecutorAccount","storage","listeners","shouldRetain","redeemInvitation","useReducer","useSyncExternalStore","useId","InviteIcon"],"mappings":";;;;;;;;AACyB,SAAR,YAA6B,GAAA,EAAK,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG;AAC1D,EAAA,IAAY,OAAO,QAAA,KAAa,WAAA,EAAa;AAE7C,EAAA,MAAM,OAAO,QAAA,CAAS,IAAA,IAAQ,SAAS,oBAAA,CAAqB,MAAM,EAAE,CAAC,CAAA;AACrE,EAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AAC5C,EAAA,KAAA,CAAM,IAAA,GAAO,UAAA;AAEb,EAAA,IAAI,aAAa,KAAA,EAAO;AACtB,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,IAAA,CAAK,YAAA,CAAa,KAAA,EAAO,IAAA,CAAK,UAAU,CAAA;AAAA,IAC1C,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AAAA,IACxB;AAAA,EACF,CAAA,MAAO;AACL,IAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AAAA,EACxB;AAEA,EAAA,IAAI,MAAM,UAAA,EAAY;AACpB,IAAA,KAAA,CAAM,WAAW,OAAA,GAAU,GAAA;AAAA,EAC7B,CAAA,MAAO;AACL,IAAA,KAAA,CAAM,WAAA,CAAY,QAAA,CAAS,cAAA,CAAe,GAAG,CAAC,CAAA;AAAA,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IAAA,MAAM,MAAM,CAAC,IAAA,KACX,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,WAAA,IAAe,CAAA,CAAE,WAAW,CAAA,CAAE,EAAA,IAAM,EAAE,CAAA,CAAE,OAAO,OAAO,CAAA;AAC1E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,MAAM,UAAUH,2BAAAA,EAAqB;AACrC,MAAA,OAAO,UAAU,GAAA,CAAI,MAAM2C,+BAAwB,OAAO,CAAC,IAAI,EAAC;AAAA,IAClE;AACA,IAAA,IAAI,CAAC,IAAA,EAAM,OAAO,EAAC;AACnB,IAAA,OAAO,GAAA,CAAK,MAAM,IAAA,CAAK,KAAA,CAAM,gBAAmF,CAAA;AAAA,EAClH,CAAA,EAAG,CAAC,IAAA,EAAM,WAAA,EAAa,UAAU,CAAC,CAAA;AAElC,EAAA,MAAM,kBAAA,GAAqBxC,iBAAAA;AAAA,IACzB,CAAC,KAAA,MAAgD;AAAA,MAC/C,MAAM,YAAY;AAChB,QAAA,MAAM,OAAA,GAAU,MAAM,cAAA,CAAe,KAAK,CAAA;AAC1C,QAAA,IAAI,CAAC,QAAQ,EAAA,EAAI;AACf,UAAA,MAAM,OAAO,MAAA,CAAO,IAAI,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,EAAG,OAAA,CAAQ,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAO,GAAI,EAAE,CAAA;AAAA,QAC/G;AAAA,MACF,CAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,gBAAgB,WAAW;AAAA,GAC9B;AAEA,EAAA,OAAO,EAAE,cAAA,EAAgB,OAAA,EAAS,WAAA,EAAa,kBAAA,EAAmB;AACpE","file":"index.cjs","sourcesContent":["\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\":root {\\n --mero-bg: #0d1117;\\n --mero-bg-secondary: #161b22;\\n --mero-bg-tertiary: #1c2128;\\n --mero-text: #e6edf3;\\n --mero-text-secondary: #8b949e;\\n --mero-accent: #a5ff11;\\n --mero-accent-hover: #8ed40d;\\n --mero-on-primary: #0d1117;\\n --mero-error: #ff6b6b;\\n --mero-border: #30363d;\\n --mero-disabled: #555555;\\n --mero-shadow: rgba(0, 0, 0, 0.5);\\n --mero-overlay: rgba(0, 0, 0, 0.75);\\n --mero-radius: 8px;\\n}\\n.mero-connect-button {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n gap: 8px;\\n padding: 10px 20px;\\n background-color: var(--mero-accent);\\n border: 1px solid var(--mero-accent);\\n border-radius: var(--mero-radius);\\n cursor: pointer;\\n font-size: 14px;\\n font-weight: 600;\\n letter-spacing: 0.01em;\\n color: var(--mero-on-primary);\\n transition:\\n background-color 0.15s ease,\\n border-color 0.15s ease,\\n box-shadow 0.15s ease,\\n transform 0.1s ease;\\n min-width: 140px;\\n box-sizing: border-box;\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n -moz-osx-font-smoothing: grayscale;\\n line-height: 1;\\n}\\n.mero-connect-button:hover:not(.mero-connected):not(.mero-reconnecting) {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n box-shadow: 0 0 0 4px rgba(165, 255, 17, 0.18);\\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--mero-accent) 18%, transparent);\\n}\\n.mero-connect-button:active:not(.mero-connected):not(.mero-reconnecting) {\\n transform: translateY(1px);\\n}\\n.mero-connect-button:focus-visible {\\n outline: none;\\n box-shadow: 0 0 0 3px rgba(165, 255, 17, 0.45);\\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--mero-accent) 45%, transparent);\\n}\\n.mero-connect-button.mero-logo-only {\\n min-width: 0;\\n width: 40px;\\n height: 40px;\\n padding: 0;\\n gap: 0;\\n}\\n.mero-connect-button.mero-connected {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n border-color: var(--mero-accent);\\n}\\n.mero-connect-button.mero-connected:hover {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n}\\n.mero-connect-button.mero-reconnecting {\\n background-color: var(--mero-bg-secondary);\\n color: var(--mero-text-secondary);\\n border-color: var(--mero-border);\\n cursor: not-allowed;\\n}\\n.mero-connect-container {\\n position: relative;\\n display: inline-block;\\n}\\n.mero-dropdown {\\n position: absolute;\\n top: 100%;\\n left: 0;\\n background-color: var(--mero-bg-secondary);\\n border: 1px solid var(--mero-border);\\n border-radius: var(--mero-radius);\\n margin-top: 6px;\\n padding: 0;\\n z-index: 1001;\\n width: 100%;\\n min-width: 180px;\\n overflow: hidden;\\n box-shadow: 0 8px 24px var(--mero-shadow);\\n}\\n.mero-dropdown-info {\\n padding: 10px 16px;\\n color: var(--mero-text-secondary);\\n font-size: 13px;\\n border-bottom: 1px solid var(--mero-border);\\n white-space: nowrap;\\n overflow: hidden;\\n text-overflow: ellipsis;\\n max-width: 220px;\\n}\\n.mero-dropdown-item {\\n display: block;\\n width: 100%;\\n padding: 10px 16px;\\n background: none;\\n border: none;\\n color: var(--mero-text);\\n text-align: left;\\n cursor: pointer;\\n font-size: 14px;\\n text-decoration: none;\\n font-family: inherit;\\n}\\n.mero-dropdown-item:hover {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n}\\n.mero-logo {\\n width: 24px;\\n height: 24px;\\n color: currentColor;\\n}\\n@keyframes meroFadeIn {\\n from {\\n opacity: 0;\\n }\\n to {\\n opacity: 1;\\n }\\n}\\n@keyframes meroSlideIn {\\n from {\\n transform: translateY(-12px);\\n opacity: 0;\\n }\\n to {\\n transform: translateY(0);\\n opacity: 1;\\n }\\n}\\n@keyframes meroSpin {\\n to {\\n transform: rotate(360deg);\\n }\\n}\\n.mero-invite-overlay {\\n position: fixed;\\n inset: 0;\\n z-index: 2147483646;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n padding: 16px;\\n background: var(--mero-overlay);\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n}\\n.mero-invite-dialog {\\n box-sizing: border-box;\\n width: min(420px, 100%);\\n padding: 24px;\\n border: 1px solid var(--mero-border);\\n border-radius: calc(var(--mero-radius) * 1.5);\\n background: var(--mero-bg-secondary);\\n color: var(--mero-text);\\n box-shadow: 0 16px 48px var(--mero-shadow);\\n outline: none;\\n animation: mero-invite-in 0.16s ease-out;\\n}\\n.mero-invite-app {\\n margin: 0 0 12px;\\n font-size: 12px;\\n font-weight: 600;\\n letter-spacing: 0.06em;\\n text-transform: uppercase;\\n color: var(--mero-text-secondary);\\n}\\n.mero-invite-head {\\n display: flex;\\n align-items: center;\\n gap: 12px;\\n}\\n.mero-invite-title {\\n margin: 0;\\n min-width: 0;\\n font-size: 18px;\\n font-weight: 600;\\n line-height: 1.3;\\n overflow-wrap: anywhere;\\n}\\n.mero-invite-body {\\n margin: 12px 0 0;\\n font-size: 14px;\\n line-height: 1.5;\\n color: var(--mero-text-secondary);\\n}\\n.mero-invite-body-error {\\n color: var(--mero-error);\\n}\\n.mero-invite-icon {\\n flex: none;\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n width: 36px;\\n height: 36px;\\n border-radius: 50%;\\n background: var(--mero-bg-tertiary);\\n color: var(--mero-accent);\\n}\\n.mero-invite-icon-error {\\n color: var(--mero-error);\\n}\\n.mero-invite-spinner {\\n box-sizing: border-box;\\n width: 36px;\\n height: 36px;\\n border: 3px solid var(--mero-bg-tertiary);\\n border-top-color: var(--mero-accent);\\n background: none;\\n animation: mero-invite-spin 0.8s linear infinite;\\n}\\n.mero-invite-progress {\\n position: relative;\\n height: 3px;\\n margin-top: 16px;\\n overflow: hidden;\\n border-radius: 2px;\\n background: var(--mero-bg-tertiary);\\n}\\n.mero-invite-progress-bar {\\n position: absolute;\\n top: 0;\\n bottom: 0;\\n width: 40%;\\n border-radius: 2px;\\n background: var(--mero-accent);\\n animation: mero-invite-progress 1.4s ease-in-out infinite;\\n}\\n.mero-invite-actions {\\n display: flex;\\n flex-wrap: wrap;\\n justify-content: flex-end;\\n gap: 8px;\\n margin-top: 20px;\\n}\\n.mero-invite-actions:empty {\\n display: none;\\n}\\n.mero-invite-button {\\n padding: 9px 16px;\\n border-radius: var(--mero-radius);\\n font: inherit;\\n font-size: 14px;\\n font-weight: 600;\\n line-height: 1.2;\\n cursor: pointer;\\n transition: background-color 0.15s ease, border-color 0.15s ease;\\n}\\n.mero-invite-button:focus-visible {\\n outline: 2px solid var(--mero-accent);\\n outline-offset: 2px;\\n}\\n.mero-invite-primary {\\n border: 1px solid var(--mero-accent);\\n background: var(--mero-accent);\\n color: var(--mero-on-primary);\\n}\\n.mero-invite-primary:hover {\\n border-color: var(--mero-accent-hover);\\n background: var(--mero-accent-hover);\\n}\\n.mero-invite-secondary {\\n border: 1px solid var(--mero-border);\\n background: transparent;\\n color: var(--mero-text);\\n}\\n.mero-invite-secondary:hover {\\n background: var(--mero-bg-tertiary);\\n}\\n.mero-invite-landing {\\n position: fixed;\\n inset: 0;\\n z-index: 9999;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n padding: 16px;\\n overflow-y: auto;\\n background: var(--mero-bg);\\n color: var(--mero-text);\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n}\\n.mero-invite-landing-card {\\n width: min(460px, 100%);\\n}\\n.mero-invite-landing-card .mero-invite-title {\\n font-size: 22px;\\n}\\n.mero-invite-landing-login {\\n display: inline-flex;\\n}\\n.mero-invite-landing-login .mero-connect-button {\\n min-width: 0;\\n padding: 9px 16px;\\n line-height: 1.2;\\n}\\n@keyframes mero-invite-spin {\\n to {\\n transform: rotate(360deg);\\n }\\n}\\n@keyframes mero-invite-progress {\\n from {\\n left: -40%;\\n }\\n to {\\n left: 100%;\\n }\\n}\\n@keyframes mero-invite-in {\\n from {\\n opacity: 0;\\n transform: translateY(6px) scale(0.98);\\n }\\n}\\n@media (prefers-reduced-motion: reduce) {\\n .mero-invite-dialog,\\n .mero-invite-spinner,\\n .mero-invite-progress-bar {\\n animation: none;\\n }\\n}\\n\")","/**\n * Types for mero-react\n */\n\nimport type { MeroClient, MeroJs, TokenStore } from '@calimero-network/mero-js';\nimport type { DelegatedAccountSession as DelegatedSession } from '@calimero-network/mero-js';\n\n/**\n * Application mode determines the permission scope\n */\nexport enum AppMode {\n /**\n * @deprecated since 2.1.0 — SingleContext is no longer supported and will\n * be removed in 3.0.0. Auth-frontend no longer drives\n * context/namespace/group selection; the auth callback returns only\n * `access_token`, `refresh_token`, `application_id`, and `node_url`.\n * Switch to {@link AppMode.MultiContext} and have your app manage\n * context selection itself.\n *\n * Migration: see `example/app/src/pages/context/SelectContext.tsx` for a\n * reference implementation. It uses `useContexts` /\n * `useNamespacesForApplication` for listing, then calls\n * `mero.admin.createNamespace` / `createGroupInNamespace` /\n * `createContext` directly (rather than the `useCreate*` hooks) so the\n * underlying server error surfaces to the user instead of being\n * swallowed by `useAsyncMutation`.\n */\n SingleContext = 'single-context',\n /** Multi-context: user can manage multiple contexts */\n MultiContext = 'multi-context',\n /** Admin: full administrative access */\n Admin = 'admin',\n}\n\n/**\n * Connection type for the login modal\n */\nexport enum ConnectionType {\n /**\n * @deprecated The login modal no longer has Local/Remote tabs — it always\n * shows node discovery + manual URL entry. Behaves the same as `Remote`.\n */\n RemoteAndLocal = 'remote-and-local',\n /** Open the login modal (node discovery + manual URL entry) */\n Remote = 'remote',\n /**\n * @deprecated The hardcoded default-local-node view was removed. Behaves\n * the same as `Remote`.\n */\n Local = 'local',\n /** Custom URL (skip modal) */\n Custom = 'custom',\n}\n\n/**\n * Custom connection configuration\n */\nexport interface CustomConnectionConfig {\n type: ConnectionType.Custom;\n url: string;\n}\n\n/**\n * Context for an application\n */\nexport interface AppContext {\n contextId: string;\n executorId: string;\n applicationId: string;\n}\n\n/**\n * Result of an RPC execution\n */\nexport interface ExecutionResult<T = unknown> {\n success: boolean;\n result?: T;\n error?: string;\n}\n\nexport interface ApplicationContextRecord {\n contextId: string;\n applicationId: string;\n}\n\nexport interface ContextDiscoveryOptions {\n applicationId: string;\n knownContextIds?: string[];\n targetAlias?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface ContextDiscoveryState {\n context: ApplicationContextRecord | null;\n loading: boolean;\n error: Error | null;\n discover: () => Promise<ApplicationContextRecord | null>;\n reset: () => void;\n}\n\n/**\n * Mero context value exposed by useMero hook\n */\nexport interface MeroContextValue {\n /**\n * The connected client, or null.\n *\n * Two shapes, because there are two ways to connect: a node login yields a\n * `MeroJs`, an account + relay connection yields a relay-transport\n * `MeroClient`. Both expose `rpc` as an `ExecuteTransport`, which is what a\n * generated ABI client depends on — so application logic is identical across\n * the two and needs no branch.\n *\n * The union is deliberately not flattened behind a cast. A relay client has\n * no `admin`, so code reaching for one should not typecheck as though it\n * were there; narrow with {@link MeroContextValue.isDelegated} first.\n */\n mero: MeroJs | MeroClient | null;\n /** Whether the user is authenticated */\n isAuthenticated: boolean;\n /** Whether the connection is online */\n isOnline: boolean;\n /** The current node URL */\n nodeUrl: string | null;\n /** The application ID */\n applicationId: string | null;\n /** The context ID (from auth flow) */\n contextId: string | null;\n /** The context identity / executor public key (from auth flow) */\n contextIdentity: string | null;\n /** Connect to a node URL and start auth flow */\n connectToNode: (url: string) => void;\n /**\n * Adopt a delegated connection: an account, a device that account certified,\n * and a relay that writes on its behalf.\n *\n * Installs the relay client immediately — there is no redirect and no token to\n * wait for, because every request carries its own warrant.\n */\n connectWithAccount: (session: DelegatedSession) => void;\n /**\n * Whether the connection is delegated (account + relay) rather than a node\n * login. True means `mero` is a relay-transport client, authenticated by the\n * account's device certificate: `rpc` writes under warrants, and `admin` and\n * `events` answer caller-scoped — this account's own contexts and namespaces,\n * and events only for contexts it is a member of.\n */\n isDelegated: boolean;\n /**\n * What this connection may do, so an app asks WHAT IS ALLOWED instead of\n * which transport it runs on. A node login can do everything; an account on\n * a relay can create contexts (delegated creation) but not namespaces or\n * invitations — those are a node's own operations today. A capability that\n * later becomes available to accounts turns true here with no app change.\n */\n can: MeroCapabilities;\n /**\n * The admin API to write against, whatever the session: the node's own admin\n * client on a node, the account admin (`createAccountAdmin`) on an account.\n * `null` until connected.\n */\n admin: import('@calimero-network/mero-js').AdminApiClient | null;\n /**\n * The app's registry identity, as the provider was given it. An account\n * founding a namespace names this application for it, since a namespace\n * founded through a relay starts with none.\n */\n app: { packageName?: string; packageVersion?: string; registryUrl?: string };\n /** The cloud an account asks for routing; the hosted one when unset. */\n cloudBaseUrl?: string;\n /** Logout and clear tokens */\n logout: () => void;\n /** Loading state */\n isLoading: boolean;\n}\n\n/**\n * MeroProvider configuration\n */\nexport interface MeroProviderConfig {\n /** Application mode */\n mode: AppMode;\n /** Package name (for registry-based apps) */\n packageName?: string;\n /** Package version (optional, defaults to latest) */\n packageVersion?: string;\n /** Registry URL (optional) */\n registryUrl?: string;\n /**\n * The cloud an account asks which relay serves a namespace or an account.\n * Unset is the hosted cloud, which is right for every deployed app; this is\n * for a local or staging setup whose namespaces the hosted cloud never saw.\n */\n cloudBaseUrl?: string;\n /** Request timeout in milliseconds */\n timeoutMs?: number;\n /**\n * Origins the OAuth callback is allowed to authenticate against. Defends\n * against a malicious `node_url` in the callback URL (token exfiltration):\n * the node login was initiated with is always trusted, and this allowlist\n * additionally permits direct-callback entry to known nodes. When neither is\n * available (no initiated node and no allowlist) a callback node_url is\n * rejected and a security error is logged.\n */\n allowedNodeUrls?: string[];\n /**\n * Token store for access/refresh tokens. Defaults to a localStorage-backed\n * store that persists across reloads.\n *\n * SECURITY: localStorage tokens — including the refresh token — are readable\n * by any script on the page, so an XSS bug can exfiltrate them. For sensitive\n * deployments pass a `MemoryTokenStore` (session-only) or a store backed by an\n * HttpOnly cookie set by your auth service.\n */\n tokenStore?: TokenStore;\n}\n\n/** See {@link MeroContextValue.can}. */\nexport interface MeroCapabilities {\n /** Found a namespace. */\n readonly createNamespace: boolean;\n /** Create a context inside a namespace this connection belongs to. */\n readonly createContext: boolean;\n /** Mint an invitation to a namespace. */\n readonly invite: boolean;\n /** Upgrade a group's application. A node's only: a relay carries just the first choice. */\n readonly upgrade: boolean;\n}\n","/**\n * Trust decision for the node URL an OAuth callback wants us to authenticate\n * against.\n *\n * The auth flow redirects the browser to a node's auth UI and back to the app\n * with `access_token` / `refresh_token` / `node_url` in the callback URL. That\n * URL is attacker-influenceable, so a malicious `node_url` would otherwise make\n * the SDK send the freshly-minted tokens to an attacker's node (exfiltration).\n *\n * Defense: only authenticate against a node we can independently trust — the\n * node login was *initiated* with (saved before the redirect), or an\n * app-configured allowlist.\n */\n\n/** True iff both URLs parse and share the same origin (scheme + host + port). */\nexport function sameOrigin(a: string, b: string): boolean {\n try {\n return new URL(a).origin === new URL(b).origin;\n } catch {\n return false;\n }\n}\n\nexport interface ResolveTrustedNodeParams {\n /** `node_url` from the OAuth callback (untrusted, attacker-influenceable). */\n candidate: string | null | undefined;\n /** Node URL login was initiated with, saved before the redirect (trusted). */\n initiated: string | null;\n /** Additional trusted origins, for direct-callback entry without an initiated node. */\n allowedNodeUrls?: string[];\n}\n\nexport interface TrustedNodeResult {\n /** The node URL that is safe to authenticate against, or null. */\n url: string | null;\n /** A candidate node_url was present but could not be trusted (likely an attack). */\n rejected: boolean;\n}\n\n/**\n * Decide which node URL, if any, is safe to authenticate against.\n *\n * - No candidate → fall back to the initiated node.\n * - Candidate + initiated node → must share the initiated node's origin, else reject.\n * - Candidate + no initiated node + allowlist → must be in the allowlist, else reject.\n * - Candidate + no trust anchor (no initiated node and no allowlist) → reject. There is\n * nothing to validate the attacker-influenceable callback against, so refusing is the\n * safe default. The normal flow always records the initiated node (via `connectToNode`)\n * before redirecting; configure `allowedNodeUrls` to permit direct-callback entry.\n */\nexport function resolveTrustedNodeUrl(params: ResolveTrustedNodeParams): TrustedNodeResult {\n const { candidate, initiated, allowedNodeUrls } = params;\n\n if (!candidate) {\n return { url: initiated ?? null, rejected: false };\n }\n\n if (initiated) {\n return sameOrigin(candidate, initiated)\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n if (allowedNodeUrls && allowedNodeUrls.length > 0) {\n return allowedNodeUrls.some((u) => sameOrigin(candidate, u))\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n return { url: null, rejected: true };\n}\n","/**\n * Decide whether the token bundle carried in an SSO callback hash may replace\n * the bundle already in the token store.\n *\n * Since core 0.11.0 (calimero-network/core#3083) refresh tokens are SINGLE-USE:\n * every `POST /auth/refresh` consumes the presented refresh token and returns a\n * new one. Re-presenting a consumed refresh token is treated as theft — the node\n * answers 401 `x-auth-error: token_reuse` and revokes the whole token family, so\n * *every* holder is hard-logged-out.\n *\n * That makes an unconditional `tokenStore.setTokens(callbackBundle)` on the SSO\n * callback path actively dangerous. A desktop host (or any SSO initiator) hands\n * the app a token bundle in the URL hash; if mero-js has already rotated the\n * stored refresh token, writing the hash bundle over it resurrects a *consumed*\n * refresh token. The next refresh presents it → `token_reuse` → family revoked.\n *\n * So the hash bundle is adopted only when it is safe:\n * - there is no stored bundle (a genuinely fresh login), or\n * - the node changed (the stored bundle belongs to a different node), or\n * - the hash tokens are genuinely NEWER than what is stored, or\n * - the stored bundle is missing a refresh token that the hash can supply.\n *\n * Anything else — a stale hash, or a hash replaying the access token we already\n * hold — is ignored, leaving the live (possibly rotated) bundle untouched.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\nimport { sameOrigin } from './node-trust';\n\nconst HOUR_MS = 3_600_000;\n\ninterface JwtClaims {\n /** Issued-at (seconds). The authoritative rotation-order signal when present. */\n iat?: number;\n /** Expiry (seconds). */\n exp?: number;\n}\n\n/**\n * Decode a JWT's payload claims without verifying the signature.\n *\n * Verification is the node's job — we only need the ordering claims to decide\n * which of two bundles is newer, and both bundles are already node-trusted by\n * the time we get here (see `resolveTrustedNodeUrl`).\n *\n * Returns null for anything that is not a decodable three-part JWT (opaque\n * tokens, test fixtures, garbage).\n */\nexport function decodeJwtClaims(token: string): JwtClaims | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n let b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');\n while (b64.length % 4) b64 += '=';\n const payload: unknown = JSON.parse(atob(b64));\n if (!payload || typeof payload !== 'object') return null;\n const { iat, exp } = payload as JwtClaims;\n return {\n iat: typeof iat === 'number' && iat > 0 ? iat : undefined,\n exp: typeof exp === 'number' && exp > 0 ? exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Absolute expiry (ms) of an access token, from its `exp` claim.\n *\n * Mirrors mero-js's internal `expiresAtFromJwt` (which it does not export —\n * checked against mero-js 6.1.0), including the \"assume one hour\" fallback for\n * tokens whose expiry we cannot read.\n */\nexport function expiresAtFromJwt(token: string, fallbackMs: number = Date.now() + HOUR_MS): number {\n const exp = decodeJwtClaims(token)?.exp;\n return exp ? exp * 1000 : fallbackMs;\n}\n\n/**\n * Is the callback's access token newer than the one we already hold?\n *\n * Prefers `iat` (issued-at) — the direct rotation-order signal — and falls back\n * to `exp`, then to the stored bundle's recorded `expires_at`. When the answer\n * cannot be established the token is NOT considered newer: refusing to adopt\n * costs a redundant login at worst, whereas adopting a stale bundle burns the\n * whole token family.\n */\nfunction isCallbackNewer(callbackAccessToken: string, stored: TokenData): boolean {\n const incoming = decodeJwtClaims(callbackAccessToken);\n if (!incoming) return false;\n\n const current = decodeJwtClaims(stored.access_token);\n if (current) {\n if (incoming.iat !== undefined && current.iat !== undefined && incoming.iat !== current.iat) {\n return incoming.iat > current.iat;\n }\n if (incoming.exp !== undefined && current.exp !== undefined && incoming.exp !== current.exp) {\n return incoming.exp > current.exp;\n }\n // Same claims (a replay of the token we already hold), or nothing to compare\n // on — either way the callback brings nothing new.\n return false;\n }\n\n // Stored access token is not a decodable JWT — compare against the expiry the\n // store recorded for it.\n return incoming.exp !== undefined && incoming.exp * 1000 > stored.expires_at;\n}\n\n/** Why the SSO hash bundle was (or was not) written to the token store. */\nexport type TokenAdoptionReason =\n /** No stored bundle — a genuinely fresh login. Seed from the hash. */\n | 'fresh-login'\n /** The stored bundle belongs to a different node. Re-seed from the hash. */\n | 'node-changed'\n /** The hash tokens are genuinely newer than the stored ones. */\n | 'newer'\n /** Same session, but the stored bundle has no refresh token and the hash does. */\n | 'fill-refresh'\n /** The hash tokens are stale, or replay the access token we already hold. */\n | 'stale';\n\nexport type TokenAdoptionDecision =\n | { adopt: true; tokens: TokenData; reason: Exclude<TokenAdoptionReason, 'stale'> }\n | { adopt: false; reason: 'stale' };\n\nexport interface ResolveTokenAdoptionParams {\n /** Access token from the callback hash. Always present (mero-js returns null otherwise). */\n callbackAccessToken: string;\n /**\n * Refresh token from the callback hash. `parseAuthCallback` yields `''` when the\n * hash carries no `refresh_token` — hosts are moving to access-only bundles\n * precisely so they cannot hand back a rotated-away refresh token.\n */\n callbackRefreshToken: string;\n /** Trusted node URL the callback resolved to (see `resolveTrustedNodeUrl`). */\n callbackNodeUrl: string;\n /** Bundle currently in the token store — mero-js may have rotated it already. */\n stored: TokenData | null;\n /** Node URL the stored bundle was issued by, i.e. the node URL before this callback. */\n storedNodeUrl: string | null;\n}\n\n/**\n * Decide what (if anything) to write to the token store for an SSO callback.\n *\n * Never returns a bundle with an empty `refresh_token` when a refresh token for\n * the same node is already stored: an access-only hash bundle is MERGED over the\n * stored one, so adopting a fresher access token cannot strip the session's\n * ability to refresh.\n */\nexport function resolveTokenAdoption(params: ResolveTokenAdoptionParams): TokenAdoptionDecision {\n const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } =\n params;\n\n const bundle = (refreshToken: string): TokenData => ({\n access_token: callbackAccessToken,\n refresh_token: refreshToken,\n expires_at: expiresAtFromJwt(callbackAccessToken),\n });\n\n // Fresh login — nothing to protect.\n if (!stored?.access_token) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'fresh-login' };\n }\n\n // Different node — the stored bundle is for someone else's token family, and\n // its refresh token is meaningless here, so it must NOT be carried over.\n const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);\n if (!sameNode) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'node-changed' };\n }\n\n // Same node, live bundle. Keep the stored refresh token unless the hash carries\n // one — the hash's refresh token may be a copy that mero-js has already rotated\n // away, but an *empty* one would strip refresh from the session entirely.\n const refreshToken = callbackRefreshToken || stored.refresh_token;\n\n if (isCallbackNewer(callbackAccessToken, stored)) {\n return { adopt: true, tokens: bundle(refreshToken), reason: 'newer' };\n }\n\n // The access token is not newer, but the stored bundle cannot refresh and the\n // hash can repair that. Keep the *stored* access token (it is at least as new).\n if (!stored.refresh_token && callbackRefreshToken) {\n return {\n adopt: true,\n tokens: { ...stored, refresh_token: callbackRefreshToken },\n reason: 'fill-refresh',\n };\n }\n\n // Stale (or a replay of the bundle we already hold). Writing it would resurrect\n // a consumed refresh token → `token_reuse` → the node revokes the whole family.\n return { adopt: false, reason: 'stale' };\n}\n","/**\n * Storage utilities for mero-react\n * \n * Provides localStorage-based token storage and other persistence utilities.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\n\n// Storage keys\nconst STORAGE_KEYS = {\n ACCESS_TOKEN: 'mero:access_token',\n REFRESH_TOKEN: 'mero:refresh_token',\n EXPIRES_AT: 'mero:expires_at',\n NODE_URL: 'mero:node_url',\n // The node the token bundle currently in the TokenStore was issued by. Distinct\n // from NODE_URL, which `connectToNode` overwrites with the *target* node before\n // redirecting to login — so at callback time NODE_URL names where we are going,\n // not who minted the tokens we still hold. Telling those apart is what lets the\n // SSO callback re-seed on a node change without mistaking a different node's\n // bundle for a rotated one (see auth/token-adoption.ts).\n TOKEN_NODE_URL: 'mero:token_node_url',\n APPLICATION_ID: 'mero:application_id',\n CONTEXT_ID: 'mero:context_id',\n CONTEXT_IDENTITY: 'mero:context_identity',\n} as const;\n\nlet _storageAvailable: boolean | null = null;\n\nfunction isLocalStorageAvailable(): boolean {\n if (_storageAvailable !== null) return _storageAvailable;\n try {\n if (typeof window === 'undefined' || !window.localStorage) {\n _storageAvailable = false;\n return false;\n }\n const testKey = '__mero_test__';\n localStorage.setItem(testKey, 'test');\n localStorage.removeItem(testKey);\n _storageAvailable = true;\n } catch {\n _storageAvailable = false;\n }\n return _storageAvailable;\n}\n\nexport const localStorageTokenStorage = {\n async get(): Promise<TokenData | null> {\n if (!isLocalStorageAvailable()) {\n return null;\n }\n\n try {\n const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);\n const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);\n const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);\n\n if (!accessToken || !refreshToken) {\n return null;\n }\n\n return {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 3600000,\n };\n } catch (e) {\n console.error('[mero-react] Failed to get token from storage:', e);\n return null;\n }\n },\n\n async set(token: TokenData): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);\n localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);\n localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());\n } catch (e) {\n console.error('[mero-react] Failed to save token to storage:', e);\n }\n },\n\n async clear(): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);\n } catch (e) {\n console.error('[mero-react] Failed to clear token from storage:', e);\n }\n },\n};\n\n/**\n * Get the stored node URL\n */\nexport function getNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Set the node URL\n */\nexport function setNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.NODE_URL, url);\n}\n\n/**\n * Clear the node URL\n */\nexport function clearNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Get the node URL that minted the token bundle currently in the TokenStore.\n */\nexport function getTokenNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Record the node URL that minted the token bundle now in the TokenStore.\n */\nexport function setTokenNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);\n}\n\n/**\n * Clear the token bundle's node URL\n */\nexport function clearTokenNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Get the stored application ID\n */\nexport function getApplicationId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Set the application ID\n */\nexport function setApplicationId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);\n}\n\n/**\n * Clear the application ID\n */\nexport function clearApplicationId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Get the stored context ID\n */\nexport function getContextId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Set the context ID\n */\nexport function setContextId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);\n}\n\n/**\n * Clear the context ID\n */\nexport function clearContextId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Get the stored context identity\n */\nexport function getContextIdentity(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Set the context identity\n */\nexport function setContextIdentity(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);\n}\n\n/**\n * Clear the context identity\n */\nexport function clearContextIdentity(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Clear all mero-react storage\n */\nexport function clearAllStorage(): void {\n if (!isLocalStorageAvailable()) return;\n Object.values(STORAGE_KEYS).forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n","import React, {\n createContext,\n useContext,\n useState,\n useEffect,\n useCallback,\n useRef,\n useMemo,\n} from 'react';\nimport {\n MeroJs,\n LocalStorageTokenStore,\n parseAuthCallback,\n buildAuthLoginUrl,\n AuthRevokedError,\n HTTPError,\n} from '@calimero-network/mero-js';\nimport { AppMode } from '../types';\nimport { CloudClient } from '@calimero-network/mero-js';\nimport type { AdminApiClient, AuthCallbackResult, MeroClient, TokenStore } from '@calimero-network/mero-js';\nimport { createNodeAdmin } from '@calimero-network/mero-js';\nimport { createAccountAdmin } from '@calimero-network/mero-js';\nimport { joinAsAccount } from '@calimero-network/mero-js';\nimport { foundDelegatedNamespace } from '@calimero-network/mero-js';\nimport { resolveTrustedNodeUrl } from '../auth/node-trust';\nimport { resolveTokenAdoption } from '../auth/token-adoption';\nimport {\n getNodeUrl,\n setNodeUrl,\n getTokenNodeUrl,\n setTokenNodeUrl,\n getApplicationId,\n setApplicationId,\n getContextId,\n setContextId,\n getContextIdentity,\n setContextIdentity,\n clearAllStorage,\n} from '../storage';\nimport type { MeroContextValue, MeroProviderConfig } from '../types';\n\nimport {\n buildDelegatedClient,\n clearDelegatedCredential,\n clearDelegatedSession,\n readDelegatedSession,\n listDelegatedContexts,\n readPinnedRelayNodeKey,\n learnRelayNodeKey,\n relayForContext,\n saveDelegatedCredential,\n saveDelegatedSession,\n type DelegatedAccountSession as DelegatedSession,\n} from '@calimero-network/mero-js';\nimport { resolveApplicationIdFromRegistry } from '@calimero-network/mero-js';\n\nconst MeroContext = createContext<MeroContextValue | null>(null);\n\n/** The registry an app's package is looked up in when none is configured; the account admin's default too. */\nconst DEFAULT_REGISTRY_URL = 'https://apps.calimero.network';\n\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Permission grants requested for the client token at login.\n *\n * Cores since 0.11.0-rc.9 default-deny admin-api routes the token holds no\n * scope for; cores >=0.11.0-rc.11 map the governance/blob/alias routes to the\n * client-grantable `namespace` / `group` / `blob` / `context:alias`\n * permissions, so app tokens must request them here or every workspace,\n * group, blob and context-alias call 403s.\n *\n * `context:list` is included even in single-context mode because every app\n * calls GET /admin-api/contexts/:id/identities-owned right after login, which\n * maps to a `context:list` requirement.\n *\n * `context:subscribe` is what `/sse`, `/sse/subscription` and `/ws` require\n * (core's `PermissionValidator`, `validator.rs`, maps all three to\n * `Context(Subscribe(Global))`). Without it every event stream an app opens is\n * refused `403` + `X-Auth-Error: permission_denied`, so the app renders, reads\n * and writes, and simply never receives a live update. Only `AppMode.Admin`\n * escaped, because `admin` covers every route.\n *\n * MEASURED against merod 0.11.0-rc.41 (build 88e323b): a client key minted with\n * the MultiContext list below minus `context:subscribe` gets `403` on\n * `GET /sse`; the same list with it gets `200`.\n *\n * `context:delete` is what `DELETE /admin-api/contexts/:id` requires\n * (`validator.rs`). An app that may create contexts may delete them, so\n * `useDeleteContext` works on a node instead of answering 403.\n *\n * Public: whatever mints a token for a mero-react app on its behalf (the\n * desktop's per-app key, admin-dashboard's, auth-frontend's allowlist) should\n * test against this rather than a hand copy. Three copies went without\n * `context:delete` and every app's context delete answered 403.\n */\nexport function getPermissionsForMode(mode: AppMode): string[] {\n switch (mode) {\n case AppMode.SingleContext:\n return [\n 'context:execute',\n 'context:list',\n 'context:subscribe',\n 'application:list',\n 'blob',\n 'context:alias',\n ];\n case AppMode.MultiContext:\n return [\n 'context:create',\n 'context:delete',\n 'context:list',\n 'context:execute',\n 'context:subscribe',\n 'application:list',\n 'namespace',\n 'group',\n 'blob',\n 'context:alias',\n ];\n case AppMode.Admin:\n return ['admin'];\n default:\n throw new Error(`Unsupported application mode: ${mode}`);\n }\n}\n\nexport interface MeroProviderProps extends MeroProviderConfig {\n children: React.ReactNode;\n}\n\nexport function MeroProvider({\n children,\n mode,\n packageName,\n packageVersion,\n registryUrl,\n cloudBaseUrl,\n timeoutMs = 30000,\n allowedNodeUrls,\n tokenStore: tokenStoreProp,\n}: MeroProviderProps) {\n const tokenStore = useMemo<TokenStore>(\n () => tokenStoreProp ?? new LocalStorageTokenStore(),\n [tokenStoreProp],\n );\n const [mero, setMero] = useState<MeroJs | MeroClient | null>(null);\n /**\n * The delegated record, or null for the node-login path.\n *\n * Read from storage in the initializer rather than an effect: a reload of a\n * delegated tab should render connected, not flash the connect button and\n * then replace it.\n */\n const [delegated, setDelegated] = useState<DelegatedSession | null>(() =>\n readDelegatedSession(),\n );\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n const [isOnline, setIsOnline] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [nodeUrl, setNodeUrlState] = useState<string | null>(() => getNodeUrl());\n const [applicationId, setApplicationIdState] = useState<string | null>(\n () => getApplicationId() || null,\n );\n const [contextId, setContextIdState] = useState<string | null>(() => getContextId());\n const [contextIdentity, setContextIdentityState] = useState<string | null>(() => getContextIdentity());\n\n const meroRef = useRef<MeroJs | null>(null);\n // Guards the SSE 401 recovery below, so a burst of reconnect failures can't\n // stack concurrent validate/refresh attempts over one single-use refresh token.\n const recoveringRef = useRef(false);\n\n // Parse auth callback ONCE in a ref (StrictMode-safe: refs persist across unmount/remount)\n const callbackRef = useRef<AuthCallbackResult | null | undefined>(undefined);\n if (callbackRef.current === undefined && isBrowser) {\n callbackRef.current = parseAuthCallback(window.location.href);\n }\n\n const createMeroInstance = useCallback(\n (url: string): MeroJs => {\n if (meroRef.current) {\n meroRef.current.close();\n }\n const instance = new MeroJs({\n baseUrl: url,\n tokenStore,\n timeoutMs,\n });\n meroRef.current = instance;\n return instance;\n },\n [timeoutMs, tokenStore],\n );\n\n const checkAuth = useCallback(\n async (instance: MeroJs): Promise<boolean> => {\n // Validate the session via /auth/validate (signature, revocation, node\n // binding — no permission requirement) instead of probing\n // GET /admin-api/contexts. Since core 0.11.0-rc.9 the node enforces\n // token permission scopes, and /admin-api/contexts requires Global\n // `context:list` — which single-context tokens (execute-only) and\n // app-scoped tokens don't hold, so probing it 403'd valid sessions and\n // bounced every app straight back to the login page.\n // Through the client: it reads back only the bundle its own node issued.\n const accessToken = instance.getTokenData()?.access_token;\n if (!accessToken) return false;\n\n const validate = async (token: string): Promise<boolean> => {\n try {\n const { valid } = await instance.auth.validateToken(token);\n return valid;\n } catch {\n return false;\n }\n };\n\n if (await validate(accessToken)) return true;\n\n // An expired access token does NOT mean the session is over: refresh\n // tokens last 30 days against core's 1-hour access TTL, so on any reload\n // more than an hour after login we land here holding a perfectly good\n // refresh token.\n //\n // `validateToken` has in fact already spent it. It pins the token under\n // test into an explicit `Authorization` header, and mero-js's init\n // headers override the transport's own token (mero-js\n // http-client/web-client.js `buildHeaders`). So the 401 + `x-auth-error:\n // token_expired` trips the transport's refresh hook — rotating the stored\n // bundle — and then the retry re-sends the SAME stale header, 401s again,\n // and reports `valid: false`. The session was silently renewed and thrown\n // away, and the app bounced to login; a second reload would then \"fix\"\n // itself, which is exactly how this reads as a random logout.\n //\n // So: re-read the token, and if the transport rotated it underneath us,\n // judge the session on the token we ACTUALLY hold now. We never call\n // /auth/refresh ourselves — doing so would race mero-js's single-flight\n // lock over a single-use refresh token and get the whole family revoked\n // (calimero-network/core#3083).\n const rotated = instance.getTokenData()?.access_token;\n if (!rotated || rotated === accessToken) return false;\n return validate(rotated);\n },\n [],\n );\n\n const connectToNode = useCallback(\n (url: string) => {\n if (!isBrowser) return;\n setNodeUrl(url);\n setNodeUrlState(url);\n\n const callbackUrl = new URL(window.location.href);\n callbackUrl.hash = '';\n\n const loginUrl = buildAuthLoginUrl(url, {\n callbackUrl: callbackUrl.toString(),\n permissions: getPermissionsForMode(mode),\n mode,\n packageName,\n packageVersion,\n registryUrl,\n });\n\n window.location.href = loginUrl;\n },\n [mode, packageName, packageVersion, registryUrl],\n );\n\n /**\n * Adopt a delegated connection.\n *\n * No redirect and nothing to await: a delegated client carries its own\n * credential on every request, so it is usable the moment it is built. The\n * record is persisted first so a reload finds it.\n */\n const connectWithAccount = useCallback((session: DelegatedSession) => {\n saveDelegatedSession(session);\n // Kept as a credential too, so the identity outlives the connection. A relay\n // can be lost without the certificate being lost — the fleet row goes stale,\n // or the record is cleared — and re-enrolling to recover a key this tab still\n // holds would be a new device for no reason.\n const { account, credential, deviceSecret } = session;\n saveDelegatedCredential({ account, credential, deviceSecret });\n setDelegated(session);\n }, []);\n\n const logout = useCallback(() => {\n if (meroRef.current) {\n meroRef.current.clearToken();\n meroRef.current.close();\n }\n // Always clear the token store, even when not connected (meroRef is null) —\n // otherwise the access/refresh tokens persist in storage after logout.\n tokenStore.clear();\n clearAllStorage();\n clearDelegatedSession();\n // The certificate goes too. Logging out of an account and leaving its device\n // key in storage would leave the next visitor able to bootstrap as it from\n // any invitation they hold.\n clearDelegatedCredential();\n setDelegated(null);\n setMero(null);\n setIsAuthenticated(false);\n setNodeUrlState(null);\n setApplicationIdState(null);\n setContextIdState(null);\n setContextIdentityState(null);\n meroRef.current = null;\n }, [tokenStore]);\n\n /**\n * Install the relay client for a delegated record.\n *\n * Separate effect from the node-login initializer below, and the two are\n * mutually exclusive: a delegated connection has no token to adopt, no node\n * URL to validate and no callback to consume, so running that machinery for\n * it would only find nothing and log out.\n */\n useEffect(() => {\n if (!delegated) return;\n // Re-keys the warrant-nonce ledger when the chosen context changes, which is\n // why `contextId` is a dependency. The context itself is NOT set from here —\n // it comes from storage (the initializer above) or from whatever the app's\n // own picker selected, exactly as on the node-login path.\n // The open context's own relay: an account's namespaces may each be served\n // by a different one. Unknown (no context yet, or one not listed yet) →\n // the session's relay, which is the one that admitted it most recently.\n const relayUrl =\n (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;\n const routed = { ...delegated, relayUrl };\n const client = buildDelegatedClient(routed, contextId);\n // A relay whose node key is not known yet: learn it before handing the app a\n // client. Published without it, the app's subscriptions open `/sse` on a\n // client with no session, which a hosted relay refuses with a 401 — the\n // client rebuilt a moment later reconnects, but the refusal is noise.\n const awaitingKey = Boolean(client && relayUrl && !readPinnedRelayNodeKey(relayUrl));\n // `null` when the account holds no relay yet, and the session is still\n // authenticated. Being signed in is how an account comes to be invited, so a\n // relay cannot be a precondition for it — and `mero: null` is what makes a\n // write say \"there is no relay\" instead of failing against a guessed node.\n if (!awaitingKey) setMero(client);\n setIsAuthenticated(true);\n setIsOnline(true);\n setNodeUrlState(relayUrl);\n setIsLoading(awaitingKey);\n\n /*\n * Which application this tab is for, asked rather than told.\n *\n * The node-login path is handed an `applicationId` by the auth callback. A\n * delegated tab has no callback, so it had none — and an app's context\n * picker that filters on it (correctly: \"I cannot tell which are mine\" and\n * \"all of them are mine\" are different answers) then had nothing to filter\n * with and stayed empty forever. That, not the relay, was the last reason\n * anyone had to type a context id in.\n *\n * `admin.getContexts()` on this client is caller-scoped through the request\n * proof — it answers this ACCOUNT's own contexts, each naming its\n * application — so the id is derivable from the credential already held.\n *\n * Not persisted with `setApplicationId`: it is derived from a cheap,\n * authoritative read, so caching it would only create a value to invalidate\n * when the account's contexts change.\n */\n let active = true;\n const stop = new AbortController();\n (async () => {\n // No relay, so no client and nothing to ask. A brand-new account is a\n // member of nothing — there are no contexts to derive an application from,\n // which is exactly the state an invitation changes.\n if (!client || !relayUrl) return;\n // Admin reads and events need a session the relay accepts, which needs\n // its node key. Pinned, or learned from the relay's attestation; learned\n // now, the client is rebuilt so its session and events use it too. With\n // neither, a hosted relay answers the proof-only path with 401: do not ask.\n //\n // Learning it can fail on the way — the release mirror timing out, the\n // relay not answering — and one such failure used to leave the whole\n // session unsigned: every read a 401 until a reload. So it is waited out,\n // with backoff, and the client stays unpublished (and the session\n // loading) meanwhile: handing the app a client now would only send its\n // reads unsigned, to be refused as if the account had no access.\n if (awaitingKey) {\n const nodeKey = await learnRelayNodeKey(relayUrl, { signal: stop.signal });\n if (!active) return;\n // `null` here is a refusal: the relay's quote did not verify, and asking\n // again would get the same answer. The client still writes (intents\n // carry their own warrant); only admin reads and events need the\n // session a verified key enables, and those stay off.\n setMero(nodeKey ? (buildDelegatedClient(routed, contextId) ?? client) : client);\n setIsLoading(false);\n if (!nodeKey) return;\n }\n // The app names its application by `packageName`, and that decides. The\n // account's contexts do not: one account is used across apps, so a\n // kv-store tab may well see chess's contexts — two applications, or only\n // another app's. Reading the id off them would leave it null when several\n // appear and, worse, point this app at another's contract when exactly\n // one foreign one does (founding a namespace signs `TargetApplicationSet`\n // with that id). The id is a pure function of the package and its\n // publisher's signing key (core's `ApplicationId::for_bundle`), both of\n // which the registry lists, so it is derived from there — also for a\n // brand-new account with no contexts, which has to found its first\n // namespace from somewhere. Should the registry not answer, warn once and\n // fall back to the contexts below, so an app without registry access\n // keeps working as before.\n if (packageName) {\n try {\n const { applicationId: derived } = await resolveApplicationIdFromRegistry(\n registryUrl ?? DEFAULT_REGISTRY_URL,\n packageName,\n );\n if (!active) return;\n setApplicationIdState(derived);\n return;\n } catch (e) {\n // Once: a registry that did not answer is not asked again until the\n // session or its chosen context changes.\n console.warn(`[mero-react] could not learn the application id of ${packageName} from the registry`, e);\n if (!active) return;\n }\n }\n try {\n // Without a `packageName` (or with a registry that did not answer), the\n // contexts are the only thing that names an application. Across every\n // relay this account uses, each answering for itself.\n const contexts = await listDelegatedContexts(delegated);\n if (!active) return;\n const apps = [\n ...new Set((contexts ?? []).map((c) => c.applicationId).filter(Boolean)),\n ];\n if (apps.length === 1) {\n setApplicationIdState(apps[0]);\n }\n // More than one, and this stays null ON PURPOSE — only without a\n // `packageName`, which would have decided above. A tab holds one\n // application's UI and nothing here says which — the account simply has\n // contexts for several. Picking the first would silently point the app at\n // another app's contract, which answers none of its methods; admitting\n // \"I don't know\" leaves the app's own \"waiting for this session to report\n // which application\" message honest, and a chooser is the follow-up.\n // Zero contexts and no `packageName`: nothing to derive from, null too.\n } catch {\n // Left null, and deliberately not surfaced as a connection failure. The\n // writes work — every one carries its own warrant — and a read that did\n // not answer must not unwind a connection that did.\n }\n })();\n\n return () => {\n active = false;\n stop.abort();\n // `close` is a node-client concern; a relay client has nothing to tear\n // down, so do not reach for it.\n };\n }, [delegated, contextId, packageName, registryUrl]);\n\n // Initialization effect\n useEffect(() => {\n // A delegated tab is already connected by the effect above. This whole\n // path — callback parsing, token adoption, node-URL trust, /auth/validate —\n // describes a session the delegated client does not have.\n if (delegated) return;\n\n let active = true;\n\n const init = async () => {\n const callback = callbackRef.current;\n let nodeFromCallback: string | null = null;\n let instance: MeroJs | null = null;\n\n if (callback) {\n // Read BEFORE the callback overwrites either of them.\n // - initiatedNodeUrl: the node login was initiated with — the trust anchor.\n // - tokenNodeUrl: the node that minted the bundle currently in the store.\n // They differ exactly when the user is switching nodes: `connectToNode`\n // points NODE_URL at the *target* node before redirecting, while the store\n // still holds the *previous* node's bundle. Falling back to the initiated\n // node keeps sessions that predate TOKEN_NODE_URL working.\n const initiatedNodeUrl = getNodeUrl();\n const tokenNodeUrl = getTokenNodeUrl() ?? initiatedNodeUrl;\n\n // The callback URL is attacker-influenceable, so validate its node_url\n // BEFORE storing tokens or connecting — otherwise a malicious node_url\n // would receive the freshly-minted tokens (exfiltration).\n const { url, rejected } = resolveTrustedNodeUrl({\n candidate: callback.nodeUrl,\n initiated: initiatedNodeUrl,\n allowedNodeUrls,\n });\n\n // Always strip the callback params (tokens + node_url) from the address\n // bar and consume the parsed callback, whatever the trust outcome.\n if (isBrowser) {\n window.history.replaceState({}, '', window.location.pathname + window.location.search);\n }\n callbackRef.current = null;\n\n if (rejected) {\n // Untrusted node_url — likely a token-exfiltration attempt. Drop the\n // callback's tokens, but DON'T return: fall through to restore any\n // existing session from storage so a tampered callback can't log a\n // legitimately authenticated user out.\n console.error(\n '[MeroProvider] OAuth callback node_url is not trusted (it does not match the node ' +\n 'login was initiated with, nor `allowedNodeUrls`). Ignoring the callback; no tokens stored.',\n );\n } else if (url) {\n // Trusted node → the callback's tokens MAY be persisted. Whether they\n // SHOULD be is a separate question: refresh tokens are single-use since\n // core 0.11.0 (calimero-network/core#3083), so blindly writing the hash\n // bundle over a bundle mero-js has already rotated resurrects a consumed\n // refresh token — the node reads that as theft (`x-auth-error:\n // token_reuse`) and revokes the entire token family, hard-logging out\n // every holder. Adopt only a fresh, newer, or different-node bundle, and\n // merge rather than replace so an access-only hash (hosts are dropping\n // `refresh_token` from the hash) can never strip a live refresh token.\n // Written through the client, which binds the bundle to its node.\n instance = createMeroInstance(url);\n const decision = resolveTokenAdoption({\n callbackAccessToken: callback.accessToken,\n callbackRefreshToken: callback.refreshToken,\n callbackNodeUrl: url,\n stored: instance.getTokenData(),\n storedNodeUrl: tokenNodeUrl,\n });\n\n if (decision.adopt) {\n instance.setTokenData(decision.tokens);\n setTokenNodeUrl(url);\n } else {\n console.warn(\n '[MeroProvider] Ignoring the SSO callback token bundle: it is stale (not newer than ' +\n 'the tokens already stored for this node). Adopting it would replay an already-rotated ' +\n 'refresh token, which the node revokes the whole token family for.',\n );\n }\n\n if (callback.applicationId) {\n setApplicationId(callback.applicationId);\n if (active) setApplicationIdState(callback.applicationId);\n }\n if (callback.contextId) {\n setContextId(callback.contextId);\n if (active) setContextIdState(callback.contextId);\n }\n if (callback.contextIdentity) {\n setContextIdentity(callback.contextIdentity);\n if (active) setContextIdentityState(callback.contextIdentity);\n }\n\n setNodeUrl(url);\n if (active) setNodeUrlState(url);\n nodeFromCallback = url;\n }\n // url === null && !rejected → callback had no node to bind to; ignore it.\n }\n\n const savedUrl = nodeFromCallback || getNodeUrl();\n if (!savedUrl) {\n if (active) setIsLoading(false);\n return;\n }\n\n instance ??= createMeroInstance(savedUrl);\n const authed = await checkAuth(instance);\n\n if (!active) return;\n\n if (authed) {\n setMero(instance);\n setIsAuthenticated(true);\n setIsOnline(true);\n } else if (nodeFromCallback) {\n setMero(instance);\n }\n\n setIsLoading(false);\n };\n\n init().catch((err) => {\n console.error('[MeroProvider] Initialization failed:', err);\n if (active) setIsLoading(false);\n });\n\n return () => {\n active = false;\n };\n }, [createMeroInstance, checkAuth, allowedNodeUrls, delegated]);\n\n // SSE connection for online/offline detection — no polling.\n useEffect(() => {\n if (!isAuthenticated || !meroRef.current) return;\n\n let active = true;\n const sse = meroRef.current.events;\n\n const onConnect = () => { if (active) setIsOnline(true); };\n const onError = (err: Error) => {\n if (!active) return;\n setIsOnline(false);\n\n // A delegated stream has no token to renew. It is authenticated by a\n // request proof the device key signs for each connect, so a 401 here is\n // not an expiry the recovery below can fix — and that recovery ends in\n // `logout()`, which would tear down a connection whose credential is\n // still perfectly good. Report offline and let the client reconnect.\n if (delegated) return;\n\n // ── Which stream failures are worth acting on ──────────────────────────\n //\n // This used to be `if (!err.message.includes('401')) return;`, and the\n // comment under it explained that mero-js threw a bare\n // `SSE connection failed: <status>`, so nothing better was available.\n // That stopped being true in mero-js 19.14.1 (#166): the SSE path now\n // throws the same typed errors the request path does, carrying the\n // status and the `x-auth-error` header.\n //\n // Matching on '401' was not merely coarse, it was aimed at the wrong\n // number. Core answers a dead or under-scoped token on `/sse` with\n // **403**, not 401 — `token_expired` is the only 401 a stream sees. So\n // every failure that actually needed acting on was the one this gate\n // dropped, and the app sat at `isOnline = false` with no way back and no\n // prompt to log in again.\n //\n // Three cases now, because they need three different answers.\n\n // 1. The token family is gone (403 `token_revoked`, or a 401\n // `token_reuse`). mero-js has already STOPPED reconnecting — every\n // retry re-sends the same dead credential — so nothing will reopen\n // this stream, and there is no refresh token left to spend either.\n if (err instanceof AuthRevokedError) {\n logout();\n return;\n }\n\n if (err instanceof HTTPError && err.status === 403) {\n // 2. The token is live but was minted without `context:subscribe`.\n // Core requires that grant for `/sse`, `/sse/subscription` and\n // `/ws`, and the grant set is baked in at MINT time — so a refresh\n // re-issues the same unusable token and the stream 403s again,\n // forever. mero-react 9.1.2 (#73) fixed what we ASK for; a client\n // key minted before it can only be replaced by a fresh login.\n // `checkAuth` would return true here and reconnect us into that\n // loop, which is why this case must not go through it.\n if (err.headers?.get('x-auth-error') === 'permission_denied') {\n console.warn(\n '[MeroProvider] This session cannot open an event stream ' +\n '(403 permission_denied): its token predates the context:subscribe ' +\n 'grant. Logging out — a fresh login mints a key that can subscribe.',\n );\n logout();\n return;\n }\n // 3. Any other 403 is core refusing this caller for a reason a new\n // token would not change — \"Forbidden: not the session owner\". Not\n // an auth-token problem, so do not spend the session on it.\n return;\n }\n\n // A 401 is NOT proof the session is over, and it used to be treated as\n // such: `logout()` wipes the token store, so an expired access token cost\n // the user their still-valid 30-day refresh token and forced a real\n // re-login.\n //\n // The stream authenticates only at connect time (an open stream survives\n // expiry), so this fires on the first reconnect after the access token\n // ages out — a sleep/wake, a network blip, a PWA resume, a node restart.\n // Routine events, all of them. Ask `checkAuth`, which recovers a\n // merely-expired token via the transport's refresh and returns false only\n // when the session is genuinely dead.\n //\n // The string check stays as a fallback: not every caller is on 19.14.1,\n // and an older mero-js still reports this as `SSE connection failed: 401`.\n const status = err instanceof HTTPError ? err.status : null;\n if (status !== 401 && !err.message.includes('401')) return;\n\n if (recoveringRef.current) return;\n recoveringRef.current = true;\n void (async () => {\n try {\n const instance = meroRef.current;\n if (!instance) return;\n if (await checkAuth(instance)) {\n // Renewed. mero-js's `onTokenRefresh` hook has already updated the\n // instance's in-memory token, so the SseClient's `getAuthToken`\n // hands the reconnect the new one.\n if (active) await instance.events.connect().catch(() => {});\n return;\n }\n if (active) logout();\n } finally {\n recoveringRef.current = false;\n }\n })();\n };\n\n sse.on('connect', onConnect);\n sse.on('error', onError);\n sse.connect().catch(() => { if (active) setIsOnline(false); });\n\n return () => {\n active = false;\n sse.off('connect', onConnect);\n sse.off('error', onError);\n };\n // `checkAuth` and `logout` are both useCallback-stable (`logout` closes over\n // the memoized `tokenStore`), so listing them does not re-subscribe the stream.\n // Not for a delegated client: this stream is opened from the node client's\n // own `events`, and a relay client observes only when it was given the\n // relay's node key — which `buildDelegatedClient` wires up itself.\n }, [isAuthenticated, mero, checkAuth, logout, delegated]);\n\n // The admin API an app writes against, whatever the session, with the same\n // calls and results on both: on a node, the node's client (installing the\n // app when a namespace needs it); on an account, the account admin, whose\n // reads go to the relay and whose writes go through it as delegated ops.\n // Never null for a signed-in account: one with no relay yet is a member of\n // nothing, and says so, rather than leaving the app to special-case it.\n const admin = useMemo<AdminApiClient | null>(() => {\n const app = { packageName, packageVersion, registryUrl };\n if (delegated !== null) {\n // No relay at all: the empty admin. A relay still being connected to (its\n // node key not learned yet) is loading, not empty — null until it is up.\n // `admin.joinNamespace` redeems for the account, relay or not: the join is\n // how it gets one, and the session moves onto that relay once it is in.\n const deps = {\n join: (namespaceId: string, invitation: Parameters<typeof joinAsAccount>[2]) =>\n joinAsAccount(delegated, namespaceId, invitation, { cloudBaseUrl, onJoined: connectWithAccount }),\n // Founding enables HA on the same cloud the joins resolve relays from.\n found: (session: Parameters<typeof foundDelegatedNamespace>[0], req: Parameters<typeof foundDelegatedNamespace>[1]) =>\n foundDelegatedNamespace(session, req, { cloudBaseUrl }),\n // Invitations are checked against the routing their claimants will use.\n routing: (namespaceId: string) =>\n new CloudClient({\n cloudBaseUrl,\n routingCredential: { credential: delegated.credential, deviceSecret: delegated.deviceSecret },\n }).getNamespaceRouting(namespaceId),\n };\n if (delegated.relayUrl === null) return createAccountAdmin({ session: delegated, read: null, app }, deps);\n if (!mero) return null;\n return createAccountAdmin(\n { session: delegated, read: (mero as unknown as { admin: AdminApiClient }).admin, app },\n deps,\n );\n }\n const nodeAdmin = (mero as { admin?: AdminApiClient } | null)?.admin;\n return nodeAdmin ? createNodeAdmin({ admin: nodeAdmin, app }) : null;\n }, [mero, delegated, packageName, packageVersion, registryUrl, cloudBaseUrl, connectWithAccount]);\n\n const contextValue = useMemo<MeroContextValue>(\n () => ({\n mero,\n isAuthenticated,\n isOnline,\n nodeUrl,\n applicationId,\n contextId,\n contextIdentity,\n connectToNode,\n connectWithAccount,\n isDelegated: delegated !== null,\n admin,\n can: delegated !== null\n // An account founds a namespace through its relay and gives it this\n // app's application (core#4269), possible only when the app names its\n // registry package, and signs its own invitations (mero-js #221). Only\n // upgrades stay a node's: just a group's first application choice can\n // go through a relay.\n ? { createNamespace: Boolean(packageName), createContext: true, invite: true, upgrade: false }\n : { createNamespace: true, createContext: true, invite: true, upgrade: true },\n app: { packageName, packageVersion, registryUrl },\n cloudBaseUrl,\n logout,\n isLoading,\n }),\n [mero, admin, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl, cloudBaseUrl],\n );\n\n return (\n <MeroContext.Provider value={contextValue}>\n {children}\n </MeroContext.Provider>\n );\n}\n\nexport function useMero(): MeroContextValue {\n const context = useContext(MeroContext);\n if (!context) {\n throw new Error('useMero must be used within a MeroProvider');\n }\n return context;\n}\n\nexport { MeroContext };\n","/**\n * CalimeroLogo - the official Calimero emblem.\n *\n * Uses `currentColor` for fills so the consumer can theme it with `color`,\n * a `style.color` override, or by passing `color` directly.\n */\n\nimport React from 'react';\n\nexport interface CalimeroLogoProps extends React.SVGAttributes<SVGSVGElement> {\n /** Width / height shorthand (applied to both). Default: 24. */\n size?: number | string;\n}\n\nexport function CalimeroLogo({\n size = 24,\n color,\n style,\n ...rest\n}: CalimeroLogoProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 193 193\"\n fill={color ?? 'currentColor'}\n style={style}\n xmlns=\"http://www.w3.org/2000/svg\"\n aria-hidden=\"true\"\n {...rest}\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M13.5969 23.2235C63.4924 -4.81833 123.53 2.55678 148.374 10.0273C153.006 11.4201 155.606 16.2198 154.181 20.7478C152.757 25.2758 147.846 27.8173 143.214 26.4245C120.866 19.7045 66.3988 13.3369 22.3442 38.0961C21.3748 38.6409 20.8298 39.6384 20.8808 40.6778C22.5544 74.7376 40.6646 139.735 103.059 173.709C107.293 176.015 108.813 181.238 106.455 185.377C104.096 189.516 98.7523 191.002 94.5186 188.696C24.7767 150.721 5.18199 78.7606 3.35124 41.5008C2.98177 33.9812 6.96683 26.9496 13.5969 23.2235Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M180.214 22.5271C185.054 22.2785 189.183 25.9121 189.437 30.6429C192.776 92.7591 159.782 138.316 138.517 157.587C133.185 162.419 125.221 164.303 117.934 161.241C102.817 154.887 88.1835 141.52 76.3001 128.189C64.2403 114.66 54.1712 100.2 48.3006 90.492C45.8345 86.4139 47.2173 81.1537 51.3891 78.743C55.561 76.3323 60.9421 77.684 63.4082 81.7621C68.803 90.6832 78.2588 104.272 89.5315 116.919C100.981 129.763 113.488 140.698 124.866 145.48C125.179 145.612 125.851 145.671 126.586 145.006C145.206 128.132 174.903 87.1988 171.912 31.5431C171.657 26.8122 175.374 22.7756 180.214 22.5271Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M85.9137 55.4487C70.263 57.0264 57.2007 60.7039 50.4014 63.4262C45.9168 65.2218 40.7922 63.1236 38.9553 58.7397C37.1184 54.3559 39.2649 49.3464 43.7495 47.5508C52.2083 44.164 66.9167 40.1173 84.1135 38.3837C101.323 36.649 121.62 37.1693 140.947 43.4423C149.244 46.1351 155.088 53.9217 154.482 62.8728C153.225 81.429 144.514 100.403 127.158 122.145C124.177 125.88 118.663 126.546 114.842 123.631C111.021 120.717 110.341 115.327 113.322 111.592C129.481 91.3484 136.032 75.6017 136.971 61.7394C137.02 61.0029 136.547 60.0904 135.417 59.7238C119.18 54.4537 101.552 53.8722 85.9137 55.4487Z\"\n />\n </svg>\n );\n}\n\nexport default CalimeroLogo;\n","/**\n * Theme tokens for mero-react components.\n *\n * Defaults match the green palette used across Calimero apps (admin-dashboard,\n * tauri-app, app-registry). Pass a partial `MeroTheme` to `ConnectButton` or\n * `LoginModal` to override any token.\n */\n\nimport type { CSSProperties } from 'react';\n\nexport interface MeroTheme {\n /** Primary accent / CTA color */\n primary?: string;\n /** Primary accent on hover */\n primaryHover?: string;\n /** Text color rendered on top of `primary` (e.g. inside the Connect button when connected) */\n primaryText?: string;\n /** Main surface color (modal background, button background) */\n background?: string;\n /** Secondary surface color (input fields, info chips) */\n backgroundSecondary?: string;\n /** Tertiary surface color (subtle elevation) */\n backgroundTertiary?: string;\n /** Border color */\n border?: string;\n /** Primary text color */\n text?: string;\n /** Muted / secondary text color */\n textSecondary?: string;\n /** Error / danger color */\n error?: string;\n /** Modal backdrop color */\n overlay?: string;\n /** Border radius (any CSS length) */\n radius?: string;\n}\n\nexport type ResolvedMeroTheme = Required<MeroTheme>;\n\nexport const defaultMeroTheme: Readonly<ResolvedMeroTheme> = Object.freeze({\n primary: '#a5ff11',\n primaryHover: '#8ed40d',\n primaryText: '#0d1117',\n background: '#0d1117',\n backgroundSecondary: '#161b22',\n backgroundTertiary: '#1c2128',\n border: '#30363d',\n text: '#e6edf3',\n textSecondary: '#8b949e',\n error: '#ff6b6b',\n overlay: 'rgba(0, 0, 0, 0.75)',\n radius: '8px',\n});\n\n/**\n * Merge a partial theme with the defaults.\n *\n * Filtering rules — values that fall back to the default:\n * - `undefined` (the prop key wasn't set, or was set to `undefined`)\n * - empty string `''`\n * - whitespace-only strings (e.g. `' '`)\n *\n * These are dropped because they're invalid CSS and would produce\n * invisible elements (transparent backgrounds, missing borders, etc.).\n * If you genuinely want the browser default for a token, omit the key\n * from the theme prop rather than passing an empty string.\n *\n * Any other non-empty string is forwarded as-is — CSS syntax itself\n * is NOT validated.\n */\nexport function resolveMeroTheme(theme?: MeroTheme): ResolvedMeroTheme {\n if (!theme) return { ...defaultMeroTheme };\n const filtered = Object.fromEntries(\n Object.entries(theme).filter(\n ([, v]) => v !== undefined && typeof v === 'string' && v.trim() !== '',\n ),\n ) as Partial<MeroTheme>;\n return { ...defaultMeroTheme, ...filtered };\n}\n\n/**\n * Single source of truth mapping each `MeroTheme` token name to the CSS\n * custom-property name it surfaces as. Used by `themeToCssVars` to emit the\n * inline-style map and by component code (e.g. `LoginModal`) to read the\n * variable in inline styles via `var(--mero-*, fallback)`.\n *\n * Adding a new token? Add it here, in `MeroTheme`, and in `defaultMeroTheme`,\n * and the rest of the system picks it up automatically.\n */\nexport const MERO_CSS_VARS: Record<keyof MeroTheme, string> = {\n background: '--mero-bg',\n backgroundSecondary: '--mero-bg-secondary',\n backgroundTertiary: '--mero-bg-tertiary',\n text: '--mero-text',\n textSecondary: '--mero-text-secondary',\n primary: '--mero-accent',\n primaryHover: '--mero-accent-hover',\n primaryText: '--mero-on-primary',\n border: '--mero-border',\n error: '--mero-error',\n overlay: '--mero-overlay',\n radius: '--mero-radius',\n};\n\n/**\n * Build a `style` object that exposes a resolved theme as CSS variables, so\n * descendant CSS rules (e.g. those in `styles.css`) pick up the overrides.\n */\nexport function themeToCssVars(theme: ResolvedMeroTheme): CSSProperties {\n const vars: Record<string, string> = {};\n for (const key of Object.keys(MERO_CSS_VARS) as Array<keyof MeroTheme>) {\n vars[MERO_CSS_VARS[key]] = theme[key];\n }\n return vars as CSSProperties;\n}\n\n/**\n * Returns a `var(--mero-*, fallback)` reference for a theme token, suitable\n * for inline styles in portal-rendered components where descendant CSS\n * variables also need to support global `:root` overrides.\n */\nexport function cssVar(theme: ResolvedMeroTheme, key: keyof MeroTheme): string {\n return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;\n}\n","/**\n * AccountSignInPanel — the Cloud tab of the connect dialog.\n *\n * Presentational only: the button, what pressing it does, and whatever the last\n * enrolment had to say. The flow itself is {@link useAccountEnrolment}; this\n * renders its outputs, so it can sit inside `LoginModal` without the modal\n * knowing anything about device keys or wallets.\n *\n * The copy is `ConnectButtonAccount`'s, unchanged.\n */\n\nimport { useMemo } from 'react';\nimport { cssVar, resolveMeroTheme, type MeroTheme } from '../theme';\n\nexport interface AccountSignInPanelProps {\n /** Start enrolment — normally `useAccountEnrolment().goToWallet`. */\n onEnrol: () => void;\n /** What the last enrolment had to say (an error, or \"nowhere to write yet\"). */\n note?: string | null;\n /** The wallet enrolment goes to. Shown only when `customWallet`. */\n walletUrl?: string;\n /** Whether `walletUrl` is an override rather than the hosted wallet. */\n customWallet?: boolean;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n}\n\nexport function AccountSignInPanel({\n onEnrol,\n note,\n walletUrl,\n customWallet = false,\n theme,\n}: AccountSignInPanelProps) {\n // Same tokens as LoginModal: `var(--mero-*, fallback)`, so the panel follows\n // the modal's inline variables and any global `:root` overrides.\n const styles = useMemo(() => {\n const t = resolveMeroTheme(theme);\n const radius = cssVar(t, 'radius');\n const error = cssVar(t, 'error');\n return {\n root: { display: 'flex', flexDirection: 'column' as const, gap: '1rem' },\n info: {\n color: cssVar(t, 'textSecondary'),\n textAlign: 'center' as const,\n fontSize: '0.875rem',\n margin: 0,\n },\n hint: {\n color: cssVar(t, 'textSecondary'),\n textAlign: 'center' as const,\n fontSize: '0.8125rem',\n margin: 0,\n opacity: 0.8,\n overflowWrap: 'anywhere' as const,\n },\n note: {\n color: error,\n backgroundColor: `color-mix(in srgb, ${error} 10%, transparent)`,\n border: `1px solid color-mix(in srgb, ${error} 30%, transparent)`,\n borderRadius: radius,\n padding: '0.75rem',\n fontSize: '0.875rem',\n textAlign: 'center' as const,\n margin: 0,\n },\n buttonGroup: { display: 'flex', justifyContent: 'center' },\n button: {\n padding: '0.75rem 2rem',\n borderRadius: radius,\n border: 'none',\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n backgroundColor: cssVar(t, 'primary'),\n color: cssVar(t, 'primaryText'),\n transition: 'all 0.15s ease',\n },\n };\n }, [theme]);\n\n return (\n <div\n className=\"mero-login-account\"\n style={styles.root}\n data-testid=\"account-sign-in-panel\"\n >\n {note && (\n <p\n className=\"mero-login-note\"\n style={styles.note}\n role=\"status\"\n data-testid=\"account-note\"\n >\n {note}\n </p>\n )}\n <p className=\"mero-login-info\" style={styles.info}>\n You will approve a device key on the wallet&apos;s own page, then come\n back here. The relay never sees your account root — only the\n certificate it signed.\n </p>\n <p className=\"mero-login-info\" style={styles.info}>\n That one certificate is all of it: finding the relay that serves your\n account, writing through it, reading your own contexts and namespaces,\n and live events. Nothing to paste in.\n </p>\n <div className=\"mero-login-actions\" style={styles.buttonGroup}>\n <button\n type=\"button\"\n className=\"mero-login-button mero-login-primary\"\n style={styles.button}\n onClick={onEnrol}\n data-testid=\"enrol-button\"\n >\n Enrol with your account\n </button>\n </div>\n {customWallet && walletUrl && (\n /* Shown only when an app overrode it, so a local rig can see at a\n glance that it is not enrolling against the hosted wallet. */\n <p className=\"mero-login-hint\" style={styles.hint}>\n Enrolling at <code>{walletUrl}</code>, not the hosted wallet.\n </p>\n )}\n </div>\n );\n}\n\nexport default AccountSignInPanel;\n","/**\n * useAccountEnrolment — the account sign-in flow, with no UI.\n *\n * Moved out of {@link ConnectButtonAccount} unchanged, so that `ConnectButton`'s\n * Cloud tab and `ConnectButtonAccount` share one copy of it: the device keys,\n * the redirect to the wallet, and the completion when the tab comes back.\n *\n * - `goToWallet` generates (or reuses) this tab's device keys, remembers a state\n * parameter, and leaves for the wallet.\n * - On the way back, the callback is read ONCE during render, the state is\n * checked against the one sent, the certificate is completed and saved, the\n * account's relays are looked up, and `connectWithAccount` connects.\n * - `note` is what the person should be told about that — an error, or a\n * connection with nowhere to write yet.\n * - `returning` is true when this page load carries an enrolment callback,\n * success or error, so a caller can show the place the note appears.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n CloudClient,\n completeDeviceEnrolment,\n deviceEnrolmentUrl,\n readEnrolmentCallback,\n type CloudAccountRelay,\n type DeviceEnrolmentCallback,\n} from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { saveDelegatedCredential } from '@calimero-network/mero-js';\n\n/** Where this tab's device keypair lives. */\nconst DEVICE_KEY = 'calimero.device';\n/** The state parameter this tab sent to the wallet, to check what comes back. */\nconst STATE_KEY = 'calimero.enrol.state';\n\n/**\n * The hosted wallet, which is a property of the platform rather than of any app.\n *\n * A default here and not a required prop: every app that enrols an account\n * enrols it at the same wallet, so making each one name it would be asking a\n * question with one answer — and an app that got it wrong would send a device key\n * to the wrong origin.\n */\nconst HOSTED_WALLET = 'https://wallet.cloud.calimero.network/account-enroll';\n\nconst hex = (b: ArrayBuffer | Uint8Array): string =>\n [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, '0')).join('');\n\n/**\n * The relay's own account, as the cloud names it beside the relay — the\n * executor a founding warrant must name.\n *\n * It is what lets a brand-new account found a namespace on the relay the cloud\n * just assigned it, with nothing typed in: a namespace that does not exist yet\n * cannot be asked who its relay is, and the account is a member of nothing that\n * could tell it. A server that does not name one (older ones omit the field)\n * leaves it `null`, and founding falls back to learning it from a namespace the\n * account is already in, as before.\n *\n * Read defensively, so this builds against a mero-js whose `CloudAccountRelay`\n * does not declare the field yet; mero-js already drops anything that is not\n * 64 lowercase hex, and this re-checks it rather than trusting the type.\n */\nfunction executorOf(relay: CloudAccountRelay): string | null {\n const value = (relay as { executorAccount?: unknown }).executorAccount;\n return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) ? value : null;\n}\n\n/**\n * Which of the account's relays to talk to, and what to say about it.\n *\n * Four outcomes, and the connection is made in ALL of them — what differs is\n * whether there is somewhere to write yet, and what the person is told:\n *\n * - a **fresh** relay with an address: use it, say nothing;\n * - only **stale** ones: use one anyway — the cloud reports `fresh` from a\n * heartbeat, and a heartbeat that lapsed a minute ago is not the same claim as\n * a node that is gone — but say so, because if the writes then fail this is\n * why;\n * - **rows with no address**: relays are assigned and the cloud has no URL for\n * any of them yet, which is the shape a node reports before its first\n * heartbeat lands. A wait.\n * - **no rows at all**: the normal state of a brand-new account. It is a member\n * of nothing, so nothing serves it.\n *\n * ## Why the last two connect instead of refusing\n *\n * This used to return \"not connected\" for both, and that was wrong in the case\n * it mattered most: you get invited *because* you are signed in, and accepting\n * an invitation is what earns a relay. Refusing to log the account in until it\n * had one locked a new account out of the only path that would give it one.\n *\n * Nothing is faked to achieve it. The session carries `relayUrl: null`, so no\n * client is built, `mero` stays `null`, and a write is told the relay is\n * missing rather than being sent to a guess.\n *\n * A current cloud assigns a relay to an account that has none on this very\n * read, so \"no rows at all\" is now mostly an older server's answer. The chosen\n * relay's `executorAccount` comes back with it, so the session can found a\n * namespace there straight away.\n */\nfunction chooseRelay(relays: readonly CloudAccountRelay[]): {\n relayUrl: string | null;\n executorAccount: string | null;\n note: string | null;\n} {\n const reachable = relays.filter(\n (r): r is CloudAccountRelay & { relayUrl: string } => typeof r.relayUrl === 'string' && r.relayUrl.length > 0,\n );\n const fresh = reachable.find((r) => r.fresh);\n if (fresh) return { relayUrl: fresh.relayUrl, executorAccount: executorOf(fresh), note: null };\n if (reachable.length > 0) {\n return {\n relayUrl: reachable[0].relayUrl,\n executorAccount: executorOf(reachable[0]),\n note:\n 'Connected through a relay whose last heartbeat has lapsed — it may not answer. It was ' +\n 'the only one with an address.',\n };\n }\n if (relays.length > 0) {\n return {\n relayUrl: null,\n executorAccount: null,\n note:\n `Signed in. Your account has ${relays.length} relay${relays.length === 1 ? '' : 's'} ` +\n 'assigned, but the cloud knows no address for any of them yet, so there is nowhere to ' +\n 'write through for the moment. Reads and writes resume as soon as one reports in.',\n };\n }\n return {\n relayUrl: null,\n executorAccount: null,\n note:\n 'Signed in, with nowhere to write yet: a new account is a member of nothing, so no node ' +\n 'serves it. Redeeming an invitation admits this account to a namespace and gives it a ' +\n 'relay — that is the normal first step, not an error.',\n };\n}\n\ninterface DeviceKeys {\n /** Ed25519 public key — what the certificate names, and what signs. */\n signPk: string;\n /** Ed25519 secret, hex seed. Signs warrants and the login statement. */\n signSk: string;\n /** X25519 public key — where wrapped scope keys are delivered. */\n kemPk: string;\n /** X25519 secret. Without it, anything delivered to `kemPk` is unreadable. */\n kemSk: string;\n}\n\n/**\n * This tab's device keys, generated once.\n *\n * TWO keypairs, for two jobs the `DeviceCert` names separately: an Ed25519 pair\n * that signs, and an X25519 pair that receives. Both halves of both are kept —\n * a public key certified without its private half is a key nothing can ever use.\n *\n * In `localStorage`, not session: they have to survive the redirect to the\n * wallet and back. A key regenerated on the way home would not match the\n * certificate the wallet just minted, and `completeDeviceEnrolment` would\n * rightly refuse it.\n */\nasync function deviceKeys(): Promise<DeviceKeys> {\n const had = localStorage.getItem(DEVICE_KEY);\n if (had) {\n const parsed = JSON.parse(had) as Partial<DeviceKeys>;\n // Keys minted before the agreement pair was real carry 32 random bytes as\n // `kemPk` and no `kemSk`. They cannot receive a wrapped scope key, ever, so\n // they are discarded rather than carried forward — the cost is re-enrolling\n // this device, which is cheap; the cost of keeping them is a delivery that\n // silently cannot be decrypted.\n if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {\n return parsed as DeviceKeys;\n }\n localStorage.removeItem(DEVICE_KEY);\n }\n\n const sign = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [\n 'sign',\n 'verify',\n ])) as CryptoKeyPair;\n\n let agree: CryptoKeyPair;\n try {\n agree = (await crypto.subtle.generateKey({ name: 'X25519' }, true, [\n 'deriveBits',\n ])) as CryptoKeyPair;\n } catch {\n // Better to refuse than to certify a delivery key with no private half:\n // enrolment would appear to succeed and the failure would surface much\n // later, as an undecryptable scope key.\n throw new Error(\n 'this browser cannot generate an X25519 key, so it cannot receive wrapped ' +\n 'scope keys. Chrome 133+ and Safari 17+ support it; enrolling without one ' +\n 'would certify a delivery key nothing holds the secret for.',\n );\n }\n\n // pkcs8 wraps the 32-byte seed behind a 16-byte header, for both curves.\n const keys: DeviceKeys = {\n signPk: hex(await crypto.subtle.exportKey('raw', sign.publicKey)),\n signSk: hex((await crypto.subtle.exportKey('pkcs8', sign.privateKey)).slice(16)),\n kemPk: hex(await crypto.subtle.exportKey('raw', agree.publicKey)),\n kemSk: hex((await crypto.subtle.exportKey('pkcs8', agree.privateKey)).slice(16)),\n };\n localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));\n return keys;\n}\n\n\n/**\n * Whether this page load is the one coming back from the wallet — a completed\n * enrolment or a declined one — WITHOUT consuming it.\n *\n * `useAccountEnrolment` reads the callback once and strips it from the address\n * bar, so a second reader finds nothing. That makes `returning` from the hook\n * unusable for the one decision that has to be taken before the hook runs: a\n * component that owns `LoginModal`'s `isOpen` and wants the dialog open on the\n * way back. This is the answer for it, as a `useState` initialiser:\n *\n * ```tsx\n * const [open, setOpen] = useState(isReturningFromWallet);\n * <LoginModal isOpen={open} ... /> // sources its own Cloud tab, lands on it\n * ```\n *\n * The parent's initialiser runs before the modal's hook reads the fragment, so\n * the two agree. `ConnectButton` needs none of this: it owns both.\n */\nexport function isReturningFromWallet(\n location: { hash: string } | undefined = typeof window === 'undefined' ? undefined : window.location,\n): boolean {\n if (!location) return false;\n const params = new URLSearchParams(location.hash.replace(/^#/, ''));\n if (params.get('error')) return true;\n return Boolean(params.get('credential') && params.get('account') && params.get('device'));\n}\n\nexport interface UseAccountEnrolmentOptions {\n /**\n * Point enrolment at a wallet other than the hosted one.\n *\n * Exists for working ON the wallet: a wallet served from `localhost:8090`\n * cannot be reached through the hosted URL, and without this the only way to\n * test a wallet change would be to deploy it.\n */\n walletUrl?: string;\n /**\n * When false, the hook reads no callback and completes nothing, so a\n * component that has the account path switched off leaves the fragment for\n * whichever component does handle it. Default true.\n */\n enabled?: boolean;\n}\n\nexport interface AccountEnrolment {\n /** Leave for the wallet to enrol this tab's device key. */\n goToWallet: () => Promise<void>;\n /** What to tell the person about the last enrolment, or null. */\n note: string | null;\n /** Whether this page load carries an enrolment callback (success or error). */\n returning: boolean;\n /** The wallet enrolment goes to: the override, else the hosted one. */\n walletUrl: string;\n /** Whether `walletUrl` is an override rather than the hosted wallet. */\n customWallet: boolean;\n}\n\nexport function useAccountEnrolment({\n walletUrl: walletOverride,\n enabled = true,\n}: UseAccountEnrolmentOptions = {}): AccountEnrolment {\n const { connectWithAccount, cloudBaseUrl } = useMero();\n const [note, setNote] = useState<string | null>(null);\n\n const walletUrl = walletOverride ?? HOSTED_WALLET;\n\n /**\n * Read the enrolment callback ONCE, during render.\n *\n * `readEnrolmentCallback` consumes the fragment — it strips it from the\n * address bar so a reload cannot replay the credential. That makes it unsafe\n * to call from an effect: React's StrictMode double-invokes effects in dev,\n * so the first run would swallow the credential and then abort through its\n * own cleanup, and the second would find nothing and silently show the\n * connect prompt again. `MeroContext` reads its auth callback this way for\n * the same reason.\n *\n * The throw case (`error=cancelled`) is captured rather than propagated: a\n * declined approval is an ordinary outcome to report, not a render failure.\n */\n const callbackRef = useRef<DeviceEnrolmentCallback | null | undefined>(undefined);\n const callbackErrorRef = useRef<string | null>(null);\n if (enabled && callbackRef.current === undefined && typeof window !== 'undefined') {\n try {\n callbackRef.current = readEnrolmentCallback();\n } catch (e) {\n callbackRef.current = null;\n callbackErrorRef.current = e instanceof Error ? e.message : String(e);\n }\n }\n /**\n * Whether this load came back from the wallet. Fixed at the first read: the\n * effect below clears the error ref once it has reported it.\n */\n const returningRef = useRef<boolean | null>(null);\n if (returningRef.current === null && callbackRef.current !== undefined) {\n returningRef.current = callbackRef.current !== null || callbackErrorRef.current !== null;\n }\n /** One completion per callback, however many times the effect runs. */\n const completingRef = useRef(false);\n\n /**\n * Finish an enrolment we are returning from.\n *\n * Runs before the button paints anything, so a tab coming back from the\n * wallet lands connected rather than showing the connect prompt again.\n */\n useEffect(() => {\n if (callbackErrorRef.current) {\n setNote(callbackErrorRef.current);\n callbackErrorRef.current = null;\n return;\n }\n const back = callbackRef.current;\n if (!back || completingRef.current) return;\n completingRef.current = true;\n let cancelled = false;\n\n (async () => {\n try {\n const keys = await deviceKeys();\n\n // Nothing is carried across the redirect any more beyond the device keys\n // themselves. There used to be a `sessionStorage` record holding the\n // typed relay and context; both are now answered by the credential this\n // returns, so the record held nothing and the \"they were lost, try\n // again\" failure it guarded cannot happen.\n // The state we sent, not the one that came back. `expectState: back.state`\n // compared the returned value against itself and therefore always passed,\n // which left the parameter as decoration: any page able to drive this\n // origin's callback could have had a credential adopted here.\n const sent = (() => {\n try {\n return sessionStorage.getItem(STATE_KEY);\n } catch {\n return null;\n }\n })();\n try {\n sessionStorage.removeItem(STATE_KEY);\n } catch {\n /* single-use where storage allows it; the comparison below is the gate */\n }\n if (!sent) {\n // No record of having started this. Refused rather than adopted: this is\n // either a callback we did not initiate, or storage that lost the value\n // mid-flow, and neither justifies accepting a certificate.\n setNote(\n 'This enrolment could not be verified as one this tab started, so it was not ' +\n 'accepted. Start again from \"Enrol with your account\".',\n );\n return;\n }\n const enrolled = await completeDeviceEnrolment({\n ...back,\n devicePublicKey: keys.signPk,\n kemPublicKey: keys.kemPk,\n expectState: sent,\n });\n\n /*\n * Where to write: asked, not typed.\n *\n * The certificate that just came back is the only input this needs. The\n * cloud mints an account-bound nonce, the device key signs it, and the\n * relay list comes back attributed to this account — no cloud session,\n * no Google sign-in, no account root. Which is why this can run here, on\n * the way home from the wallet, for a person who has none of those.\n *\n * `CloudClient`'s default base URL is the prod manager\n * (`manager.cloud.calimero.network`), which is the right default for a\n * hosted account and the only deployment that answers this route today.\n */\n // Saved BEFORE the relay lookup, and kept whatever that lookup answers.\n //\n // A first-time account is a member of nothing, so `getAccountRelays`\n // correctly answers `[]` and no connection is made below. That is not a\n // failed enrolment: the certificate is real, and it is the input that\n // resolves a relay from an INVITATION instead\n // (`useDelegatedBootstrap`). Discarding it here would make \"no relay\n // yet\" mean \"enrol again\", which mints a second device for an account\n // whose first one was fine.\n saveDelegatedCredential({\n account: enrolled.account,\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n });\n\n const cloud = new CloudClient({\n cloudBaseUrl,\n routingCredential: {\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n },\n });\n const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));\n // Connected either way — see `chooseRelay`. A null relay is an\n // authenticated account with nowhere to write yet, and the note says\n // what changes that.\n if (chosen.note) setNote(chosen.note);\n\n // Nothing else to obtain. The certificate this enrolment just returned\n // authenticates the reads and the event stream as well as the writes —\n // the device key signs each request and the node verifies it against the\n // certificate. There used to be a `login()` here, minting a session\n // against the relay node's signing key; that key had to be learned out of\n // band and the hosted case has never published one, so the picker was\n // dark on exactly the deployment it was written for.\n\n // Deliberately NOT gated on `cancelled`: the fragment has already been\n // consumed, so abandoning here would strand a credential that cannot be\n // read again. The context outlives this component, so installing the\n // connection after a StrictMode teardown is correct.\n // The relay's executor rides along when the cloud named one, so a\n // brand-new account can found a namespace on it with no join first.\n // Left off entirely otherwise, so an older server's session is the\n // same record it always was.\n connectWithAccount({\n relayUrl: chosen.relayUrl,\n account: enrolled.account,\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n ...(chosen.executorAccount ? { executorAccount: chosen.executorAccount } : {}),\n });\n } catch (e) {\n if (!cancelled) setNote(e instanceof Error ? e.message : String(e));\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [connectWithAccount, cloudBaseUrl]);\n\n const goToWallet = useCallback(async () => {\n // No inputs to validate: there is nothing left to ask for. A device key this\n // browser cannot make (no X25519, blocked storage) is reported in the note,\n // where the person is looking, rather than lost as an unhandled rejection.\n let keys: DeviceKeys;\n try {\n keys = await deviceKeys();\n } catch (e) {\n setNote(e instanceof Error ? e.message : String(e));\n return;\n }\n // Remembered before leaving, so what comes back can be checked against what\n // we sent. Without this the state parameter is decoration: comparing the\n // returned value to itself always passes, which is what it did here.\n const state = hex(crypto.getRandomValues(new Uint8Array(16)));\n try {\n sessionStorage.setItem(STATE_KEY, state);\n } catch {\n // Storage unavailable (private mode, blocked site data). The redirect\n // still works and the check below reports it as unverifiable rather than\n // silently passing.\n }\n window.location.assign(\n deviceEnrolmentUrl({\n walletUrl,\n devicePublicKey: keys.signPk,\n kemPublicKey: keys.kemPk,\n returnTo: window.location.origin + window.location.pathname,\n state,\n }),\n );\n }, [walletUrl]);\n\n return {\n goToWallet,\n note,\n returning: returningRef.current === true,\n walletUrl,\n customWallet: walletOverride !== undefined,\n };\n}\n","/**\n * Is this page running inside a Calimero Desktop (Tauri) window?\n *\n * The desktop opens every app in its own webview, already bound to the node it\n * runs, so the Cloud sign-in (wallet → relay, no node) is the wrong door there:\n * it would leave the desktop's own node behind, and the wallet redirect would\n * navigate the app window off to another origin.\n *\n * Two signals, either is enough:\n * - `__TAURI_INTERNALS__`, which Tauri injects natively into every webview it\n * creates, remote URLs included — what mero-js's own Tauri check reads;\n * - `__TAURI_FETCH_PROXY_INJECTED__`, the marker the desktop's app-window\n * init script sets, in case a future Tauri stops exposing the former there.\n *\n * Read at call time and SSR-safe: false whenever there is no `window`.\n */\nexport function isDesktopWindow(): boolean {\n if (typeof window === 'undefined') return false;\n const w = window as unknown as Record<string, unknown>;\n return '__TAURI_INTERNALS__' in w || w.__TAURI_FETCH_PROXY_INJECTED__ === true;\n}\n","/**\n * LoginModal - Modal for connecting to a Calimero node\n *\n * A single section: the modal auto-discovers nodes on the well-known local\n * ports (see `nodeDiscovery`) and offers whatever is running as radio choices,\n * plus an always-available \"enter URL manually\" option. With nothing found it\n * falls straight through to manual URL entry.\n *\n * The old Local/Remote tabs are gone — the \"Local\" tab pointed at a hardcoded\n * default node (`node1.127.0.0.1.nip.io`) that doesn't resolve in most setups;\n * discovery + manual entry covers both cases properly.\n *\n * By default the modal has two tabs: **Node** (everything above, unchanged,\n * selected by default) and **Cloud** (sign in with a Calimero account — see\n * `AccountSignInPanel` / `useAccountEnrolment`). The Cloud tab is sourced from\n * `useAccountEnrolment` inside the modal, so an app that mounts `LoginModal`\n * itself gets account sign-in with no wiring; `cloud={false}` removes it, and\n * a `cloud` object (what `ConnectButton` passes) replaces it with the caller's.\n *\n * Because of that the modal reads `useMero()` and must sit inside a\n * `MeroProvider`, as every app's does.\n *\n * Styling: colors and radius are `--mero-*` tokens (a `theme` prop, or global\n * variables). Every part also carries a stable `mero-login-*` class, as\n * `InvitationDialog` does with `mero-invite-*`, so an app can restyle what the\n * tokens do not reach. Inline styles outrank classes, so the look that is not a\n * token stays out of them where it can: the font is inherited (set it on\n * `.mero-login-overlay`), and the dialog's shadow reads `--mero-login-shadow`\n * with today's shadow as the fallback.\n */\n\nimport { useMemo, useState, useEffect, useCallback, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport { AccountSignInPanel } from './AccountSignInPanel';\nimport { useAccountEnrolment } from '../delegated/useAccountEnrolment';\nimport { isDesktopWindow } from '../utils/desktop';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport {\n discoverLocalNodes,\n nodeEndpoint,\n DEFAULT_LOCAL_NODE_PORTS,\n} from '@calimero-network/mero-js';\nimport {\n cssVar,\n resolveMeroTheme,\n themeToCssVars,\n type MeroTheme,\n type ResolvedMeroTheme,\n} from '../theme';\n\n/** Sentinel selection value for the manual \"enter a URL\" option. */\nconst CUSTOM_SELECTION = '__custom__';\n\nexport interface LoginModalProps {\n /** Callback when user connects */\n onConnect: (url: string) => void;\n /** Callback when modal is closed */\n onClose: () => void;\n /**\n * @deprecated Ignored. The modal always shows node discovery + manual URL\n * entry; the old hardcoded-default \"Local\" view was removed. Kept so\n * existing call sites keep compiling.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Whether the modal is open */\n isOpen: boolean;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Ports probed when discovering local nodes. Defaults to the well-known\n * Calimero dev ports (2428, 2429, 2528, 2529). Mostly an escape hatch for\n * non-standard setups and tests.\n */\n localNodePorts?: readonly number[];\n /**\n * The second way in: a **Cloud** tab, signing in with a Calimero account by\n * enrolling this tab's device key at the wallet.\n *\n * - **Omitted** (the default): the tab is shown, sourced from\n * `useAccountEnrolment()` inside the modal — enrolment starts from the tab,\n * and a page coming back from the wallet is completed here, whether or not\n * the modal is open. Nothing to wire; the modal must be inside a\n * `MeroProvider`.\n * - **`false`**: no Cloud tab and no tabs at all — the node dialog as it was.\n * - **omitted inside a Calimero Desktop window**: as `false` — the window is\n * already bound to the desktop's node. Pass a `cloud` object to override.\n * The modal reads no enrolment callback, leaving it to whichever component\n * does.\n * - **An object**: the caller's own enrolment, used verbatim; the modal reads\n * none itself. The values are `useAccountEnrolment`'s, as `ConnectButton`\n * passes them.\n */\n cloud?:\n | false\n | {\n /** Start enrolment — normally `useAccountEnrolment().goToWallet`. */\n onEnrol: () => void;\n /** What the last enrolment had to say, shown on the Cloud tab. */\n note?: string | null;\n /** The wallet enrolment goes to. Shown only when `customWallet`. */\n walletUrl?: string;\n /** Whether `walletUrl` is an override rather than the hosted wallet. */\n customWallet?: boolean;\n };\n /**\n * The tab selected when the modal opens. Ignored with `cloud={false}`.\n *\n * Default `'node'` — except that a modal sourcing its own Cloud tab opens on\n * `'cloud'` when the page is coming back from the wallet, so whatever the\n * completion has to say is where the person is looking. An explicit value\n * always wins.\n */\n initialTab?: LoginModalTab;\n}\n\n/** The two tabs of the connect dialog, when it has a Cloud tab. */\nexport type LoginModalTab = 'node' | 'cloud';\n\nconst TABS: readonly { id: LoginModalTab; label: string }[] = [\n { id: 'node', label: 'Node' },\n { id: 'cloud', label: 'Cloud' },\n];\n\n/**\n * Validate URL format\n */\nfunction isValidUrl(urlString: string): boolean {\n if (!urlString || urlString.trim() === '') {\n return false;\n }\n\n try {\n const urlToTest =\n urlString.startsWith('http://') || urlString.startsWith('https://')\n ? urlString\n : `https://${urlString}`;\n\n const url = new URL(urlToTest);\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return false;\n }\n\n if (!url.hostname) {\n return false;\n }\n\n const hostname = url.hostname;\n\n // Allow localhost\n if (hostname === 'localhost') {\n return true;\n }\n\n // Check for valid IP address\n const ipv4Regex = /^(\\d{1,3}\\.){3}\\d{1,3}$/;\n if (ipv4Regex.test(hostname)) {\n const octets = hostname.split('.').map(Number);\n return octets.every((octet) => octet >= 0 && octet <= 255);\n }\n\n // Check for valid domain name\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n return domainRegex.test(hostname);\n } catch {\n return false;\n }\n}\n\n/** Strip the scheme for a compact node label (e.g. `localhost:2428`). */\nfunction displayNodeUrl(url: string): string {\n return url.replace(/^https?:\\/\\//, '').replace(/\\/+$/, '');\n}\n\n/**\n * Mix a color with transparent using CSS `color-mix`. Works for any valid CSS\n * color value (hex of any length, rgb(), hsl(), named colors, var(...)) — not\n * just 6-digit hex.\n */\nfunction tint(color: string, percent: number): string {\n return `color-mix(in srgb, ${color} ${percent}%, transparent)`;\n}\n\n/**\n * Build the inline-style map from a resolved theme. Each value is emitted as\n * `var(--mero-*, fallback)` so a global `:root { --mero-* }` rule reaches the\n * portal-rendered modal; the fallback ensures the modal still renders correctly\n * if the consumer hasn't imported `styles.css`.\n */\nfunction buildStyles(t: ResolvedMeroTheme) {\n const bg = cssVar(t, 'background');\n const bgSecondary = cssVar(t, 'backgroundSecondary');\n const text = cssVar(t, 'text');\n const textSecondary = cssVar(t, 'textSecondary');\n const accent = cssVar(t, 'primary');\n const onPrimary = cssVar(t, 'primaryText');\n const border = cssVar(t, 'border');\n const error = cssVar(t, 'error');\n const overlay = cssVar(t, 'overlay');\n const radius = cssVar(t, 'radius');\n\n const errorBg = tint(error, 10);\n const errorBorder = tint(error, 30);\n const accentGlow = tint(accent, 15);\n\n return {\n overlay: {\n position: 'fixed' as const,\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n backgroundColor: overlay,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n zIndex: 10000,\n padding: '1rem',\n animation: 'meroFadeIn 0.2s ease-out',\n },\n content: {\n backgroundColor: bg,\n borderRadius: radius,\n padding: '2rem',\n maxWidth: '420px',\n width: '100%',\n position: 'relative' as const,\n border: `1px solid ${border}`,\n // Not a theme token, so an app could not reach it past the inline style:\n // `--mero-login-shadow` replaces it whole. Unset, it is the shadow and\n // accent ring the dialog always had.\n boxShadow: `var(--mero-login-shadow, 0 25px 50px -12px rgba(0, 0, 0, 0.6), 0 0 0 1px ${accentGlow})`,\n animation: 'meroSlideIn 0.25s ease-out',\n color: text,\n },\n closeButton: {\n position: 'absolute' as const,\n top: '0.75rem',\n right: '0.75rem',\n background: 'none',\n border: 'none',\n fontSize: '1.5rem',\n color: textSecondary,\n cursor: 'pointer',\n padding: '0.25rem',\n lineHeight: 1,\n },\n header: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n marginBottom: '1.5rem',\n },\n title: {\n fontSize: '1.25rem',\n fontWeight: 600,\n color: text,\n margin: 0,\n },\n info: {\n color: textSecondary,\n textAlign: 'center' as const,\n marginBottom: '1.5rem',\n fontSize: '0.875rem',\n },\n error: {\n color: error,\n backgroundColor: errorBg,\n border: `1px solid ${errorBorder}`,\n borderRadius: radius,\n padding: '0.75rem',\n marginBottom: '1rem',\n fontSize: '0.875rem',\n textAlign: 'center' as const,\n },\n radioList: {\n display: 'flex',\n flexDirection: 'column' as const,\n gap: '0.5rem',\n marginBottom: '1rem',\n },\n radioItem: {\n display: 'flex',\n alignItems: 'center',\n gap: '0.625rem',\n color: text,\n cursor: 'pointer',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n transition: 'all 0.15s ease',\n fontSize: '0.875rem',\n },\n radioItemActive: {\n // Override the full `border` shorthand (not just borderColor) so React\n // never has to mix shorthand + longhand on the same element.\n border: `1px solid ${accent}`,\n backgroundColor: accentGlow,\n color: text,\n },\n radioIndicator: {\n flexShrink: 0,\n width: '1rem',\n height: '1rem',\n borderRadius: '50%',\n border: `2px solid ${border}`,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n radioIndicatorActive: {\n border: `2px solid ${accent}`,\n },\n radioDot: {\n width: '0.5rem',\n height: '0.5rem',\n borderRadius: '50%',\n backgroundColor: accent,\n },\n nodeMeta: {\n marginLeft: 'auto',\n fontSize: '0.75rem',\n color: textSecondary,\n },\n input: {\n width: '100%',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n color: text,\n fontSize: '0.875rem',\n outline: 'none',\n marginBottom: '1rem',\n boxSizing: 'border-box' as const,\n },\n toolbar: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '1rem',\n },\n rescan: {\n background: 'none',\n border: 'none',\n color: accent,\n cursor: 'pointer',\n fontSize: '0.8125rem',\n padding: '0.25rem 0.5rem',\n },\n buttonGroup: {\n display: 'flex',\n justifyContent: 'center',\n },\n button: {\n padding: '0.75rem 2rem',\n borderRadius: radius,\n border: 'none',\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n backgroundColor: accent,\n color: onPrimary,\n transition: 'all 0.15s ease',\n },\n buttonDisabled: {\n opacity: 0.5,\n cursor: 'not-allowed',\n },\n loading: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '1rem',\n padding: '2rem',\n color: textSecondary,\n },\n discovering: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n padding: '1rem',\n color: textSecondary,\n fontSize: '0.875rem',\n },\n spinner: {\n width: '2rem',\n height: '2rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n tabList: {\n display: 'flex',\n gap: '0.25rem',\n padding: '0.25rem',\n marginBottom: '1.5rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n },\n tab: {\n flex: 1,\n padding: '0.5rem 1rem',\n borderRadius: radius,\n border: '1px solid transparent',\n backgroundColor: 'transparent',\n color: textSecondary,\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n transition: 'all 0.15s ease',\n },\n tabActive: {\n border: `1px solid ${accent}`,\n backgroundColor: accentGlow,\n color: text,\n },\n spinnerSmall: {\n width: '1.5rem',\n height: '1.5rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n };\n}\n\n/**\n * LoginModal - Connection modal component\n */\nexport function LoginModal({\n onConnect,\n onClose,\n isOpen,\n theme,\n localNodePorts = DEFAULT_LOCAL_NODE_PORTS,\n cloud,\n initialTab: initialTabProp,\n}: LoginModalProps) {\n // The modal's own enrolment, for the default case only. A caller that passed\n // its own `cloud` already holds an enabled hook, and the callback it reads is\n // single-use: a second enabled reader here would find nothing, or — if it\n // rendered first — take the callback away from the caller. So this is on\n // exactly when nobody else is. Called before the `isOpen` early return, so a\n // tab coming back from the wallet is completed while the modal is closed too.\n //\n // Inside a Calimero Desktop window there is no default Cloud tab: the window\n // is already bound to the desktop's node (see `isDesktopWindow`). A caller\n // that passes its own `cloud` object still gets it.\n const ownCloud = cloud === undefined && !isDesktopWindow();\n const own = useAccountEnrolment({ enabled: ownCloud });\n const cloudTab = useMemo(\n () =>\n ownCloud\n ? {\n onEnrol: () => {\n void own.goToWallet();\n },\n note: own.note,\n walletUrl: own.walletUrl,\n customWallet: own.customWallet,\n }\n : cloud || null,\n [cloud, ownCloud, own.goToWallet, own.note, own.walletUrl, own.customWallet],\n );\n const initialTab: LoginModalTab =\n initialTabProp ?? (ownCloud && own.returning ? 'cloud' : 'node');\n\n const [tab, setTab] = useState<LoginModalTab>(initialTab);\n // Each opening starts on `initialTab`: the modal stays mounted while closed,\n // so without this a reopen would land on whatever tab was left selected.\n useEffect(() => {\n if (isOpen) setTab(initialTab);\n }, [isOpen, initialTab]);\n const tabRefs = useRef<Record<LoginModalTab, HTMLButtonElement | null>>({\n node: null,\n cloud: null,\n });\n const activeTab: LoginModalTab = cloudTab ? tab : 'node';\n\n // `selected` is a discovered node URL or CUSTOM.\n const [selected, setSelected] = useState<string>(CUSTOM_SELECTION);\n const [discovered, setDiscovered] = useState<string[]>([]);\n const [discovering, setDiscovering] = useState<boolean>(false);\n const [customUrl, setCustomUrl] = useState<string>('');\n\n const [loading, setLoading] = useState<boolean>(false);\n const [error, setError] = useState<string | null>(null);\n\n const resolved = useMemo(() => resolveMeroTheme(theme), [theme]);\n const styles = useMemo(() => buildStyles(resolved), [resolved]);\n // Only emit inline `--mero-*` variables when a `theme` prop was actually\n // provided. Without a prop, we let global `:root { --mero-* }` rules cascade\n // through to the portal-rendered modal (with `var()` fallbacks in buildStyles\n // covering the case where no global rules are loaded).\n const themeVars = useMemo(\n () => (theme ? themeToCssVars(resolved) : undefined),\n [theme, resolved],\n );\n\n // Load saved URL into the manual field\n useEffect(() => {\n const savedUrl = localStorage.getItem('mero:node_url');\n if (savedUrl) {\n setCustomUrl(savedUrl);\n }\n }, []);\n\n // Probe local ports whenever the modal is open; a bumpable nonce lets the\n // user trigger a re-scan.\n const [scanNonce, setScanNonce] = useState(0);\n const portsKey = useMemo(() => localNodePorts.join(','), [localNodePorts]);\n\n useEffect(() => {\n if (!isOpen) {\n return;\n }\n\n const controller = new AbortController();\n let active = true;\n setDiscovering(true);\n // Clear any prior results so a re-scan never shows stale nodes.\n setDiscovered([]);\n setError(null);\n\n discoverLocalNodes({ ports: localNodePorts, signal: controller.signal })\n .then((nodes) => {\n if (!active) return;\n setDiscovered(nodes);\n // Default to the first discovered node, else fall through to manual.\n setSelected(nodes.length > 0 ? nodes[0] : CUSTOM_SELECTION);\n })\n // discoverLocalNodes is designed never to reject; the catch is purely\n // defensive so a future change can't surface an unhandled rejection.\n .catch(() => {\n if (active) setSelected(CUSTOM_SELECTION);\n })\n .finally(() => {\n if (active) setDiscovering(false);\n });\n\n return () => {\n active = false;\n controller.abort();\n };\n // portsKey captures localNodePorts content; scanNonce forces a re-scan.\n }, [isOpen, portsKey, scanNonce]);\n\n const isCustom = selected === CUSTOM_SELECTION;\n const hasDiscovered = discovered.length > 0;\n\n // Whether the connect button can fire in the current state.\n const canConnect =\n !loading && !discovering && (isCustom ? isValidUrl(customUrl) : true);\n\n // Keep a ref so the input's keydown handler always sees current validity.\n const canConnectRef = useRef(canConnect);\n canConnectRef.current = canConnect;\n\n const handleConnect = useCallback(async () => {\n const usingDiscovered = selected !== CUSTOM_SELECTION;\n const targetUrl = usingDiscovered ? selected : customUrl;\n\n // Manual URLs must look valid before we try them.\n if (!usingDiscovered && !isValidUrl(targetUrl)) {\n return;\n }\n\n const normalizedUrl = targetUrl.replace(/\\/+$/, '');\n\n // A discovered node already answered a health check — connect straight away.\n if (usingDiscovered) {\n onConnect(normalizedUrl);\n return;\n }\n\n // Manually entered URLs are verified via is-authed.\n setLoading(true);\n setError(null);\n\n try {\n const response = await fetch(\n nodeEndpoint(normalizedUrl, 'admin-api/is-authed'),\n );\n\n if (response.ok || response.status === 401) {\n setLoading(false);\n onConnect(normalizedUrl);\n } else {\n throw new Error(`Connection failed: ${response.statusText}`);\n }\n } catch (err) {\n console.error('Connection failed:', err);\n setError('Failed to connect. Please check the URL and try again.');\n setLoading(false);\n }\n }, [selected, customUrl, onConnect]);\n\n if (!isOpen) {\n return null;\n }\n\n const showManualInput = isCustom;\n const renderRadio = (value: string, label: string, meta?: string) => {\n const active = selected === value;\n return (\n // Selection is driven solely by the radio input's `onChange` — clicking\n // anywhere on the wrapping label forwards to the input, and keyboard\n // users can tab to / arrow through the (visually hidden but focusable)\n // input. A label `onClick` here would double-fire `setSelected`.\n <label\n key={value}\n className={\n active ? 'mero-login-option mero-login-option-active' : 'mero-login-option'\n }\n data-testid={`node-option-${value === CUSTOM_SELECTION ? 'custom' : displayNodeUrl(value)}`}\n style={{\n ...styles.radioItem,\n ...(active ? styles.radioItemActive : {}),\n }}\n >\n <input\n type=\"radio\"\n name=\"mero-node\"\n value={value}\n checked={active}\n onChange={() => setSelected(value)}\n style={{ position: 'absolute', opacity: 0 }}\n />\n <span\n className=\"mero-login-option-indicator\"\n style={{\n ...styles.radioIndicator,\n ...(active ? styles.radioIndicatorActive : {}),\n }}\n >\n {active && (\n <span className=\"mero-login-option-dot\" style={styles.radioDot} />\n )}\n </span>\n {label}\n {meta && (\n <span className=\"mero-login-option-meta\" style={styles.nodeMeta}>\n {meta}\n </span>\n )}\n </label>\n );\n };\n\n const renderNodeSection = () => {\n if (discovering) {\n return (\n <div\n className=\"mero-login-discovering\"\n style={styles.discovering}\n data-testid=\"node-discovering\"\n >\n <div className=\"mero-login-spinner\" style={styles.spinnerSmall} />\n <p>Searching for local nodes...</p>\n </div>\n );\n }\n\n return (\n <>\n <p className=\"mero-login-info\" style={styles.info}>\n {hasDiscovered\n ? 'Select your Calimero node to continue.'\n : 'No local node found. Enter a node URL to continue.'}\n </p>\n\n {hasDiscovered && (\n <div\n className=\"mero-login-options\"\n style={styles.radioList}\n role=\"radiogroup\"\n aria-label=\"Available nodes\"\n >\n {discovered.map((url) =>\n renderRadio(url, displayNodeUrl(url), 'local'),\n )}\n {/* Manual entry is always offered alongside discovered nodes. */}\n {renderRadio(CUSTOM_SELECTION, 'Enter node URL manually')}\n </div>\n )}\n\n {showManualInput && (\n <input\n type=\"text\"\n value={customUrl}\n onChange={(e) => setCustomUrl(e.target.value)}\n placeholder=\"https://your-node-url.calimero.network\"\n className=\"mero-login-input\"\n style={styles.input}\n data-testid=\"node-url-input\"\n autoFocus={!hasDiscovered}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && canConnectRef.current) {\n handleConnect();\n }\n }}\n />\n )}\n\n <div className=\"mero-login-toolbar\" style={styles.toolbar}>\n <button\n type=\"button\"\n className=\"mero-login-rescan\"\n style={styles.rescan}\n onClick={() => setScanNonce((n) => n + 1)}\n data-testid=\"rescan-button\"\n >\n ↻ Rescan local nodes\n </button>\n </div>\n </>\n );\n };\n\n // The node dialog's body, exactly as it was before there were tabs. With a\n // Cloud tab it is wrapped as the Node tabpanel; without one it is the whole\n // modal body, with no wrapper, so a direct LoginModal user sees no change.\n const renderNodeBody = () => {\n const body = loading ? (\n <div className=\"mero-login-loading\" style={styles.loading}>\n <p>Connecting to node...</p>\n <div className=\"mero-login-spinner\" style={styles.spinner} />\n </div>\n ) : (\n <>\n {error && (\n <p className=\"mero-login-error\" style={styles.error}>\n {error}\n </p>\n )}\n\n {renderNodeSection()}\n\n <div className=\"mero-login-actions\" style={styles.buttonGroup}>\n <button\n className=\"mero-login-button mero-login-primary\"\n onClick={handleConnect}\n disabled={!canConnect}\n style={{\n ...styles.button,\n ...(!canConnect ? styles.buttonDisabled : {}),\n }}\n data-testid=\"connect-button\"\n >\n Connect\n </button>\n </div>\n </>\n );\n if (!cloudTab) return body;\n return (\n <div\n className=\"mero-login-panel\"\n role=\"tabpanel\"\n id=\"mero-login-panel-node\"\n aria-labelledby=\"mero-login-tab-node\"\n >\n {body}\n </div>\n );\n };\n\n // WAI-ARIA tabs with automatic activation: the selected tab is the one tab\n // stop, and the arrow keys (plus Home/End) move selection and focus.\n const selectTab = (id: LoginModalTab) => {\n setTab(id);\n tabRefs.current[id]?.focus();\n };\n const onTabKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {\n const i = TABS.findIndex((t) => t.id === activeTab);\n let next: number | null = null;\n if (e.key === 'ArrowRight') next = (i + 1) % TABS.length;\n else if (e.key === 'ArrowLeft') next = (i - 1 + TABS.length) % TABS.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = TABS.length - 1;\n if (next === null) return;\n e.preventDefault();\n selectTab(TABS[next].id);\n };\n const renderTabs = () => (\n <div\n className=\"mero-login-tabs\"\n role=\"tablist\"\n aria-label=\"How to connect\"\n style={styles.tabList}\n >\n {TABS.map((t) => {\n const selected = activeTab === t.id;\n return (\n <button\n key={t.id}\n ref={(el) => {\n tabRefs.current[t.id] = el;\n }}\n type=\"button\"\n className={\n selected ? 'mero-login-tab mero-login-tab-active' : 'mero-login-tab'\n }\n role=\"tab\"\n id={`mero-login-tab-${t.id}`}\n aria-selected={selected}\n aria-controls={`mero-login-panel-${t.id}`}\n tabIndex={selected ? 0 : -1}\n onClick={() => setTab(t.id)}\n onKeyDown={onTabKeyDown}\n style={{ ...styles.tab, ...(selected ? styles.tabActive : {}) }}\n data-testid={`login-tab-${t.id}`}\n >\n {t.label}\n </button>\n );\n })}\n </div>\n );\n\n const modalContent = (\n <>\n <style>{`\n @keyframes meroSpin { to { transform: rotate(360deg); } }\n @keyframes meroFadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes meroSlideIn { from { transform: translateY(-12px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n `}</style>\n <div\n className=\"mero-login-overlay\"\n style={{ ...themeVars, ...styles.overlay }}\n onClick={onClose}\n >\n <div\n className=\"mero-login-dialog\"\n style={styles.content}\n onClick={(e) => e.stopPropagation()}\n >\n <button\n className=\"mero-login-close\"\n style={styles.closeButton}\n onClick={onClose}\n aria-label=\"Close\"\n >\n &times;\n </button>\n\n <div className=\"mero-login-header\" style={styles.header}>\n <CalimeroLogo\n size={44}\n color={cssVar(resolved, 'primary')}\n className=\"mero-login-logo\"\n />\n <h1 className=\"mero-login-title\" style={styles.title}>\n Connect to Calimero\n </h1>\n </div>\n\n {cloudTab && renderTabs()}\n\n {activeTab === 'cloud' && cloudTab ? (\n <div\n className=\"mero-login-panel\"\n role=\"tabpanel\"\n id=\"mero-login-panel-cloud\"\n aria-labelledby=\"mero-login-tab-cloud\"\n tabIndex={0}\n >\n <AccountSignInPanel\n onEnrol={cloudTab.onEnrol}\n note={cloudTab.note}\n walletUrl={cloudTab.walletUrl}\n customWallet={cloudTab.customWallet}\n theme={theme}\n />\n </div>\n ) : (\n renderNodeBody()\n )}\n </div>\n </div>\n </>\n );\n\n return createPortal(modalContent, document.body);\n}\n\nexport default LoginModal;\n","/**\n * ConnectButton - A button component for connecting to Calimero\n *\n * Shows connection status and provides login/logout functionality.\n * Includes built-in LoginModal with two tabs: **Node** (node discovery + URL,\n * the default) and **Cloud** (sign in with a Calimero account by enrolling at\n * the wallet — see `useAccountEnrolment`). `cloud={false}` removes the Cloud\n * tab and leaves the node dialog exactly as it was.\n */\n\nimport React, { useState, useEffect, useRef, useMemo } from 'react';\nimport { useMero } from '../context';\nimport { LoginModal } from './LoginModal';\nimport { isDesktopWindow } from '../utils/desktop';\nimport { useAccountEnrolment } from '../delegated/useAccountEnrolment';\nimport { readDelegatedSession } from '@calimero-network/mero-js';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport { ConnectionType as ConnectionTypeEnum } from '../types';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\nexport interface ConnectButtonProps {\n /**\n * Connection behaviour. `Custom` (object form) connects straight to the\n * given URL, skipping the modal; every other value opens the LoginModal,\n * which always shows node discovery + manual URL entry.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Custom class name */\n className?: string;\n /** Custom styles */\n style?: React.CSSProperties;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Render only the Calimero logo, no text. Produces a square 40×40 icon\n * button. The label is still announced to screen readers via `aria-label`.\n * Default: false.\n */\n logoOnly?: boolean;\n /**\n * Override the default labels per state. A bare string is shorthand for\n * `{ connect: '<string>' }`. The connected and reconnecting states keep\n * their defaults unless explicitly overridden.\n */\n label?:\n | string\n | { connect?: string; connected?: string; reconnecting?: string };\n /**\n * Offer the **Cloud** tab — sign in with a Calimero account — next to the\n * node dialog. Default true in a browser, false inside a Calimero Desktop\n * window (already bound to the desktop's node; see `isDesktopWindow`). With\n * false the modal has no tabs, and this button reads no enrolment callback,\n * leaving it to whichever component does.\n */\n cloud?: boolean;\n /**\n * Overrides for the account path, for local development only.\n */\n accountDefaults?: {\n /**\n * Point enrolment at a wallet other than the hosted one — for working ON\n * the wallet, e.g. one served from `localhost:8090`.\n */\n walletUrl?: string;\n };\n}\n\n/** `abcdef…123456` — enough of a 64-hex account id to recognise it. */\nfunction shortAccount(account: string): string {\n return account.length > 14 ? `${account.slice(0, 6)}…${account.slice(-6)}` : account;\n}\n\n/**\n * ConnectButton - Displays connection status and handles login/logout\n */\nexport function ConnectButton({\n connectionType = ConnectionTypeEnum.Remote,\n className,\n style,\n theme,\n logoOnly = false,\n label,\n cloud: cloudProp,\n accountDefaults,\n}: ConnectButtonProps) {\n const cloud = cloudProp ?? !isDesktopWindow();\n const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline, isDelegated } = useMero();\n const enrolment = useAccountEnrolment({\n walletUrl: accountDefaults?.walletUrl,\n enabled: cloud,\n });\n // A tab coming back from the wallet opens straight onto the Cloud tab, so\n // whatever the completion has to say is where the person is looking. Once\n // `connectWithAccount` lands, the connected state below replaces it.\n const [isModalOpen, setIsModalOpen] = useState(() => cloud && enrolment.returning);\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n // The account an account session belongs to, for the dropdown. Read from the\n // stored session (the context exposes `isDelegated`, not the account).\n const account = useMemo(\n () => (isAuthenticated && isDelegated ? readDelegatedSession()?.account ?? null : null),\n [isAuthenticated, isDelegated],\n );\n\n // Resolve once. Inline CSS variables are only emitted when a theme prop is\n // provided — otherwise we leave the cascade alone so global `:root { --mero-* }`\n // overrides take effect.\n const resolvedTheme = useMemo(\n () => (theme ? resolveMeroTheme(theme) : null),\n [theme],\n );\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n // Close dropdown when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (\n dropdownRef.current &&\n !dropdownRef.current.contains(event.target as Node)\n ) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', handleClickOutside);\n return () => document.removeEventListener('mousedown', handleClickOutside);\n }, []);\n\n const dashboardUrl = useMemo(() => {\n if (!isAuthenticated || !nodeUrl || isDelegated) return '#';\n return new URL('admin-dashboard/', nodeUrl).toString();\n }, [isAuthenticated, nodeUrl]);\n\n const labels = useMemo(() => {\n const overrides = typeof label === 'string' ? { connect: label } : label;\n return {\n connect: overrides?.connect ?? 'Connect',\n connected: overrides?.connected ?? 'Connected',\n reconnecting: overrides?.reconnecting ?? 'Reconnecting...',\n };\n }, [label]);\n\n const buttonClassName = logoOnly ? 'mero-logo-only' : '';\n\n const handleConnect = () => {\n // If Custom type with URL, connect directly\n if (\n typeof connectionType === 'object' &&\n connectionType.type === ConnectionTypeEnum.Custom\n ) {\n connectToNode(connectionType.url);\n return;\n }\n\n // Otherwise, open modal\n setIsModalOpen(true);\n };\n\n const handleModalConnect = (url: string) => {\n setIsModalOpen(false);\n connectToNode(url);\n };\n\n // Reconnecting state\n if (isAuthenticated && !isOnline) {\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-reconnecting', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label={labels.reconnecting}\n title={logoOnly ? labels.reconnecting : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.reconnecting}\n </button>\n </div>\n );\n }\n\n // Connected state\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((prev) => !prev)}\n aria-label={labels.connected}\n title={logoOnly ? labels.connected : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connected}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n {isDelegated && account && (\n <div className=\"mero-dropdown-info\" title={account} data-testid=\"connected-account\">\n Account {shortAccount(account)}\n </div>\n )}\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {/* A delegated account with no relay is signed in and has no node\n to name. Saying so beats an empty row that reads as a bug. */}\n {nodeUrl ?? (isDelegated ? 'no relay yet' : null)}\n </div>\n {isDelegated && enrolment.note && (\n <div className=\"mero-dropdown-info\" data-testid=\"connected-note\">\n {enrolment.note}\n </div>\n )}\n {/* No dashboard link on the delegated path: the admin dashboard is\n a node-operator surface, and a keyholder has no credential for\n it. Offering a link that 401s would be worse than omitting it. */}\n {!isDelegated && (\n <a\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n )}\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n // Disconnected state\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={handleConnect}\n aria-label={labels.connect}\n title={logoOnly ? labels.connect : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connect}\n </button>\n <LoginModal\n isOpen={isModalOpen}\n onConnect={handleModalConnect}\n onClose={() => setIsModalOpen(false)}\n theme={resolvedTheme ?? theme}\n cloud={\n cloud\n ? {\n onEnrol: () => {\n void enrolment.goToWallet();\n },\n note: enrolment.note,\n walletUrl: enrolment.walletUrl,\n customWallet: enrolment.customWallet,\n }\n : false\n }\n initialTab={cloud && enrolment.returning ? 'cloud' : 'node'}\n />\n </div>\n );\n}\n\nexport default ConnectButton;\n","/**\n * ConnectButtonAccount — ConnectButton, plus a second way in.\n *\n * A copy of {@link ConnectButton} rather than a change to it, deliberately:\n * the node-login path is load-bearing for every shipped app, and this is an\n * experiment. `ConnectButton` and `LoginModal` are untouched.\n *\n * Two ways to connect, and the difference is who runs the node:\n *\n * - **I run a node** — exactly today's behaviour. `LoginModal` discovers nodes\n * or takes a URL, and `connectToNode` redirects into the node's auth flow.\n * - **I have an account** — no node. A wallet on another origin certifies this\n * tab's device key, and a relay writes on the account's behalf under warrants\n * signed here.\n *\n * ## One credential, two signatures over it\n *\n * The certificate the wallet mints is the whole of what this holds. The device\n * key it certifies signs two different things, and neither needs anything more:\n *\n * - a **warrant**, per intent, is what `rpc.execute` sends — an app's own logic,\n * including a generated ABI client, runs on this alone;\n * - a **request proof** (`X-Calimero-Proof`), per request, authenticates the\n * caller-scoped reads and the event stream. The node verifies the signature\n * against the certificate with no store read and no prior relationship, so\n * `getContexts` and `listNamespaces` answer this account's own and `/sse`\n * delivers this account's contexts.\n *\n * ## The pane asks for nothing\n *\n * It used to have three fields, and not one of them was a question an end user\n * could answer. All three are gone:\n *\n * - the **relay** is discovered. The same certificate proves the cloud's\n * account→relay lookup (`CloudClient.getAccountRelays`): the device signs an\n * account-bound nonce and the cloud names the relays. No cloud session, no\n * Google sign-in, no account root.\n * - the **wallet** is a platform constant, defaulted here, overridable only for\n * working on the wallet itself.\n * - the **context** is chosen after connecting, not before. `MeroContext` learns\n * this tab's `applicationId` from the registry by the app's `packageName`\n * (the account's contexts, caller-scoped by the request proof, name it only\n * when the app passes none), so an app's own context picker has what it needs\n * and the person picks from a list instead of pasting a 64-hex id.\n *\n * So the account path is one button.\n *\n * This pane used to ask for the relay node's signing key as well, to mint an\n * `account_proof` session with `login()`. Nothing needs it: the proof path was\n * measured serving the same reads and the same events without it, against a node\n * built from core `aecba573b`. A session remains the right shape where the device\n * key sits behind a boundary worth crossing once — a hardware key — which is not\n * this.\n */\n\nimport React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { useMero } from '../context';\nimport { useAccountEnrolment } from '../delegated/useAccountEnrolment';\nimport { LoginModal } from './LoginModal';\nimport { isDesktopWindow } from '../utils/desktop';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\nexport interface ConnectButtonAccountProps {\n className?: string;\n style?: React.CSSProperties;\n theme?: MeroTheme;\n /**\n * Overrides for local development. An app in production passes none of this,\n * and the pane asks the person for nothing at all.\n *\n * Nothing here is a value an end user could know, which is precisely why none\n * of it is a form field any more:\n *\n * - the **relay** is discovered — the certificate the enrolment returns proves\n * the cloud's account→relay lookup, so there is nothing to type and a prefill\n * would only be a staler second source of truth;\n * - the **context** is chosen after connecting, from the account's own contexts,\n * which `admin.getContexts()` answers caller-scoped through the request proof.\n */\n /**\n * Show the \"I have an account\" path. Default true in a browser, false inside\n * a Calimero Desktop window, which is already bound to the desktop's node\n * (see `isDesktopWindow`).\n */\n cloud?: boolean;\n defaults?: {\n /**\n * Point enrolment at a wallet other than the hosted one.\n *\n * Exists for working ON the wallet: a wallet served from `localhost:8090`\n * cannot be reached through the hosted URL, and without this the only way to\n * test a wallet change would be to deploy it.\n */\n walletUrl?: string;\n };\n}\n\nexport function ConnectButtonAccount({\n className,\n style,\n theme,\n defaults = {},\n cloud: cloudProp,\n}: ConnectButtonAccountProps) {\n const cloud = cloudProp ?? !isDesktopWindow();\n const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, logout } = useMero();\n\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);\n const [isAccountOpen, setIsAccountOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n const resolvedTheme = useMemo(() => (theme ? resolveMeroTheme(theme) : null), [theme]);\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n useEffect(() => {\n const onOutside = (e: MouseEvent) => {\n if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', onOutside);\n return () => document.removeEventListener('mousedown', onOutside);\n }, []);\n\n const { goToWallet, note, walletUrl } = useAccountEnrolment({\n walletUrl: defaults.walletUrl,\n enabled: cloud,\n });\n\n if (isAuthenticated && !isOnline) {\n return (\n <div className=\"mero-connect-container\" style={{ ...themeVars, display: 'inline-block' }}>\n <button\n className={['mero-connect-button', 'mero-reconnecting', className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label=\"Reconnecting...\"\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n Reconnecting...\n </button>\n </div>\n );\n }\n\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((p) => !p)}\n aria-label=\"Connected\"\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {isDelegated ? 'Connected (account)' : 'Connected'}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {/* A delegated account with no relay is signed in and has no node\n to name. Saying so beats an empty row that reads as a bug. */}\n {nodeUrl ?? (isDelegated ? 'no relay yet' : null)}\n </div>\n {/* No dashboard link on the delegated path: the admin dashboard is\n a node-operator surface, and a keyholder has no credential for\n it. Offering a link that 401s would be worse than omitting it. */}\n {!isDelegated && nodeUrl && (\n <a\n href={new URL('admin-dashboard/', nodeUrl).toString()}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n )}\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"mero-connect-container\" style={{ ...themeVars, display: 'inline-block' }}>\n <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>\n <button\n className={['mero-connect-button', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsNodeModalOpen(true)}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n I run a node\n </button>\n {cloud && (\n <button\n className={['mero-connect-button', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsAccountOpen((p) => !p)}\n >\n I have an account\n </button>\n )}\n </div>\n\n {cloud && isAccountOpen && (\n <div\n style={{\n marginTop: 12,\n padding: 14,\n border: '1px solid rgba(127,127,127,.35)',\n borderRadius: 8,\n display: 'grid',\n gap: 8,\n maxWidth: 520,\n textAlign: 'left',\n font: '13px system-ui, sans-serif',\n }}\n >\n {/* No form fields. Every one this pane used to have asked for\n something only an operator could know, and all three are now\n answered by the certificate: the wallet is the platform's, the relay\n is looked up, and the context is chosen afterwards from the\n account's own. What is left is a button and an explanation of what\n pressing it does. */}\n <button className=\"mero-connect-button\" onClick={goToWallet}>\n Enrol with your account\n </button>\n <p style={{ margin: 0, opacity: 0.75 }}>\n You will approve a device key on the wallet&apos;s own page, then come\n back here. The relay never sees your account root — only the\n certificate it signed.\n </p>\n <p style={{ margin: 0, opacity: 0.75 }}>\n That one certificate is all of it: finding the relay that serves your\n account, writing through it, reading your own contexts and namespaces,\n and live events. Nothing to paste in.\n </p>\n {defaults.walletUrl && (\n /* Shown only when an app overrode it, so a local rig can see at a\n glance that it is not enrolling against the hosted wallet. */\n <p style={{ margin: 0, opacity: 0.6 }}>\n Enrolling at <code>{walletUrl}</code>, not the hosted wallet.\n </p>\n )}\n </div>\n )}\n\n {note && (\n <p style={{ font: '13px system-ui, sans-serif', color: '#b3261e' }}>{note}</p>\n )}\n\n <LoginModal\n isOpen={isNodeModalOpen}\n onConnect={(url) => {\n setIsNodeModalOpen(false);\n connectToNode(url);\n }}\n onClose={() => setIsNodeModalOpen(false)}\n theme={resolvedTheme ?? theme}\n // This component runs the account path itself (the hook above); the node\n // dialog stays node-only so the single-use callback has one reader.\n cloud={false}\n />\n </div>\n );\n}\n\nexport default ConnectButtonAccount;\n","/**\n * Minimal Base58 (Bitcoin alphabet) decoder.\n *\n * Blob ids come back from the admin API Base58-encoded, while a namespace's\n * `appKey` is a hex string, so comparing \"what's installed\" to \"what the group\n * targets\" needs one side converted. Decoding Base58 to canonical lowercase hex\n * is the smaller, encoding-agnostic conversion.\n */\n\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Decode a Base58 string to a lowercase hex string (no `0x` prefix). Leading\n * `1` characters map to leading zero bytes, so the byte width is preserved.\n * Throws on any character outside the Base58 alphabet.\n */\nexport function base58ToHex(input: string): string {\n const bytes: number[] = [];\n for (const char of input) {\n let carry = ALPHABET.indexOf(char);\n if (carry === -1) throw new Error(`invalid base58 character: ${char}`);\n for (let i = 0; i < bytes.length; i++) {\n carry += bytes[i] * 58;\n bytes[i] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n for (let k = 0; k < input.length && input[k] === '1'; k++) bytes.push(0);\n return bytes\n .reverse()\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","import { useState, useCallback, useEffect, useMemo, useRef } from 'react';\nimport { classifyError, compareSemver, memberJoinedOpenOp, signerFromSecret } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { base58ToHex } from '../utils/base58';\nimport { listDelegatedContexts, listDelegatedNamespaces, readDelegatedSession } from '@calimero-network/mero-js';\nimport { governRoot } from '@calimero-network/mero-js';\nimport { createDelegatedContext, createDelegatedPrivateContext } from '@calimero-network/mero-js';\nimport type {\n Codec,\n EphemeralClient,\n Context,\n CreateContextRequest,\n CreateGroupInvitationRequest,\n CreateGroupInNamespaceRequest,\n CreateNamespaceInvitationRequest,\n CreateNamespaceInvitationResponseData,\n CreateNamespaceRequest,\n CreateRecursiveInvitationResponseData,\n GetBlobInfoResponseData,\n GroupContextEntry,\n GroupInfo,\n GroupUpgradeStatusResponseData,\n MetadataRecord,\n JoinGroupRequest,\n JoinNamespaceRequest,\n ListGroupMembersResponseData,\n Namespace,\n NamespaceIdentity,\n NodeIdentity,\n ReparentGroupRequest,\n AddGroupMembersRequest,\n RemoveGroupMembersRequest,\n SetDefaultCapabilitiesRequest,\n SetMetadataRequest,\n SetSubgroupVisibilityRequest,\n SetTeeAdmissionPolicyRequest,\n SubgroupEntry,\n SseEventData,\n UpdateMemberRoleRequest,\n UpgradeGroupRequest,\n UploadBlobRequest,\n ResyncContextRequest,\n MigrationStatus,\n MemberMigrationStatusEntry,\n MigrationStatusRollup,\n MigrateMyEntriesSummary,\n AppVersionChangedEvent,\n GroupMembershipEventData,\n GroupMigrationEventData,\n ClassifiedError,\n RedeemOutcome,\n} from '@calimero-network/mero-js';\nimport type {\n ApplicationContextRecord,\n ContextDiscoveryOptions,\n ContextDiscoveryState,\n} from '../types';\n\nexport { useMero } from '../context';\n\n/**\n * The presence types come straight from `mero-js` now — `Codec` and\n * `EphemeralEntry` are its own declarations, and `EphemeralClient` is the type\n * of the class behind `mero.ephemeral`, so a drift between what this hook\n * assumes and what the SDK does is a compile error rather than a runtime\n * surprise.\n *\n * Re-exported under the same names this package has always exported, so\n * consumers importing `Codec` / `EphemeralEntry` / `EphemeralClient` from\n * `@calimero-network/mero-react` keep compiling — they now simply get the\n * nominal `mero-js` types instead of structural copies of them.\n *\n * On `EphemeralEntry.ageMs`: it is ABSENT on a live delta and PRESENT on a\n * replayed seed entry, reporting how stale that entry already was (bounded by\n * the node's presence TTL). Absent and `0` are different — a `0` means \"the\n * node replayed this and it is brand new\", not \"no age information\". Read it\n * with `?? 0`, never with a truthiness check.\n */\nexport type { Codec, EphemeralEntry, EphemeralClient } from '@calimero-network/mero-js';\n\nexport interface UseEphemeralOptions<T> {\n /** Encoding for the presence slice. Defaults to JSON. */\n codec?: Codec<T>;\n /** Base value for the first `setPresence` merge. */\n initial?: T;\n /** Minimum ms between publishes. Trailing edge — the latest value wins. */\n throttleMs?: number;\n /** Include your own echoed presence in `peers`. Default false. */\n includeSelf?: boolean;\n}\n\n/** Shape returned by {@link useEphemeral}. */\nexport interface UseEphemeralResult<T> {\n peers: Map<string, T>;\n setPresence: (partial: Partial<T>) => void;\n ageOf: (author: string) => number | undefined;\n error: Error | null;\n}\n\n/**\n * Which asynchronous producer currently owns the latched error slot.\n *\n * Only genuinely ASYNCHRONOUS failures are latched — an event happened once,\n * in the past, and nothing about the current render can re-derive it. Anything\n * that is a standing property of the current props/client (notably \"this\n * client has no `mero.ephemeral` surface\") is NOT latched: it is recomputed\n * every render, so it can neither go stale nor be accidentally cleared.\n *\n * The slot is shared, so each producer only clears what it itself raised.\n */\ntype ErrorSource = 'identity' | 'publish';\n\n/**\n * The latched async error, tagged with its producer AND with the context it\n * belongs to.\n *\n * `contextKey` is what makes cross-context leaks structurally impossible\n * rather than a matter of remembering to clear: a write whose key is no longer\n * the current context is dropped on the way in (a publish that was in flight\n * across a context switch), and a latch whose key no longer matches is not\n * read on the way out. Neither path depends on some other effect having run a\n * clear first.\n */\ninterface LatchedEphemeralError {\n contextKey: string | null;\n source: ErrorSource;\n error: Error;\n}\n\nconst NO_EPHEMERAL_SURFACE_MESSAGE =\n 'useEphemeral: this client has no `mero.ephemeral` surface. Ephemeral ' +\n 'presence requires @calimero-network/mero-js >= 9.1.0; upgrade the ' +\n 'installed @calimero-network/mero-js (and any lockfile pin) to use it.';\n\nconst COULD_NOT_RESOLVE_IDENTITY_MESSAGE =\n 'useEphemeral: could not resolve a local context identity, so your own ' +\n 'presence cannot be filtered out. Pass includeSelf: true to accept this.';\n\n/**\n * How long after the last replayed entry (one carrying `ageMs`) the replay\n * window stays open before `peers` is reconciled down to what the replay\n * contained. Long enough to absorb a replay burst split across several SSE\n * frames/ticks, short enough that a swept peer does not linger.\n */\nconst REPLAY_RECONCILE_MS = 50;\n\n/**\n * Observe and publish ephemeral presence (cursors, typing, online) for a\n * context.\n *\n * ONE read path: the subscription. When a client subscribes, the node replays\n * that context's current presence to that connection as ordinary entries\n * before the live deltas start, so seeding and updating share a single shape\n * ({@link EphemeralEntry}) and a reconnect — `SseClient` auto-reconnects and\n * re-subscribes — re-seeds itself. There is no snapshot fetch and no\n * client-side reconciliation pass.\n *\n * Freshness is computed entirely from local clock deltas: a replayed entry is\n * current as of `Date.now() - ageMs`, a live delta as of `Date.now()`. No\n * cross-machine clock comparison is ever performed.\n *\n * No client-side TTL or heartbeat: the node sweeps at 7s and emits removals,\n * and re-publishes on your behalf every 2.5s. A replay is treated as\n * AUTHORITATIVE — see the replay-reconcile pass in the read effect — so a peer\n * swept while the SSE connection was down does not survive the reconnect.\n *\n * `error` is derived, not accumulated: standing conditions (no `ephemeral`\n * surface) are recomputed every render, one-shot async failures are latched\n * keyed by the context they happened in, and whether a latched failure is even\n * relevant (an unresolved identity when `includeSelf` is true) is decided at\n * read time. Nothing survives a context switch.\n */\nexport function useEphemeral<T>(\n contextId: string | null,\n options: UseEphemeralOptions<T> = {},\n): UseEphemeralResult<T> {\n const { includeSelf = false } = options;\n const { mero } = useMero();\n // Cast: the installed mero-js's `MeroJs` type predates `ephemeral` (see\n // `EphemeralClient` above), though it exists at runtime.\n const ephemeral = mero\n ? ((mero as unknown as { ephemeral?: EphemeralClient }).ephemeral ?? null)\n : null;\n\n const [peers, setPeers] = useState<Map<string, T>>(new Map());\n // The one latched async error (see `LatchedEphemeralError`). Not read\n // directly — `error` below derives what is actually reported from it.\n const [latchedError, setLatchedError] = useState<LatchedEphemeralError | null>(null);\n // The context the CURRENT render targets. Read by `setSourceError` so a\n // callback that resolves after a context switch can tell that its result is\n // no longer wanted without closing over anything but its own captured key.\n const contextKeyRef = useRef<string | null>(contextId);\n contextKeyRef.current = contextId;\n // `key` is the contextId captured when the failing operation was STARTED,\n // not when it settled. A late write from a context we have already left is\n // dropped here rather than being written and then hopefully cleared.\n const setSourceError = useCallback(\n (source: ErrorSource, err: Error, key: string | null) => {\n if (key !== contextKeyRef.current) return;\n setLatchedError({ contextKey: key, source, error: err });\n },\n [],\n );\n const clearSourceError = useCallback((source: ErrorSource, key: string | null) => {\n setLatchedError(prev =>\n prev && prev.source === source && prev.contextKey === key ? null : prev,\n );\n }, []);\n\n // DERIVED, never latched: \"this client has no `mero.ephemeral` surface\" is a\n // standing property of the current client, not an event. Recomputing it every\n // render is what makes it impossible to (a) leave it set after an upgraded\n // client arrives or (b) lose it to some other effect's clear — a context\n // switch, for instance, cannot hide a client that still has no surface.\n // Memoised only so the Error identity is stable while the condition holds.\n const surfaceError = useMemo(\n () => (mero && !ephemeral ? new Error(NO_EPHEMERAL_SURFACE_MESSAGE) : null),\n [mero, ephemeral],\n );\n\n // A latch is reported only if it belongs to the context being rendered, and\n // only if it is still MEANINGFUL: an unresolved local identity is an error\n // solely because self-filtering needs it, so opting into `includeSelf` makes\n // it a non-event — decided here, at read time, rather than by racing an\n // effect to clear it.\n const error =\n surfaceError ??\n (latchedError &&\n latchedError.contextKey === contextId &&\n !(latchedError.source === 'identity' && includeSelf)\n ? latchedError.error\n : null);\n // author -> local ms timestamp the entry is considered current as of.\n const receivedAtRef = useRef<Map<string, number>>(new Map());\n // `codec` and `initial` are held in refs, never in a dependency array:\n // `jsonCodec()` is a FACTORY, so `{ codec: jsonCodec() }` at the call site is\n // a fresh identity every render. As a dep it would tear down and re-create\n // the subscription on every render — and since every applied entry sets a\n // new Map (a new render), that is an unbounded resubscribe storm, each\n // resubscribe pulling a fresh presence replay. A codec swapped mid-flight is\n // not a real use case.\n const codecRef = useRef<Codec<T> | undefined>(options.codec);\n codecRef.current = options.codec;\n const initialRef = useRef<T | undefined>(options.initial);\n initialRef.current = options.initial;\n // This node's own context member key (device-level), resolved async. Never\n // compare this against an account id — that comparison silently never\n // matches, which is the classic self-echo bug.\n const selfRef = useRef<string | null>(null);\n const lastLocalRef = useRef<T | undefined>(options.initial);\n const pendingRef = useRef<T | undefined>(undefined);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n // Seeded to the mount time (not 0) so an isolated call shortly after mount\n // is correctly treated as part of the initial \"burst\" and trailing-edge\n // throttled, rather than bypassing the throttle because it looks like it's\n // arriving long after a (nonexistent) previous publish.\n const lastSentAtRef = useRef<number>(Date.now());\n // Open replay window: the authors seen since a replayed entry (one carrying\n // `ageMs`) last arrived. Null when no replay is in progress.\n const replaySeenRef = useRef<Set<string> | null>(null);\n const replayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const ageOf = useCallback((author: string): number | undefined => {\n const at = receivedAtRef.current.get(author);\n return at === undefined ? undefined : Date.now() - at;\n }, []);\n\n // Clear ALL per-context state synchronously the instant the target context\n // changes. Read state, so a previous context's peers don't keep rendering\n // until the new context's replay arrives — and write state, because a\n // queued publish would otherwise fire into the PREVIOUS context (its\n // `setTimeout` closure captured the old `publish`), and `lastLocalRef` would\n // shallow-merge the old context's fields into the first slice published in\n // the new one. Presence is app-defined data (cursor position, typing target),\n // so both are genuine cross-context writes, not cosmetic leaks.\n //\n // The latched error is dropped here as well, but purely as housekeeping (it\n // is what makes A -> B -> A not resurrect A's old failure). Correctness does\n // not rest on it: the latch carries its own `contextKey`, so an error from a\n // context we have left is neither written nor read regardless of whether this\n // effect ran. The standing surface condition is untouched — it is derived, so\n // it re-reports itself on the very next render if it is still true.\n useEffect(() => {\n setPeers(new Map());\n receivedAtRef.current = new Map();\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n pendingRef.current = undefined;\n lastLocalRef.current = initialRef.current;\n selfRef.current = null;\n setLatchedError(null);\n }, [contextId]);\n\n // Resolve THIS node's context member key — the same value the node stamps\n // as `author` on ephemeral entries.\n useEffect(() => {\n if (!mero || !contextId) return;\n // Captured at START. Everything this effect reports is tagged with it, so\n // a slow lookup that lands after a context switch cannot write into the\n // context we switched to.\n const key = contextId;\n let cancelled = false;\n // The RAW client's lookup, on purpose, unlike every other hook: \"self\" here\n // must be exactly the key the client behind `mero.ephemeral` stamps as\n // `author` on this node's entries, and that is what its own admin API\n // answers. The session `admin` answers for the session instead (an account\n // admin returns the account id), which names a different key and would\n // leave own echoes unfiltered.\n mero.admin\n .getContextIdentitiesOwned(contextId)\n .then(res => {\n if (cancelled) return;\n const self = res.identities?.[0] ?? null;\n selfRef.current = self;\n if (!self) {\n // Latched unconditionally — `includeSelf` is NOT consulted here.\n // Whether an unresolved identity matters is a question about the\n // CURRENT props, so it is answered where `error` is derived; asking\n // it here is what previously left the error stranded when\n // `includeSelf` flipped to true while resolution still failed.\n setSourceError('identity', new Error(COULD_NOT_RESOLVE_IDENTITY_MESSAGE), key);\n return;\n }\n // A later run of this effect (contextId change, includeSelf toggle)\n // resolved a self identity where an earlier run didn't — clear the\n // \"could not resolve\" error this effect itself raised.\n clearSourceError('identity', key);\n // Ordering race: the identity lookup and the subscription's presence\n // replay land independently, so a self entry can already be seeded in\n // `peers`. Retroactively drop it now that we know who \"self\" is.\n if (!includeSelf) {\n receivedAtRef.current.delete(self);\n setPeers(prev => {\n if (!prev.has(self)) return prev;\n const next = new Map(prev);\n next.delete(self);\n return next;\n });\n }\n })\n .catch((err: unknown) => {\n if (!cancelled) {\n setSourceError('identity', toError(err), key);\n }\n });\n return () => { cancelled = true; };\n // `mero` itself is a dep on purpose: a real MeroProvider memoizes its\n // context value, so `mero` only changes identity when the underlying\n // client is actually replaced (e.g. `allowedNodeUrls` changes) — and\n // that replacement is exactly when this effect must re-resolve the\n // local identity against the new client. Keying on presence alone\n // (`Boolean(mero)`) would silently keep resolving against a closed,\n // stale client instance.\n }, [mero, contextId, includeSelf, setSourceError, clearSourceError]);\n\n // The single read path. Subscribing makes the node replay this context's\n // current presence to this connection as ordinary entries, then stream live\n // deltas — so this one handler both seeds and updates, and an SSE reconnect\n // (which re-subscribes) re-seeds without any extra machinery.\n //\n // A REPLAY IS AUTHORITATIVE. The node replays exactly who is present right\n // now; anything we still hold that the replay does not mention is gone.\n // Without reconciling against it, a peer swept while the connection was down\n // is a permanent ghost: its removal event was delivered to nobody, and the\n // replay — which lists only survivors — will never mention it again. That\n // sweep happens inside `SseClient`'s auto-reconnect, so it does NOT re-run\n // this effect; reconciliation has to be driven by the entries themselves,\n // which is why it keys off `ageMs` (present only on replayed entries) rather\n // than off subscribe/unsubscribe. Clearing `peers` eagerly on subscribe would\n // also miss the reconnect case entirely — and would blank the UI on every\n // `includeSelf` toggle.\n //\n // The window closes `REPLAY_RECONCILE_MS` after the last replayed entry, and\n // live entries arriving while it is open count as present too, so a peer that\n // publishes mid-replay is never swept. A replayed entry that somehow arrives\n // after the window closed re-adds its author immediately — the failure mode\n // is a flicker, never a resurrected ghost or a permanent loss.\n useEffect(() => {\n if (!ephemeral || !contextId) return;\n\n const closeReplayWindow = () => {\n replayTimerRef.current = null;\n const seen = replaySeenRef.current;\n replaySeenRef.current = null;\n if (!seen) return;\n setPeers(prev => {\n let next: Map<string, T> | null = null;\n for (const author of prev.keys()) {\n if (seen.has(author)) continue;\n if (!next) next = new Map(prev);\n next.delete(author);\n receivedAtRef.current.delete(author);\n }\n return next ?? prev;\n });\n };\n\n const unsubscribe = ephemeral.subscribe<T>(\n contextId,\n entry => {\n const { author, state } = entry;\n if (entry.ageMs !== undefined) {\n // A replayed entry: (re)open the reconcile window and debounce its\n // close, so a replay burst split across frames counts as one replay.\n if (!replaySeenRef.current) replaySeenRef.current = new Set();\n if (replayTimerRef.current) clearTimeout(replayTimerRef.current);\n replayTimerRef.current = setTimeout(closeReplayWindow, REPLAY_RECONCILE_MS);\n }\n if (entry.removed || state === undefined) {\n replaySeenRef.current?.delete(author);\n receivedAtRef.current.delete(author);\n setPeers(prev => {\n if (!prev.has(author)) return prev;\n const next = new Map(prev);\n next.delete(author);\n return next;\n });\n return;\n }\n if (!includeSelf && author === selfRef.current) return;\n replaySeenRef.current?.add(author);\n // `ageMs` is absent on a live delta (current as of now) and present on\n // a replayed entry (current as of `now - ageMs`). `?? 0` — never a\n // truthiness test: an `ageMs` of 0 is a real, meaningful value.\n receivedAtRef.current.set(author, Date.now() - (entry.ageMs ?? 0));\n setPeers(prev => new Map(prev).set(author, state));\n },\n codecRef.current,\n );\n\n return () => {\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n unsubscribe();\n };\n // `ephemeral` itself is a dep on purpose — see the identity-resolution\n // effect above. A replaced client must re-subscribe against the new\n // client, not keep reading/writing through the old (possibly closed)\n // one. `codec` is deliberately NOT a dep — see `codecRef`.\n }, [ephemeral, contextId, includeSelf]);\n\n const publish = useCallback((value: T) => {\n if (!ephemeral || !contextId) return;\n // Captured at START, like the identity lookup's `key`: `ephemeral.set` is\n // not cancellable, so a rejection can land long after a context switch.\n // Tagging the write with the context it was issued for is what keeps that\n // failure out of the new context's error slot.\n const key = contextId;\n lastSentAtRef.current = Date.now();\n void ephemeral.set<T>(key, value, codecRef.current).then(\n () => clearSourceError('publish', key),\n (err: unknown) => setSourceError('publish', toError(err), key),\n );\n }, [ephemeral, contextId, setSourceError, clearSourceError]);\n\n /**\n * Publish your own presence.\n *\n * SHALLOW merge over the last locally-set value (starting from `initial`):\n * presence is one slot per author, so fields are not independent channels\n * and a bare replace would silently drop whatever you did not mention.\n * Nested objects are replaced wholesale, not deep-merged —\n * `setPresence({ cursor: { x: 1 } })` DROPS `cursor.y` if it was set\n * separately.\n *\n * Throttled on the trailing edge: rapid calls collapse into one publish\n * carrying the newest value, never the oldest queued one.\n */\n const setPresence = useCallback((partial: Partial<T>) => {\n const next = { ...(lastLocalRef.current ?? ({} as T)), ...partial } as T;\n lastLocalRef.current = next;\n\n const throttleMs = options.throttleMs ?? 30;\n if (throttleMs <= 0) {\n publish(next);\n return;\n }\n\n pendingRef.current = next;\n if (timerRef.current) return;\n const elapsed = Date.now() - lastSentAtRef.current;\n const delay = Math.max(throttleMs - elapsed, 0);\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n const queued = pendingRef.current;\n pendingRef.current = undefined;\n if (queued !== undefined) publish(queued);\n }, delay);\n }, [publish, options.throttleMs]);\n\n // Cancel a queued publish on unmount.\n useEffect(() => () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n }, []);\n\n return { peers, setPresence, ageOf, error };\n}\n\n/**\n * Shape accepted by the metadata-setter hooks — re-exported from mero-js so\n * callers have one canonical type. A `set*Metadata` call **replaces the whole\n * record**: `data` defaults to `{}` and wholly replaces the stored map; omit\n * `name` to keep the current name.\n */\nexport type SetMetadataInput = SetMetadataRequest;\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction mapApplicationContexts(contexts: Context[]): ApplicationContextRecord[] {\n return contexts.map((context) => ({\n contextId: context.id,\n applicationId: context.applicationId,\n }));\n}\n\nfunction useMountedRef() {\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n return mountedRef;\n}\n\n/** Options a mutation hook that can fail meaningfully accepts. */\nexport interface MutationOptions {\n /**\n * Rethrow a failed request from the action, after recording it in `error`\n * and `failure`.\n *\n * By default an action resolves `null` on failure, which a caller awaiting it\n * cannot tell apart from \"not connected\" — and a `catch` around it never\n * runs, so a refused join reads as a successful one. Set this when the\n * caller branches on the outcome.\n */\n throwOnError?: boolean;\n}\n\nfunction useAsyncMutation({ throwOnError = false }: MutationOptions = {}) {\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [failure, setFailure] = useState<ClassifiedError | null>(null);\n\n const run = useCallback(\n async <T,>(action: () => Promise<T>): Promise<T | null> => {\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n setFailure(null);\n }\n\n try {\n return await action();\n } catch (err) {\n if (mountedRef.current) {\n setError(toError(err));\n setFailure(classifyError(err));\n }\n // The original error, not the wrapped one: it carries the status.\n if (throwOnError) throw err;\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [mountedRef, throwOnError],\n );\n\n return { loading, error, failure, run, setError };\n}\n\n/**\n * Generic read resource: fetch + loading/error/data with a latest-request-wins\n * guard. `fetcher` is null when the read is disabled (missing args) — the\n * resource resets to `initialValue` and nothing is fetched. `deps` drive both\n * the refetch and a synchronous reset when they change, so a slow earlier\n * request can never overwrite a newer one. This is the staleness guard the read\n * hooks used to hand-roll (and mostly lacked), now in one place.\n */\nfunction useAsyncResource<T>(\n fetcher: (() => Promise<T>) | null,\n initialValue: T,\n deps: readonly unknown[],\n): { data: T; loading: boolean; error: Error | null; refetch: () => Promise<void> } {\n const mountedRef = useMountedRef();\n const [data, setData] = useState<T>(initialValue);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const reqRef = useRef(0);\n\n // fetcherRef is refreshed every render so refetch() always calls the latest\n // closure; initialRef captures the (per-hook constant) initial value once.\n // Neither is a dependency — adding them would break latest-request-wins.\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n const initialRef = useRef(initialValue);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n const fn = fetcherRef.current;\n if (!fn) {\n if (mountedRef.current && seq === reqRef.current) {\n setData(initialRef.current);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await fn();\n if (mountedRef.current && seq === reqRef.current) setData(result);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, deps);\n\n // Invalidate any in-flight request and drop the previous key's data DURING\n // RENDER, not in an effect. An effect leaves one render where `data` still\n // answers for the old inputs, and a consumer that persists what it sees\n // (a \"this member already has a name\" marker, say) makes that transient\n // staleness permanent.\n const prevDeps = useRef(deps);\n if (\n deps.length !== prevDeps.current.length ||\n deps.some((d, i) => !Object.is(d, prevDeps.current[i]))\n ) {\n prevDeps.current = deps;\n reqRef.current += 1;\n setData(initialRef.current);\n setError(null);\n }\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction extractAliasContextId(value: unknown): string | null {\n if (typeof value === 'string') {\n return value;\n }\n\n if (!value || typeof value !== 'object') {\n return null;\n }\n\n if ('value' in value && typeof value.value === 'string') {\n return value.value;\n }\n\n if ('contextId' in value && typeof value.contextId === 'string') {\n return value.contextId;\n }\n\n return null;\n}\n\n/**\n * Execute RPC methods against a context.\n * Tracks loading/error state. Unmount-safe.\n */\nexport function useExecute(contextId: string | null, executorId: string | null) {\n const { mero, isDelegated } = useMero();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const execute = useCallback(\n async <T = unknown>(method: string, params?: Record<string, unknown>): Promise<T | null> => {\n if (!mero || !contextId || !executorId) {\n // A delegated session with no client is one specific, ordinary state —\n // an account that has not been invited anywhere yet, so the cloud names\n // no relay for it — and it must not report as \"Not connected\", because\n // the account IS connected and re-authenticating cures nothing. The cure\n // is an invitation, so the message says so.\n if (mountedRef.current) {\n setError(\n new Error(\n !mero && isDelegated\n ? 'No relay for this account yet, so there is nowhere to send this write. ' +\n 'Redeeming an invitation admits the account to a namespace and gives it a ' +\n 'relay; reads and events resume with it.'\n : 'Not connected',\n ),\n );\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await mero.rpc.execute<T>({\n contextId,\n method,\n argsJson: params,\n executorPublicKey: executorId,\n });\n return result;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n if (mountedRef.current) setError(e);\n return null;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [mero, contextId, executorId, isDelegated],\n );\n\n return { execute, loading, error };\n}\n\n/** Event payload delivered to a `useSubscription` callback. */\nexport type SubscriptionEventData =\n | SseEventData\n | GroupMembershipEventData\n | GroupMigrationEventData;\n\n/** Ids to subscribe to. Either can be omitted, but not both. */\nexport interface SubscriptionInput {\n contextIds?: string[];\n groupIds?: string[];\n}\n\n/**\n * Subscribe to SSE events for context and/or group IDs.\n * StrictMode-safe: tracks the SseClient instance in a ref to avoid\n * double-connect on mount/unmount/remount cycles.\n */\nexport function useSubscription(\n contextIds: string[],\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: string[] | SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n) {\n const { mero } = useMero();\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n const { contextIds = [], groupIds = [] } = Array.isArray(input)\n ? { contextIds: input, groupIds: [] as string[] }\n : input;\n\n const contextIdsKey = JSON.stringify(contextIds);\n const groupIdsKey = JSON.stringify(groupIds);\n\n useEffect(() => {\n if (!mero || (contextIds.length === 0 && groupIds.length === 0)) return;\n\n const sse = mero.events;\n\n const handler = (event: SubscriptionEventData) => {\n callbackRef.current(event);\n };\n\n sse.on('event', handler);\n sse.connect().catch(() => {});\n sse.subscribe({ contextIds, groupIds }).catch(() => {});\n\n return () => {\n sse.off('event', handler);\n };\n }, [mero, contextIdsKey, groupIdsKey]);\n}\n\n/**\n * Fetch contexts for the current node, optionally filtered by application ID.\n */\nexport function useContexts(applicationId?: string | null) {\n const { admin, isDelegated } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ApplicationContextRecord[]>(\n admin\n ? async () => {\n // A delegated session may list only its own contexts: the\n // per-application listing is node-wide, so a relay refuses it (403).\n // The caller-scoped `getContexts` carries each context's application,\n // so filter here instead.\n if (isDelegated) {\n // Across every relay this account uses: its namespaces may each be\n // served by a different one, and each relay lists only its own.\n const session = readDelegatedSession();\n const listed = session ? await listDelegatedContexts(session) : [];\n const own = listed.filter(\n (c) => !applicationId || c.applicationId === applicationId,\n );\n return mapApplicationContexts(own);\n }\n const response = applicationId\n ? await admin.getContextsForApplication(applicationId)\n : await admin.getContexts();\n return mapApplicationContexts(response.contexts ?? []);\n }\n : null,\n [],\n [admin, applicationId, isDelegated],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useApplicationContexts(applicationId?: string | null) {\n return useContexts(applicationId);\n}\n\nexport function useGroupMembers(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ListGroupMembersResponseData | null>(\n admin && groupId ? () => admin.listGroupMembers(groupId) : null,\n null,\n [admin, groupId],\n );\n // `members` is a guaranteed array on the wire; `?? []` guards mocks / drift.\n return {\n members: data?.members ?? [],\n loading,\n error,\n refetch,\n };\n}\n\nexport function useGroupContexts(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupContextEntry[]>(\n admin && groupId ? () => admin.listGroupContexts(groupId) : null,\n [],\n [admin, groupId],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useGroupInvitations() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createInvitation = useCallback(\n async (groupId: string, request?: CreateGroupInvitationRequest) => {\n if (!admin) {\n return null;\n }\n return run(() => admin.createGroupInvitation(groupId, request));\n },\n [admin, run],\n );\n\n return { createInvitation, loading, error };\n}\n\nexport function useJoinGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinGroup = useCallback(\n async (request: JoinGroupRequest) => {\n if (!admin) {\n return null;\n }\n return run(() => admin.joinGroup(request));\n },\n [admin, run],\n );\n\n return { joinGroup, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useGroupCapabilities(groupId?: string | null, memberId?: string | null) {\n const { admin } = useMero();\n const [capabilities, setCapabilitiesState] = useState<number | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Read+write hybrid (setCapabilities shares this state), so it keeps the\n // inline latest-request-wins guard rather than useAsyncResource.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !groupId || !memberId) {\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(null);\n setError(null);\n setLoading(false);\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const response = await admin.getMemberCapabilities(groupId, memberId);\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(response.capabilities);\n }\n return response.capabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, memberId, admin, mountedRef]);\n\n useEffect(() => {\n reqRef.current += 1;\n setCapabilitiesState(null);\n setError(null);\n }, [groupId, memberId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n const setCapabilities = useCallback(\n async (nextCapabilities: number) => {\n if (!admin || !groupId || !memberId) {\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n await admin.setMemberCapabilities(groupId, memberId, { capabilities: nextCapabilities });\n if (mountedRef.current) {\n setCapabilitiesState(nextCapabilities);\n }\n return nextCapabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [groupId, memberId, admin, mountedRef],\n );\n\n return { capabilities, loading, error, refetch, setCapabilities };\n}\n\nexport function useContextDiscovery(options: ContextDiscoveryOptions): ContextDiscoveryState {\n const { admin } = useMero();\n const [context, setContext] = useState<ApplicationContextRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n\n const knownContextIdsKey = JSON.stringify(options.knownContextIds ?? []);\n\n const discover = useCallback(async () => {\n if (!admin) {\n const notConnectedError = new Error('Not connected');\n if (mountedRef.current) {\n setError(notConnectedError);\n }\n return null;\n }\n const knownContextIds = new Set(options.knownContextIds ?? []);\n const pollIntervalMs = options.pollIntervalMs ?? 1000;\n const timeoutMs = options.timeoutMs ?? 30000;\n const deadline = Date.now() + timeoutMs;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n while (Date.now() <= deadline) {\n if (options.targetAlias) {\n const aliasMatch = extractAliasContextId(\n await admin.lookupContextAlias(options.targetAlias),\n );\n\n if (aliasMatch && !knownContextIds.has(aliasMatch)) {\n const discoveredFromAlias = {\n contextId: aliasMatch,\n applicationId: options.applicationId,\n };\n\n if (mountedRef.current) {\n setContext(discoveredFromAlias);\n }\n\n return discoveredFromAlias;\n }\n }\n\n const response = await admin.getContextsForApplication(options.applicationId);\n const contexts = mapApplicationContexts(response.contexts ?? []);\n const discovered = contexts.find(\n (applicationContext) => !knownContextIds.has(applicationContext.contextId),\n );\n\n if (discovered) {\n if (mountedRef.current) {\n setContext(discovered);\n }\n return discovered;\n }\n\n if (Date.now() + pollIntervalMs > deadline) {\n break;\n }\n\n await sleep(pollIntervalMs);\n }\n\n const timeoutError = new Error(\n `Timed out discovering a context for application ${options.applicationId}`,\n );\n\n if (mountedRef.current) {\n setContext(null);\n setError(timeoutError);\n }\n\n return null;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setContext(null);\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n }, [\n knownContextIdsKey,\n admin,\n mountedRef,\n options.applicationId,\n options.knownContextIds,\n options.pollIntervalMs,\n options.targetAlias,\n options.timeoutMs,\n ]);\n\n const reset = useCallback(() => {\n if (mountedRef.current) {\n setContext(null);\n setError(null);\n setLoading(false);\n }\n }, [mountedRef]);\n\n return { context, loading, error, discover, reset };\n}\n\n// ---- Context CRUD Hooks ----\n\nexport function useCreateContext() {\n const { admin, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createContext = useCallback(\n async (request: CreateContextRequest) => {\n if (isDelegated) {\n // An account creates a context through the relay serving the namespace,\n // under a creation warrant (mero-js createDelegatedContext).\n const session = readDelegatedSession();\n if (!session || !request.groupId) return null;\n return run(() =>\n createDelegatedContext(session, {\n namespaceId: request.groupId!,\n applicationId: request.applicationId,\n serviceName: request.serviceName,\n contextSeed: request.contextSeed,\n name: request.name,\n initializationParams: request.initializationParams as number[] | undefined,\n }),\n );\n }\n if (!admin) return null;\n return run(() => admin.createContext(request));\n },\n [admin, run, isDelegated],\n );\n\n return { createContext, loading, error };\n}\n\nexport interface CreatePrivateContextRequest {\n readonly namespaceId: string;\n readonly applicationId: string;\n /** The accounts that share it with you, and nobody else — e.g. the other person of a DM. */\n readonly members: readonly string[];\n readonly initializationParams?: number[];\n}\n\n/**\n * Create a context only you and `members` are in (a DM, a small room): its own\n * restricted group in the namespace, members added directly — they are in the\n * namespace already, so nobody is invited. Same call on either connection:\n *\n * - a node login makes the group, adds the members and creates the context\n * with its own admin calls (as mero-chat's DMs do);\n * - an account has the relay serving the namespace do the same three steps,\n * each under its own warrant (mero-js createDelegatedContext).\n */\nexport function useCreatePrivateContext() {\n const { admin, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createPrivateContext = useCallback(\n async (request: CreatePrivateContextRequest): Promise<{ contextId: string } | null> => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => createDelegatedPrivateContext(session, request));\n }\n if (!admin) return null;\n return run(async () => {\n const { groupId } = await admin.createGroupInNamespace(request.namespaceId, {\n visibility: 'restricted',\n });\n // The creator is the new group's admin already; the others join it here.\n await admin.addGroupMembers(groupId, {\n members: request.members.map((identity) => ({ identity, role: 'Member' })),\n });\n const { contextId } = await admin.createContext({\n applicationId: request.applicationId,\n groupId,\n initializationParams: request.initializationParams,\n });\n return { contextId };\n });\n },\n [admin, run, isDelegated],\n );\n\n return { createPrivateContext, loading, error };\n}\n\nexport function useDeleteContext() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteContext = useCallback(\n async (contextId: string) => {\n if (!admin) return null;\n return run(() => admin.deleteContext(contextId));\n },\n [admin, run],\n );\n\n return { deleteContext, loading, error };\n}\n\n/**\n * Join a context. `failure` says what kind of refusal a failed join was, and\n * whether trying again later could work; pass `{ throwOnError: true }` to have\n * `joinContext` reject instead of resolving `null`.\n */\nexport function useJoinContext(options: MutationOptions = {}) {\n const { admin } = useMero();\n const { loading, error, failure, run } = useAsyncMutation(options);\n\n const joinContext = useCallback(\n async (contextId: string) => {\n if (!admin) return null;\n return run(() => admin.joinContext(contextId));\n },\n [admin, run],\n );\n\n return { joinContext, loading, error, failure };\n}\n\nexport function useJoinSubgroupInheritance() {\n const { admin, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinSubgroupInheritance = useCallback(\n async (groupId: string) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n // Joining an open subgroup yourself: a root op carrying your own credential.\n return run(async () => {\n await governRoot(session, groupId, memberJoinedOpenOp({ member: session.account, groupId, credential: session.credential }));\n // An account's identity in the subgroup is its device key: what its ops are signed with.\n const { publicKey } = await signerFromSecret(session.deviceSecret);\n return { groupId, memberPublicKey: publicKey, wasInherited: false };\n });\n }\n if (!admin) return null;\n return run(() => admin.joinSubgroupInheritance(groupId));\n },\n [admin, run, isDelegated],\n );\n\n return { joinSubgroupInheritance, loading, error };\n}\n\nexport function useContextGroup(contextId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n admin && contextId ? () => admin.getContextGroup(contextId) : null,\n null,\n [admin, contextId],\n );\n return { groupId: data, loading, error, refetch };\n}\n\n// ---- Group Info / Management Hooks ----\n\nexport function useGroupInfo(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupInfo | null>(\n admin && groupId ? () => admin.getGroupInfo(groupId) : null,\n null,\n [admin, groupId],\n );\n return { groupInfo: data, loading, error, refetch };\n}\n\nexport function useDeleteGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteGroup = useCallback(\n async (groupId: string) => {\n if (!admin) return null;\n return run(() => admin.deleteGroup(groupId));\n },\n [admin, run],\n );\n\n return { deleteGroup, loading, error };\n}\n\nexport function useSyncGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const syncGroup = useCallback(\n async (groupId: string) => {\n if (!admin) return null;\n return run(() => admin.syncGroup(groupId));\n },\n [admin, run],\n );\n\n return { syncGroup, loading, error };\n}\n\n/**\n * Takes the invitee's signing KEY (bs58) - the one call on this resource that\n * does, because someone being added may have no account here yet. Every other\n * member call, including `useRemoveGroupMembers`, takes the ACCOUNT, so a value\n * round-tripped from an add is the wrong one to remove with.\n */\nexport function useAddGroupMembers() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const addGroupMembers = useCallback(\n async (groupId: string, request: AddGroupMembersRequest) => {\n if (!admin) return null;\n return run(() => admin.addGroupMembers(groupId, request));\n },\n [admin, run],\n );\n\n return { addGroupMembers, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useRemoveGroupMembers() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const removeGroupMembers = useCallback(\n async (groupId: string, request: RemoveGroupMembersRequest) => {\n if (!admin) return null;\n return run(() => admin.removeGroupMembers(groupId, request));\n },\n [admin, run],\n );\n\n return { removeGroupMembers, loading, error };\n}\n\n// ---- Namespace Hooks ----\n\nexport function useNamespaces() {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n admin ? () => admin.listNamespaces() : null,\n [],\n [admin],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useNamespace(namespaceId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace | null>(\n admin && namespaceId ? () => admin.getNamespace(namespaceId) : null,\n null,\n [admin, namespaceId],\n );\n return { namespace: data, loading, error, refetch };\n}\n\n/**\n * Who this node is: `accountId` is what member-addressing takes and what\n * `useGroupMembers` rows are keyed by — `publicKey` is the signing key and\n * addresses nobody. Both are 32-byte strings, so a swap fails silently.\n */\nexport function useNodeIdentity() {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NodeIdentity | null>(\n admin ? () => admin.getNodeIdentity() : null,\n null,\n [admin],\n );\n return { identity: data, loading, error, refetch };\n}\n\n/**\n * @deprecated Use {@link useNodeIdentity}. Identity is per-node, not\n * per-namespace, and this no longer gates on participation: it answers for a\n * namespace this node never joined, so `identity != null` is not \"am I a\n * member?\" — ask `useNamespaces` for that. Its `publicKey` is the signing key,\n * NOT the account member-addressing wants.\n */\nexport function useNamespaceIdentity(namespaceId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NamespaceIdentity | null>(\n admin && namespaceId ? () => admin.getNamespaceIdentity(namespaceId) : null,\n null,\n [admin, namespaceId],\n );\n return { identity: data, loading, error, refetch };\n}\n\nexport function useNamespacesForApplication(applicationId?: string | null) {\n const { admin, isDelegated } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n admin && applicationId\n ? isDelegated\n ? async () => {\n // The per-application listing is node-wide, so a relay refuses it to\n // an account; list its own namespaces on every relay and filter.\n const session = readDelegatedSession();\n const listed = session ? await listDelegatedNamespaces(session) : [];\n return listed.filter((ns) => ns.targetApplicationId === applicationId);\n }\n : () => admin.listNamespacesForApplication(applicationId)\n : null,\n [],\n [admin, applicationId, isDelegated],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useCreateNamespace() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespace = useCallback(\n async (request: CreateNamespaceRequest) => {\n if (!admin) return null;\n return run(() => admin.createNamespace(request));\n },\n [admin, run],\n );\n\n return { createNamespace, loading, error };\n}\n\nexport function useDeleteNamespace() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteNamespace = useCallback(\n async (namespaceId: string) => {\n if (!admin) return null;\n return run(() => admin.deleteNamespace(namespaceId));\n },\n [admin, run],\n );\n\n return { deleteNamespace, loading, error };\n}\n\nexport function useCreateNamespaceInvitation() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespaceInvitation = useCallback(\n async (\n namespaceId: string,\n request?: CreateNamespaceInvitationRequest,\n ): Promise<CreateNamespaceInvitationResponseData | CreateRecursiveInvitationResponseData | null> => {\n if (!admin) return null;\n return run(() => admin.createNamespaceInvitation(namespaceId, request));\n },\n [admin, run],\n );\n\n return { createNamespaceInvitation, loading, error };\n}\n\n/**\n * Join a namespace by invitation. `failure` says what kind of refusal a failed\n * join was, and whether trying again later could work; pass\n * `{ throwOnError: true }` to have `joinNamespace` reject instead of resolving\n * `null`.\n *\n * To follow an invitation link, prefer {@link useRedeemInvitation}: it also\n * recognises a join that landed although its request failed.\n */\nexport function useJoinNamespace(options: MutationOptions = {}) {\n const { admin } = useMero();\n const { loading, error, failure, run } = useAsyncMutation(options);\n\n const joinNamespace = useCallback(\n async (namespaceId: string, request: JoinNamespaceRequest) => {\n if (!admin) return null;\n return run(() => admin.joinNamespace(namespaceId, request));\n },\n [admin, run],\n );\n\n return { joinNamespace, loading, error, failure };\n}\n\n/**\n * Follow an invitation: join its namespace once, then check membership, and\n * report what happened as a {@link RedeemOutcome}.\n *\n * Unlike {@link useJoinNamespace}, a request that failed but whose join landed\n * anyway — the desktop proxy aborts at 30s, a join with no member online takes\n * longer — is `already-member`, not a failure. `shouldRetain(outcome)` from\n * mero-js says whether to keep the invitation for another attempt.\n *\n * `redeem` resolves `null` only when there is no client to send it through.\n */\nexport function useRedeemInvitation() {\n const { admin } = useMero();\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [outcome, setOutcome] = useState<RedeemOutcome | null>(null);\n\n const redeem = useCallback(\n async (\n namespaceId: string,\n invitation: JoinNamespaceRequest['invitation'],\n options: { groupName?: string; teamName?: string } = {},\n ): Promise<RedeemOutcome | null> => {\n if (!admin) return null;\n if (mountedRef.current) {\n setLoading(true);\n setOutcome(null);\n }\n try {\n const result = await admin.redeemInvitation(namespaceId, invitation, options);\n if (mountedRef.current) setOutcome(result);\n return result;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [admin, mountedRef],\n );\n\n return { redeem, outcome, loading };\n}\n\nexport function useCreateGroupInNamespace() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createGroupInNamespace = useCallback(\n async (namespaceId: string, request?: CreateGroupInNamespaceRequest) => {\n if (!admin) return null;\n return run(() => admin.createGroupInNamespace(namespaceId, request));\n },\n [admin, run],\n );\n\n return { createGroupInNamespace, loading, error };\n}\n\nexport function useNamespaceGroups(namespaceId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n admin && namespaceId ? () => admin.listNamespaceGroups(namespaceId) : null,\n [],\n [admin, namespaceId],\n );\n return { groups: data, loading, error, refetch };\n}\n\n// ---- Group Settings & Role Management ----\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useUpdateMemberRole() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const updateMemberRole = useCallback(\n async (groupId: string, identity: string, request: UpdateMemberRoleRequest) => {\n if (!admin) return null;\n return run(() => admin.updateMemberRole(groupId, identity, request));\n },\n [admin, run],\n );\n\n return { updateMemberRole, loading, error };\n}\n\nexport function useSetDefaultCapabilities() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setDefaultCapabilities = useCallback(\n async (groupId: string, request: SetDefaultCapabilitiesRequest) => {\n if (!admin) return null;\n return run(() => admin.setDefaultCapabilities(groupId, request));\n },\n [admin, run],\n );\n\n return { setDefaultCapabilities, loading, error };\n}\n\nexport function useSetSubgroupVisibility() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setSubgroupVisibility = useCallback(\n async (groupId: string, request: SetSubgroupVisibilityRequest) => {\n if (!admin) return null;\n return run(() => admin.setSubgroupVisibility(groupId, request));\n },\n [admin, run],\n );\n\n return { setSubgroupVisibility, loading, error };\n}\n\nexport function useDefaultCapabilities(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<number | null>(\n admin && groupId ? () => admin.getDefaultCapabilities(groupId) : null,\n null,\n [admin, groupId],\n );\n return { defaultCapabilities: data, loading, error, refetch };\n}\n\nexport function useSubgroupVisibility(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n admin && groupId ? () => admin.getSubgroupVisibility(groupId) : null,\n null,\n [admin, groupId],\n );\n return { subgroupVisibility: data, loading, error, refetch };\n}\n\nexport function useSetTeeAdmissionPolicy() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setTeeAdmissionPolicy = useCallback(\n async (groupId: string, request: SetTeeAdmissionPolicyRequest) => {\n if (!admin) return null;\n return run(() => admin.setTeeAdmissionPolicy(groupId, request));\n },\n [admin, run],\n );\n\n return { setTeeAdmissionPolicy, loading, error };\n}\n\n// ---- Metadata Hooks ----\n\nexport function useSetGroupMetadata() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setGroupMetadata = useCallback(\n async (groupId: string, request: SetMetadataInput) => {\n if (!admin) return null;\n return run(() => admin.setGroupMetadata(groupId, request));\n },\n [admin, run],\n );\n\n return { setGroupMetadata, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useSetMemberMetadata() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setMemberMetadata = useCallback(\n async (groupId: string, identity: string, request: SetMetadataInput) => {\n if (!admin) return null;\n return run(() => admin.setMemberMetadata(groupId, identity, request));\n },\n [admin, run],\n );\n\n return { setMemberMetadata, loading, error };\n}\n\nexport function useSetContextMetadata() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setContextMetadata = useCallback(\n async (groupId: string, contextId: string, request: SetMetadataInput) => {\n if (!admin) return null;\n return run(() => admin.setContextMetadata(groupId, contextId, request));\n },\n [admin, run],\n );\n\n return { setContextMetadata, loading, error };\n}\n\nexport function useGroupMetadata(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<MetadataRecord | null>(\n admin && groupId ? () => admin.getGroupMetadata(groupId) : null,\n null,\n [admin, groupId],\n );\n return { metadata: data, loading, error, refetch };\n}\n\nexport function useMemberMetadata(groupId?: string | null, identity?: string | null) {\n const { admin } = useMero();\n const [metadata, setMetadata] = useState<MetadataRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Drop the previous (group, member)'s record DURING RENDER. Clearing in an\n // effect leaves one render where `metadata` answers for the pair that was\n // asked about last, and a consumer that persists what it sees turns that\n // transient staleness into a permanent wrong answer.\n const prevKey = useRef<string | null>(null);\n const key = `${groupId ?? ''}:${identity ?? ''}`;\n if (prevKey.current !== null && prevKey.current !== key) {\n setMetadata(null);\n setError(null);\n }\n prevKey.current = key;\n\n // Shared fetch logic for the auto-mount effect and the explicit\n // refetch callable. The per-invocation `signal.aborted` flag covers\n // the response-during-unmount race cleanly without the global\n // mountedRef gate that — under StrictMode-like fast unmount/remount\n // cycles — could leave the hook stuck on `metadata = null` when an\n // in-flight response landed during cleanup and the followup mount's\n // useCallback referential identity hadn't changed enough to re-fire\n // the effect.\n const run = useCallback(\n async (signal: { aborted: boolean }) => {\n if (!admin || !groupId || !identity) {\n if (!signal.aborted) {\n setMetadata(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (!signal.aborted) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await admin.getMemberMetadata(groupId, identity);\n if (!signal.aborted) setMetadata(result);\n } catch (err) {\n if (!signal.aborted) setError(toError(err));\n } finally {\n if (!signal.aborted) setLoading(false);\n }\n },\n [admin, groupId, identity],\n );\n\n useEffect(() => {\n const signal = { aborted: false };\n void run(signal);\n return () => {\n signal.aborted = true;\n };\n }, [run]);\n\n // Explicit refetch — the caller's `await refetch()` resolves only\n // after state has been written (preserves the prior API contract;\n // call sites like `useMemberDisplayName.setName` rely on the new\n // value being readable from state after the await).\n const refetch = useCallback(async () => {\n const signal = { aborted: false };\n await run(signal);\n }, [run]);\n\n return { metadata, loading, error, refetch };\n}\n\n// ---- Group Signing Key, Upgrades & Hierarchy ----\n\nexport function useUpgradeGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const upgradeGroup = useCallback(\n async (groupId: string, request: UpgradeGroupRequest) => {\n if (!admin) return null;\n return run(() => admin.upgradeGroup(groupId, request));\n },\n [admin, run],\n );\n\n return { upgradeGroup, loading, error };\n}\n\n/**\n * Install a registry package version onto the node — the discrete \"Download\"\n * step an Updates flow runs before an `upgradeGroup`. Resolves the installed\n * application id (`InstallApplicationResponseData`). Downloading does not by\n * itself change what any group runs; pair it with a subsequent upgrade.\n */\nexport function useInstallFromRegistry() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n /**\n * ⚠️ NO `registryUrl` ARGUMENT ANY MORE. Since core's registry-only\n * application distribution, a node installs by `package@version` and\n * resolves the artifact against the registry IT is configured with — a\n * client cannot name one. mero-js dropped `installFromRegistry` for\n * `installApplication({ package, version })` to match, so the old third\n * argument had nowhere to go.\n */\n const installFromRegistry = useCallback(\n async (packageName: string, version: string) => {\n if (!admin) return null;\n return run(() => admin.installApplication({ package: packageName, version }));\n },\n [admin, run],\n );\n\n return { installFromRegistry, loading, error };\n}\n\n/**\n * Kick off a full state re-pull for a context — operator recovery for a\n * context stranded mid-sync. `force` re-pulls even when the node does not\n * flag the context as stranded.\n */\nexport function useResyncContext() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const resyncContext = useCallback(\n async (contextId: string, request: ResyncContextRequest = {}) => {\n if (!admin) return null;\n return run(() => admin.resyncContext(contextId, request));\n },\n [admin, run],\n );\n\n return { resyncContext, loading, error };\n}\n\nexport function useGroupUpgradeStatus(groupId?: string | null) {\n const { admin } = useMero();\n const [upgradeStatus, setUpgradeStatus] = useState<GroupUpgradeStatusResponseData>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus) so overlapping refetches\n // can't land out of order and overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !groupId) {\n if (mountedRef.current) {\n setUpgradeStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await admin.getGroupUpgradeStatus(groupId);\n if (mountedRef.current && seq === reqRef.current) {\n setUpgradeStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, admin, mountedRef]);\n\n // Clear stale status synchronously when the target group changes (and\n // invalidate any in-flight refetch), mirroring useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setUpgradeStatus(null);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { upgradeStatus, loading, error, refetch };\n}\n\nexport function useRetryGroupUpgrade() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const retryGroupUpgrade = useCallback(\n async (groupId: string) => {\n if (!admin) return null;\n return run(() => admin.retryGroupUpgrade(groupId));\n },\n [admin, run],\n );\n\n return { retryGroupUpgrade, loading, error };\n}\n\n/** Move `childGroupId` under a new parent. */\nexport function useReparentGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const reparentGroup = useCallback(\n async (childGroupId: string, request: ReparentGroupRequest) => {\n if (!admin) return null;\n return run(() => admin.reparentGroup(childGroupId, request));\n },\n [admin, run],\n );\n\n return { reparentGroup, loading, error };\n}\n\nexport function useSubgroups(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n admin && groupId ? () => admin.listSubgroups(groupId) : null,\n [],\n [admin, groupId],\n );\n return { subgroups: data, loading, error, refetch };\n}\n\n// ---- Context-Group Relationship ----\n\nexport function useDetachContextFromGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const detachContextFromGroup = useCallback(\n async (groupId: string, contextId: string) => {\n if (!admin) return null;\n return run(() => admin.detachContextFromGroup(groupId, contextId));\n },\n [admin, run],\n );\n\n return { detachContextFromGroup, loading, error };\n}\n\n/**\n * Subscribe to a namespace's `GroupMigration` events, invoking `onEvent` per\n * frame and unsubscribing on unmount.\n *\n * A non-admin subscriber never sees `CascadeProgress`; core delivers that to\n * namespace admins only, so a UI must not wait on it to decide progress.\n */\n/**\n * Fallback poll cadence for `useMigrationStatus` when the SSE stream is\n * unavailable (no token, a proxy that buffers, an older node) and the caller\n * named no interval of its own. Chosen to match the heartbeat cadence that\n * migration facts actually arrive on; an explicit `pollIntervalMs` overrides it.\n */\nexport const DEFAULT_MIGRATION_POLL_INTERVAL_MS = 5000;\n\nexport function useMigrationEvents(\n namespaceId: string | null | undefined,\n onEvent: (event: GroupMigrationEventData) => void,\n): boolean {\n const { mero } = useMero();\n const mountedRef = useMountedRef();\n // Whether the stream is actually carrying frames. Callers use it to decide\n // whether they still need a fallback poll, so it must reflect the subscribe\n // ACTUALLY succeeding - not merely that we asked.\n const [live, setLive] = useState(false);\n // Held in a ref so a caller passing an inline arrow does not resubscribe on\n // every render - the subscription's lifetime is the namespace's, not the\n // callback identity's.\n const handlerRef = useRef(onEvent);\n handlerRef.current = onEvent;\n\n useEffect(() => {\n if (!mero || !namespaceId) return;\n const sse = mero.events;\n const unsubscribe = sse.onMigrationEvent((event) => handlerRef.current(event));\n // Sequential, and the result is recorded: connecting but failing to\n // subscribe is still a dead stream, and both used to be swallowed, which\n // left a caller unable to tell a live stream from a silent one.\n let cancelled = false;\n void (async () => {\n try {\n await sse.connect();\n await sse.subscribe({ groupIds: [namespaceId] });\n if (!cancelled && mountedRef.current) setLive(true);\n } catch {\n if (!cancelled && mountedRef.current) setLive(false);\n }\n })();\n return () => {\n cancelled = true;\n if (mountedRef.current) setLive(false);\n unsubscribe();\n };\n }, [mero, namespaceId, mountedRef]);\n\n return live;\n}\n\n/**\n * Migration-status rollup for a namespace (skew #3).\n *\n * Live: subscribes to the `GroupMigration` event family and re-reads on each\n * frame. It re-READS rather than folding the event's counters in, because the\n * rollup is recomputed from raw member rows and is the authoritative answer.\n * `pollIntervalMs` stays as the fallback when SSE is unavailable, and when the\n * caller names none it defaults to `DEFAULT_MIGRATION_POLL_INTERVAL_MS` for\n * exactly as long as the stream is down - so the panel can never sit silently\n * frozen with neither transport.\n * Derived counters are null-safe before the first load.\n */\nexport function useMigrationStatus(\n namespaceId?: string | null,\n options?: { pollIntervalMs?: number },\n) {\n const { admin } = useMero();\n const [status, setStatus] = useState<MigrationStatus | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Monotonic request token: only the latest in-flight request applies its\n // result, so an overlapping poll or a fast namespace change can't let a\n // stale response overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!admin || !namespaceId) {\n if (mountedRef.current) {\n setStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await admin.getMigrationStatus(namespaceId);\n if (mountedRef.current && seq === reqRef.current) {\n setStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [namespaceId, admin, mountedRef]);\n\n // Clear stale state the instant the namespace changes, so the panel shows a\n // loading state rather than the previous namespace's data during the refetch.\n useEffect(() => {\n setStatus(null);\n setError(null);\n }, [namespaceId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Live updates. The frame is a signal, not the answer: it says something\n // moved, and the re-read is what stays authoritative. This runs BEFORE the\n // poll below because whether the stream is genuinely live is what decides\n // if a caller who named no interval needs a fallback poll at all.\n const sseLive = useMigrationEvents(namespaceId, () => void refetch());\n\n // An explicit interval always wins - a caller that asked to poll keeps\n // polling. When none was named, poll only while the stream is NOT live:\n // migration facts arrive by heartbeat gossip with no push transport of their\n // own, so with neither SSE nor an interval the panel loads once and then\n // silently never updates again, with no error to show for it.\n const pollIntervalMs =\n options?.pollIntervalMs ??\n (sseLive ? undefined : DEFAULT_MIGRATION_POLL_INTERVAL_MS);\n useEffect(() => {\n if (!pollIntervalMs || !admin || !namespaceId) return;\n const handle = setInterval(() => void refetch(), pollIntervalMs);\n return () => clearInterval(handle);\n }, [pollIntervalMs, admin, namespaceId, refetch]);\n\n const rollup: MigrationStatusRollup | null = status?.rollup ?? null;\n const members: MemberMigrationStatusEntry[] = status?.members ?? [];\n\n return {\n status,\n rollup,\n members,\n allMigrated: rollup?.allMigrated ?? false,\n /**\n * When this node watched the fleet converge, or `null`. Durable, unlike\n * `allMigrated`, which is recomputed from in-TTL heartbeats and lapses back\n * to false when a member simply goes quiet.\n */\n fleetCompletedAt: status?.fleetCompletedAt ?? null,\n membersPendingSignature: rollup?.membersPendingSignature ?? 0,\n /** Members whose migrate aborted (migration-check failed or apply errored). */\n failed: rollup?.failed ?? 0,\n loading,\n error,\n refetch,\n };\n}\n\n/**\n * Bundle-version skew (#2): reads the context's installed `applicationVersion`\n * (semver) and compares it to the app-declared `expected` build constant. Any\n * mismatch (either direction) is `isStale` → \"reload to update\". Subscribes to\n * `AppVersionChanged` so a live flip updates `appVersion` without a refetch.\n */\nexport function useAppVersion(contextId?: string | null, expected?: string) {\n const { mero, admin } = useMero();\n const [appVersion, setAppVersion] = useState<string | undefined>(undefined);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!admin || !contextId) {\n if (mountedRef.current) {\n setAppVersion(undefined);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const context = await admin.getContext(contextId);\n if (mountedRef.current && seq === reqRef.current) {\n setAppVersion(context.applicationVersion);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [contextId, admin, mountedRef]);\n\n // Reset on context change so a stale version isn't shown during the refetch.\n useEffect(() => {\n setAppVersion(undefined);\n setError(null);\n }, [contextId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !contextId) return;\n const off = mero.events.onAppVersionChanged((event: AppVersionChangedEvent) => {\n if (event.contextId !== contextId) return;\n if (mountedRef.current && event.toVersion) {\n // Invalidate any in-flight refetch so its (older) result can't clobber\n // this live update.\n reqRef.current += 1;\n setAppVersion(event.toVersion);\n }\n });\n return off;\n }, [mero, contextId, mountedRef]);\n\n const isStale = appVersion != null && expected != null && appVersion !== expected;\n\n return { appVersion, expected, isStale, loading, error, refetch };\n}\n\n/**\n * \"Is a newer version available?\" for an Updates view. Reads a package's\n * published versions from the registry and compares the newest to the running\n * `currentVersion` (e.g. a context's `applicationVersion`). `updateAvailable`\n * is true only when the registry's newest is strictly greater. This is the\n * registry-side check the admin acts on; gate rendering on admin status at the\n * call site. Pure read — fetching nothing until both `registryUrl` and\n * `packageName` are provided.\n */\nexport function useLatestVersion(\n registryUrl?: string | null,\n packageName?: string | null,\n currentVersion?: string | null,\n) {\n const { admin } = useMero();\n const [versions, setVersions] = useState<string[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!admin || !registryUrl || !packageName) {\n // Invalidate any in-flight request so a late response can't repopulate\n // stale versions for the previous package after the inputs were cleared.\n reqRef.current += 1;\n if (mountedRef.current) {\n setVersions([]);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await admin.getRegistryVersions(registryUrl, packageName);\n if (mountedRef.current && seq === reqRef.current) {\n setVersions(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [admin, registryUrl, packageName, mountedRef]);\n\n // Clear stale versions the instant the package/registry changes.\n useEffect(() => {\n setVersions([]);\n setError(null);\n }, [registryUrl, packageName]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // getRegistryVersions returns newest-first, so [0] is the latest published.\n const latestVersion = versions[0] ?? null;\n const updateAvailable =\n latestVersion != null &&\n currentVersion != null &&\n compareSemver(latestVersion, currentVersion) > 0;\n\n return { versions, latestVersion, currentVersion, updateAvailable, loading, error, refetch };\n}\n\ninterface GroupAppVersion {\n /** Semver of the application the group currently targets (`null` until loaded). */\n version: string | null;\n /** The group's `targetApplicationId`. */\n applicationId: string | null;\n /** The installed blob differs from the one the group targets (see hook doc). */\n pendingApply: boolean;\n /** Only populated via the group-info path; `null` in the namespace path. */\n activeUpgrade: GroupUpgradeStatusResponseData;\n}\n\nconst EMPTY_GROUP_APP_VERSION: GroupAppVersion = {\n version: null,\n applicationId: null,\n pendingApply: false,\n activeUpgrade: null,\n};\n\n/** An appKey carries no \"pending\" signal when it is absent or all-zero. */\nfunction isZeroAppKey(appKey?: string): boolean {\n return !appKey || /^0+$/.test(appKey);\n}\n\n/**\n * What app version does this group run, and is there a downloaded-but-not-yet-\n * applied update? Replaces the appKey-vs-installed-blob comparison apps\n * otherwise hand-roll: `pendingApply` is true when the group's `appKey` (the\n * blob it targets) is present, non-zero, and differs from the blob actually\n * installed for its `targetApplicationId`. Deciding whether to render or gate on\n * that status (admin-only actions, etc.) is the call site's job.\n *\n * Resolution stays cheap: the group's record comes from `listNamespaces()` when\n * the id is a namespace, else from `getGroupInfo()`; `getApplication()` then\n * reads the installed version and blob. `activeUpgrade` is returned only when it\n * arrives for free on the group-info path (it is not fetched separately).\n * Subscribes to `AppVersionChanged` and refetches, since any version flip in the\n * workspace can make the rollup stale.\n */\nexport function useGroupAppVersion(groupId?: string) {\n const { mero, admin } = useMero();\n const [data, setData] = useState<GroupAppVersion>(EMPTY_GROUP_APP_VERSION);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !groupId) {\n if (mountedRef.current) {\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n // Namespace-first resolution: a top-level group is a namespace; only\n // subgroups need the getGroupInfo fallback (which also carries\n // activeUpgrade, so we surface it without a third call).\n const namespaces = await admin.listNamespaces();\n const namespace = namespaces.find((entry) => entry.namespaceId === groupId);\n\n let appKey: string | undefined;\n let applicationId: string | null;\n let activeUpgrade: GroupUpgradeStatusResponseData = null;\n\n if (namespace) {\n appKey = namespace.appKey;\n applicationId = namespace.targetApplicationId;\n } else {\n const info = await admin.getGroupInfo(groupId);\n appKey = info.appKey;\n applicationId = info.targetApplicationId;\n activeUpgrade = info.activeUpgrade ?? null;\n }\n\n let version: string | null = null;\n let pendingApply = false;\n if (applicationId) {\n const { application } = await admin.getApplication(applicationId);\n version = application?.version ?? null;\n if (application && !isZeroAppKey(appKey)) {\n const installedHex = base58ToHex(application.blob.bytecode).toLowerCase();\n pendingApply = appKey!.toLowerCase() !== installedHex;\n }\n }\n\n if (mountedRef.current && seq === reqRef.current) {\n setData({ version, applicationId, pendingApply, activeUpgrade });\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, admin, mountedRef]);\n\n // Clear stale state synchronously when the target group changes (and\n // invalidate any in-flight refetch). Mirrors useGroupUpgradeStatus.\n useEffect(() => {\n reqRef.current += 1;\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !groupId) return;\n const off = mero.events.onAppVersionChanged(() => {\n if (mountedRef.current) void refetch();\n });\n return off;\n }, [mero, groupId, refetch, mountedRef]);\n\n return { ...data, loading, error, refetch };\n}\n\n/**\n * The caller's own identity-gated entries pending re-signature (skew #1).\n * `pending` is `pendingCount > 0` (from `count_my_pending`); `authorize()` runs\n * the one-tap `migrate_my_entries` convert and folds the resulting `remaining`\n * back into the count.\n */\nexport function useMyAuthoredMigration(contextId?: string | null) {\n const { mero } = useMero();\n const [summary, setSummary] = useState<MigrateMyEntriesSummary | null>(null);\n const [pendingCount, setPendingCount] = useState(0);\n const mountedRef = useMountedRef();\n const { loading, error, run } = useAsyncMutation();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refresh = useCallback(async () => {\n if (!mero || !contextId) {\n if (mountedRef.current) setPendingCount(0);\n return;\n }\n const seq = ++reqRef.current;\n try {\n const count = await mero.rpc.countMyPending(contextId);\n if (mountedRef.current && seq === reqRef.current) setPendingCount(count);\n } catch {\n // best-effort count; leave the previous value on a transient failure\n }\n }, [mero, contextId, mountedRef]);\n\n // Clear stale per-context state synchronously when the target changes (and\n // invalidate any in-flight refresh), so the banner doesn't flash the previous\n // context's count until the new count resolves. Mirrors useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setPendingCount(0);\n setSummary(null);\n }, [contextId]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const authorize = useCallback(async () => {\n if (!mero || !contextId) return null;\n const result = await run(() => mero.rpc.migrateMyEntries(contextId));\n if (result && mountedRef.current) {\n // Invalidate any in-flight refresh so a stale count can't overwrite the\n // authoritative post-convert remaining.\n reqRef.current += 1;\n setSummary(result);\n setPendingCount(result.remaining);\n }\n return result;\n }, [mero, contextId, run, mountedRef]);\n\n return {\n summary,\n pendingCount,\n pending: pendingCount > 0,\n authorize,\n loading,\n error,\n refresh,\n };\n}\n\n// ---- Blob Hooks ----\n\n/**\n * Options for the blob READ hooks.\n *\n * `contextId` is what picks the mode, and the two modes have wildly different\n * costs:\n *\n * - **omitted** — local-only read. The node answers from its own blob store\n * and returns immediately, or 404s.\n * - **supplied** — network discovery. The node probes that context's peers\n * (availability nodes first) for a holder. Core bounds the search by a ~30s\n * deadline, and for {@link useBlobUrl} the byte transfer is on top of that.\n *\n * So `loading` is load-bearing UI state on these hooks, not decoration: a\n * discovery read can plausibly spin for half a minute before it resolves\n * either way. Render a spinner (or a cancel affordance) accordingly.\n */\nexport interface BlobHookOptions {\n /** Context whose peers to probe. Omit for a local-only read. */\n contextId?: string;\n}\n\n/** Options for {@link useBlobUrl}. */\nexport interface UseBlobUrlOptions extends BlobHookOptions {\n /**\n * MIME type stamped on the `Blob` the object URL points at. The blob read\n * itself carries no type, and a peer-sourced answer has no `mimeType` at\n * all, so pass it when the consumer needs one (`<img>` sniffs; a download\n * `<a>` and an `<iframe>` do not).\n */\n type?: string;\n}\n\n/**\n * True when the failure is the node saying \"nobody has this blob\" (HTTP 404)\n * rather than a transport/auth failure.\n *\n * Duck-typed on `status` rather than `instanceof HTTPError`: a consumer app can\n * easily end up with two copies of mero-js (bundled + peer), and an\n * `instanceof` across that boundary silently reports false.\n */\nfunction isBlobNotFound(error: Error | null): boolean {\n return !!error && (error as { status?: unknown }).status === 404;\n}\n\n/**\n * A blob's presence and size, WITHOUT downloading it — the cheap half of the\n * blob surface, and the one to ask before pulling something large.\n *\n * `blobId` follows the same `string | null` convention as the other read\n * hooks: null/undefined means \"no read\", not \"read nothing\" — nothing is\n * fetched and `info` stays null.\n *\n * `hash` and `mimeType` on the result are genuinely optional: a peer probe\n * answers with presence and size only, so a discovery-sourced hit carries\n * neither. `info.source` (`'local' | 'peer'`, undefined on nodes that predate\n * the header) tells the two apart — do not treat a missing `mimeType` as a\n * malformed response.\n *\n * `notFound` distinguishes the legitimate \"no holder\" outcome (the node\n * answered 404) from a transport failure. `error` is set in BOTH cases — this\n * hook does not swallow the 404, it only labels it.\n *\n * Latency: immediate without `contextId`, up to core's ~30s discovery deadline\n * with one. See {@link BlobHookOptions}.\n */\nexport function useBlobInfo(blobId?: string | null, options?: BlobHookOptions) {\n const { admin } = useMero();\n const contextId = options?.contextId;\n const { data, loading, error, refetch } = useAsyncResource<GetBlobInfoResponseData | null>(\n admin && blobId\n ? () => admin.getBlobInfo(blobId, contextId ? { contextId } : undefined)\n : null,\n null,\n [admin, blobId, contextId],\n );\n\n return { info: data, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * A blob's bytes as an object URL, ready for `<img src>`, an `<a href>`\n * download, or an `<iframe>`.\n *\n * Lifecycle is handled here so the consumer never has to revoke: the URL is\n * revoked on unmount, and whenever `blobId`/`contextId`/`type` change. `url`\n * goes back to null synchronously on such a change, so a revoked URL is never\n * handed out as the current one — render off `url` and it is always live.\n *\n * A response for a superseded `blobId` is dropped before an object URL is even\n * created, so an out-of-order arrival can neither overwrite the newer result\n * nor leak.\n *\n * Latency: this is the expensive hook. Without `contextId` it is a local read;\n * with one it is discovery (core's ~30s deadline) PLUS the transfer of the\n * bytes. Prefer {@link useBlobInfo} to decide whether the download is worth\n * starting, and always render `loading`.\n *\n * `notFound` marks the node's 404 (\"no peer holds this\") apart from a\n * transport failure; `error` is set for both.\n */\nexport function useBlobUrl(blobId?: string | null, options?: UseBlobUrlOptions) {\n const { admin } = useMero();\n const contextId = options?.contextId;\n const type = options?.type;\n const mountedRef = useMountedRef();\n const [url, setUrl] = useState<string | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n // Latest-request-wins token, same shape as useAsyncResource's.\n const reqRef = useRef(0);\n // The URL currently handed out, held in a ref so revocation never depends on\n // a render having happened.\n const urlRef = useRef<string | null>(null);\n\n const revoke = useCallback(() => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n }, []);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !blobId) return;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const bytes = await admin.getBlob(blobId, contextId ? { contextId } : undefined);\n // Check BEFORE creating the object URL: a loser allocates nothing, so\n // there is nothing to leak and nothing to overwrite the winner with.\n if (!mountedRef.current || seq !== reqRef.current) return;\n revoke();\n const objectUrl = URL.createObjectURL(new Blob([bytes], type ? { type } : undefined));\n urlRef.current = objectUrl;\n setUrl(objectUrl);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, [admin, blobId, contextId, type, revoke, mountedRef]);\n\n // Invalidate the in-flight request and drop the current URL synchronously\n // when the inputs change, so the consumer never sees the previous blob's URL\n // (revoked or not) attributed to the new id.\n useEffect(() => {\n reqRef.current += 1;\n revoke();\n setUrl(null);\n setError(null);\n setLoading(false);\n }, [admin, blobId, contextId, type, revoke]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Final revoke on unmount. Separate from the input-change effect above so it\n // runs exactly once, on teardown, whatever the deps did.\n useEffect(() => revoke, [revoke]);\n\n return { url, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * Upload bytes to the node's blob store. Mutation-shaped, like the other\n * write hooks: `uploadBlob` resolves to `{ blobId, size }`, or null when the\n * client is absent or the call failed (read `error` for which).\n *\n * Pass `contextId` to announce the blob to that context, which is what lets\n * the context's other members later discover it with {@link useBlobUrl} /\n * {@link useBlobInfo}. Without it the blob is only readable on this node.\n */\nexport function useUploadBlob() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const uploadBlob = useCallback(\n async (request: UploadBlobRequest) => {\n if (!admin) return null;\n return run(() => admin.uploadBlob(request));\n },\n [admin, run],\n );\n\n return { uploadBlob, loading, error };\n}\n","import type { ReactNode } from 'react';\nimport { useMyAuthoredMigration } from '../hooks';\n\nexport interface MigrationPendingBannerProps {\n /** Context whose authored entries to check / convert. */\n contextId: string;\n className?: string;\n /** Override the default prompt text. */\n children?: ReactNode;\n /** Fired once a convert leaves nothing pending (`remaining === 0`). */\n onMigrated?: () => void;\n}\n\n/**\n * Shows only when the current identity has entries below the target schema\n * (skew #1). A single button runs the one-tap `migrate_my_entries` convert and\n * the banner clears itself once nothing is pending.\n */\nexport function MigrationPendingBanner({\n contextId,\n className,\n children,\n onMigrated,\n}: MigrationPendingBannerProps) {\n const { pending, pendingCount, authorize, loading } = useMyAuthoredMigration(contextId);\n\n if (!pending) return null;\n\n const handleClick = async () => {\n const result = await authorize();\n if (result && result.remaining === 0) {\n onMigrated?.();\n }\n };\n\n const message =\n children ??\n `You have ${pendingCount} ${pendingCount === 1 ? 'entry' : 'entries'} to re-sign after a recent upgrade.`;\n\n return (\n <div className={className} data-testid=\"migration-pending-banner\" role=\"status\">\n <span>{message}</span>\n <button type=\"button\" onClick={handleClick} disabled={loading}>\n {loading ? 'Migrating…' : 'Migrate my data'}\n </button>\n </div>\n );\n}\n","import { useMigrationStatus } from '../hooks';\n\nexport interface MigrationAdminPanelProps {\n /** Namespace whose migration rollup to display. */\n namespaceId: string;\n /** Re-fetch interval; migration facts arrive via heartbeat gossip. */\n pollIntervalMs?: number;\n className?: string;\n}\n\n/**\n * Operator view of a namespace's migration rollup (skew #3): the cohort\n * counters, `membersPendingSignature`, and a per-member table. Read-only —\n * pair with the upgrade-trigger hooks to drive a migration.\n */\nexport function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }: MigrationAdminPanelProps) {\n const { status, rollup, members, membersPendingSignature, failed, error } = useMigrationStatus(\n namespaceId,\n { pollIntervalMs },\n );\n\n // Surface a real failure rather than the misleading \"no status\" message.\n if (error && !status) {\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n Failed to load migration status: {error.message}\n </div>\n );\n }\n\n // Before the first successful fetch (initial paint or in-flight), show\n // loading — a successful read always yields a rollup, so a null status here\n // means \"not loaded yet\", never \"empty\".\n if (!status || !rollup) {\n return <div className={className} data-testid=\"migration-admin-panel\">Loading migration status…</div>;\n }\n\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n {error && (\n // A poll failed after data was already loaded — keep showing the last\n // good rollup but flag that it may be stale.\n <div data-testid=\"migration-status-error\" role=\"alert\">\n Could not refresh migration status: {error.message}\n </div>\n )}\n <dl>\n <div><dt>Target version</dt><dd>{status.targetVersion}</dd></div>\n <div><dt>Migrated</dt><dd>{rollup.migrated}</dd></div>\n <div><dt>In progress</dt><dd>{rollup.inProgress}</dd></div>\n <div><dt>Unknown</dt><dd>{rollup.unknown}</dd></div>\n <div><dt>Failed</dt><dd data-testid=\"migration-failed-count\">{failed}</dd></div>\n <div><dt>Total</dt><dd>{rollup.total}</dd></div>\n <div><dt>All migrated</dt><dd>{rollup.allMigrated ? 'yes' : 'no'}</dd></div>\n <div>\n <dt>Members pending signature</dt>\n <dd data-testid=\"members-pending-signature\">{membersPendingSignature}</dd>\n </div>\n </dl>\n <table>\n <thead>\n <tr><th>Peer</th><th>State</th><th>Schema</th><th>Pending</th><th>Reason</th></tr>\n </thead>\n <tbody>\n {members.map((m) => (\n <tr key={m.peer} data-testid=\"migration-member-row\">\n <td>{m.peer}</td>\n <td>{m.state}</td>\n <td>{m.report?.schemaVersion ?? '—'}</td>\n <td>{m.report?.authoredRemaining ?? '—'}</td>\n <td>{m.report?.migrationFailed ?? '—'}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n","/**\n * The delegated connect path, entered from an invitation instead of an account.\n *\n * `ConnectButtonAccount` enrols the device and then asks the cloud which relays\n * serve the ACCOUNT. For a first-time account that answer is `[]` and there is\n * nothing to connect to — correctly, since nothing yet serves an account that is\n * a member of nothing. This hook is the other door into the same connection: it\n * takes an invitation, resolves a relay from the NAMESPACE, presents the signed\n * join, and then connects through the node that carried it.\n *\n * It is `MeroContext`'s own `connectWithAccount` at the end, not a second\n * connection mechanism — the only difference is how the relay was found.\n */\n\nimport { useCallback, useState, useMemo } from 'react';\nimport type { SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport {\n bootstrapFromInvitation,\n type BootstrapResult,\n} from '@calimero-network/mero-js';\nimport {\n carryExecutorAccount,\n readDelegatedCredential,\n readDelegatedSession,\n rememberRelay,\n type DelegatedCredential,\n} from '@calimero-network/mero-js';\n\nexport interface UseDelegatedBootstrapOptions {\n /** Point at a cloud other than the hosted manager. For local rigs. */\n readonly cloudBaseUrl?: string;\n}\n\nexport interface UseDelegatedBootstrapResult {\n /** The enrolled account and its certificate, or `null` if none was ever held. */\n readonly credential: DelegatedCredential | null;\n /**\n * Whether this account is signed in with nowhere to write.\n *\n * True means: an enrolled credential is held and no relay is known for it, so\n * the account→relay lookup has nothing and an invitation is what changes that.\n * Being signed in is NOT the missing part — that is the whole point, since you\n * have to be signed in to be invited.\n *\n * False covers \"already has a relay\" and \"never enrolled\", which need the two\n * other entry points rather than this one.\n */\n readonly needsBootstrap: boolean;\n readonly running: boolean;\n /** The last attempt's outcome, kept so a UI can name the failing step. */\n readonly result: BootstrapResult | null;\n /**\n * Admit this account to the invitation's namespace and connect through the\n * admitting node.\n *\n * Resolves rather than throws for every expected refusal: the step names are\n * the point, because an empty intersection, an unreachable admitter and a\n * namespace with no fleet assignment need three different actions.\n */\n readonly bootstrap: (input: {\n readonly namespaceId: string;\n readonly invitation: SignedGroupOpenInvitation;\n /**\n * A node to present the join to, skipping the cloud lookup — an operator's,\n * a local rig's, or one a future invitation carries.\n */\n readonly nodeUrl?: string;\n /** The context the invitation is for, so its relay is known before any listing. */\n readonly contextId?: string;\n }) => Promise<BootstrapResult>;\n}\n\nexport function useDelegatedBootstrap(\n options: UseDelegatedBootstrapOptions = {},\n): UseDelegatedBootstrapResult {\n const { connectWithAccount, cloudBaseUrl: providerCloud } = useMero();\n const [running, setRunning] = useState(false);\n const [result, setResult] = useState<BootstrapResult | null>(null);\n\n // Read at render rather than held in state: the record is written by the\n // enrolment return in `ConnectButtonAccount`, in the same tab but outside\n // React's knowledge, so a cached copy would be stale exactly once — on the\n // load where it matters.\n //\n // Read every render, but the same object while its contents are the same:\n // a fresh parse each time made every callback below new on every render, and\n // an app with any of them in an effect's dependencies looped (\"Maximum update\n // depth exceeded\").\n const read = readDelegatedCredential();\n const credential = useMemo(\n () => read,\n // Keyed on the contents, not the parsed object.\n [read?.account, read?.credential, read?.deviceSecret],\n );\n // The stored record rather than the context's `nodeUrl`: that one is seeded\n // from `getNodeUrl()`, which can still hold a node URL from an earlier\n // node-login on this origin, and a stale value there would hide the very state\n // this reports.\n const relayUrl = readDelegatedSession()?.relayUrl ?? null;\n\n const cloudBaseUrl = options.cloudBaseUrl ?? providerCloud;\n const bootstrap = useCallback(\n async (input: {\n namespaceId: string;\n invitation: SignedGroupOpenInvitation;\n nodeUrl?: string;\n contextId?: string;\n }): Promise<BootstrapResult> => {\n const held = readDelegatedCredential();\n if (!held) {\n const failure: BootstrapResult = {\n ok: false,\n step: 'no-credential',\n reason:\n 'This tab holds no enrolled account, so there is no identity to admit. Enrol with ' +\n 'your account first — the invitation is then what gives it its first membership.',\n };\n setResult(failure);\n return failure;\n }\n setRunning(true);\n try {\n const outcome = await bootstrapFromInvitation({\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n credential: held,\n nodeUrl: input.nodeUrl,\n cloudBaseUrl,\n });\n setResult(outcome);\n // Connected only on a node that actually took the join. A session\n // installed after a refusal would look connected and refuse every write,\n // which is the failure this whole path exists to avoid.\n if (outcome.ok) {\n // Added to the account's relay map, never replacing it: the relays\n // that serve its other namespaces stay reachable.\n if (outcome.session.relayUrl) {\n rememberRelay(held.account, outcome.session.relayUrl, {\n namespaceId: input.namespaceId,\n contextId: input.contextId,\n });\n }\n connectWithAccount(carryExecutorAccount(readDelegatedSession(), outcome.session));\n }\n return outcome;\n } finally {\n setRunning(false);\n }\n },\n [cloudBaseUrl, connectWithAccount],\n );\n\n return {\n credential,\n needsBootstrap: credential !== null && relayUrl === null,\n running,\n result,\n bootstrap,\n };\n}\n","/**\n * The injected bridge, or `null` outside a capable launcher (SSR, plain tab,\n * PWA, or a launcher too old to inject it).\n */\nexport function getBridge() {\n if (typeof window === \"undefined\")\n return null;\n const b = window.__calimero_platform__;\n if (!b || typeof b !== \"object\")\n return null;\n const bridge = b;\n if (typeof bridge.version !== \"number\" ||\n !Array.isArray(bridge.capabilities) ||\n typeof bridge.invoke !== \"function\" ||\n typeof bridge.on !== \"function\") {\n return null;\n }\n return bridge;\n}\n/** Whether the current launcher advertises a given capability. */\nexport function hasCapability(name) {\n const bridge = getBridge();\n return bridge !== null && bridge.capabilities.includes(name);\n}\n","/**\n * Shareable deep-link generation.\n *\n * Links are ALWAYS HTTPS (`https://links.calimero.network/<slug>/<action>?…`),\n * never `calimero://` — the custom scheme is a device-local transport only. An\n * HTTPS link works everywhere: it opens the web/PWA app directly, and on a\n * device with the desktop installed + associated it hands off to the launcher.\n */\nconst DEFAULT_HOST = \"https://links.calimero.network\";\n/**\n * Build a canonical shareable link.\n *\n * @param slug the app slug (its manifest `handlers.slug`, e.g. `mero-chat`)\n * @param action the intent verb, e.g. `join`\n * @param params query params (values are URL-encoded)\n * @param host override the default host (no trailing slash needed)\n */\nexport function createLink(slug, action, params = {}, host = DEFAULT_HOST) {\n const base = host.replace(/\\/+$/, \"\");\n const path = `${encodeURIComponent(slug)}/${encodeURIComponent(action)}`;\n const url = new URL(`${base}/${path}`);\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, value);\n }\n return url.toString();\n}\n","/**\n * Durable pending-intent store.\n *\n * A deep-link intent (e.g. an invitation) must survive the app's own churn —\n * reload, auth redirect, even install→reopen — until the app explicitly acks\n * it. We persist captured intents to a single storage key (localStorage in the\n * browser; an injected Storage in tests), dedup by a content nonce so the same\n * link arriving from two sources (initial URL + a warm bridge event) is stored\n * once, and drop an intent only on `ack`.\n */\nconst STORAGE_KEY = \"calimero.platform.pendingIntents\";\n/** FNV-1a 32-bit — stable, dependency-free content hash for the dedup nonce. */\nfunction hashNonce(raw) {\n let h = 0x811c9dc5;\n for (let i = 0; i < raw.length; i++) {\n h ^= raw.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\nexport class PendingIntentStore {\n constructor(storage, now = () => Date.now()) {\n this.storage = storage;\n this.now = now;\n }\n read() {\n try {\n const raw = this.storage.getItem(STORAGE_KEY);\n if (!raw)\n return [];\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : [];\n }\n catch {\n return [];\n }\n }\n write(list) {\n try {\n this.storage.setItem(STORAGE_KEY, JSON.stringify(list));\n }\n catch {\n /* storage full / unavailable — the intent is best-effort */\n }\n }\n /** Capture an intent; idempotent by content nonce. Returns the stored entry. */\n capture(raw) {\n const nonce = hashNonce(raw);\n const list = this.read();\n const existing = list.find((i) => i.nonce === nonce);\n if (existing)\n return existing;\n const intent = { nonce, raw, capturedAt: this.now() };\n this.write([...list, intent]);\n return intent;\n }\n /** The oldest unacked intent, or null. */\n peek() {\n return this.read()[0] ?? null;\n }\n /** All unacked intents, oldest first. */\n all() {\n return this.read();\n }\n /** Drop an intent once the app has handled it. */\n ack(nonce) {\n this.write(this.read().filter((i) => i.nonce !== nonce));\n }\n}\n","/**\n * The deep-link controller: one place an app learns \"someone opened me with an\n * intent,\" no matter how it arrived.\n *\n * Sources it merges:\n * - the initial page URL (`location.href` — web/PWA cold open, or the launcher\n * appending `?invitation=…` to the app's frontend URL),\n * - the launcher bridge `deep-link` event (warm: app already open, a new link\n * routed to it),\n * - the PWA `launchQueue` (`targetURL`).\n *\n * All three funnel through the durable {@link PendingIntentStore}, so an intent\n * survives reload/auth/install and is deduped by content nonce (the same link\n * from URL + bridge fires a handler once). A handler registered LATE still\n * receives buffered intents. Each delivered intent carries `resolve()` — the\n * app calls it once handled, which acks the store so it never replays.\n */\n/**\n * Parse a captured raw string into `{ slug, action, params }`.\n *\n * `calimero://<slug>/<action>?…` is split by hand (NOT via `new URL().hostname`)\n * because non-special-scheme host parsing mangles dotted slugs like\n * `com.calimero.curb`. HTTPS/relative URLs use the URL parser; an app's own\n * root URL (`/?invitation=X`) yields null slug/action and just the params.\n */\nexport function parseIntent(raw) {\n const params = {};\n let slug = null;\n let action = null;\n try {\n if (/^calimero:\\/\\//i.test(raw)) {\n const rest = raw.slice(\"calimero://\".length);\n const qIdx = rest.indexOf(\"?\");\n const pathPart = qIdx >= 0 ? rest.slice(0, qIdx) : rest;\n const queryPart = qIdx >= 0 ? rest.slice(qIdx + 1) : \"\";\n const segs = pathPart.split(\"/\").filter(Boolean);\n slug = segs[0] ?? null;\n action = segs[1] ?? null;\n new URLSearchParams(queryPart).forEach((v, k) => (params[k] = v));\n }\n else {\n const url = new URL(raw, \"https://x.invalid/\");\n const segs = url.pathname.replace(/^\\/+|\\/+$/g, \"\").split(\"/\").filter(Boolean);\n slug = segs[0] ?? null;\n action = segs[1] ?? null;\n url.searchParams.forEach((v, k) => (params[k] = v));\n }\n }\n catch {\n /* unparseable — leave nulls / empty params */\n }\n return { slug, action, params };\n}\n/** Does a URL carry a deep-link signal (query or non-root path) worth capturing? */\nfunction hasIntentSignal(href) {\n try {\n const url = new URL(href, \"https://x.invalid/\");\n const segs = url.pathname.replace(/^\\/+|\\/+$/g, \"\").split(\"/\").filter(Boolean);\n return url.search.length > 1 || segs.length > 0;\n }\n catch {\n return false;\n }\n}\nexport class DeepLinkController {\n constructor(store, sources = {}) {\n this.store = store;\n this.handlers = new Set();\n this.delivered = new Set();\n this.unsubscribers = [];\n if (sources.location?.href && hasIntentSignal(sources.location.href)) {\n this.capture(sources.location.href);\n }\n if (sources.bridge) {\n const off = sources.bridge.on(\"deep-link\", (payload) => {\n const raw = extractRaw(payload);\n if (raw)\n this.capture(raw);\n });\n this.unsubscribers.push(off);\n }\n if (sources.launchQueue) {\n sources.launchQueue.setConsumer((p) => {\n if (p?.targetURL && hasIntentSignal(p.targetURL))\n this.capture(p.targetURL);\n });\n }\n }\n /** Register an intent handler; immediately replays buffered (unacked,\n * not-yet-delivered) intents. Returns an unsubscribe fn. */\n on(handler) {\n this.handlers.add(handler);\n for (const stored of this.store.all()) {\n if (!this.delivered.has(stored.nonce)) {\n this.delivered.add(stored.nonce);\n handler(this.toIntent(stored));\n }\n }\n return () => this.handlers.delete(handler);\n }\n /** Tear down source subscriptions + handlers. */\n dispose() {\n for (const off of this.unsubscribers.splice(0))\n off();\n this.handlers.clear();\n }\n capture(raw) {\n const stored = this.store.capture(raw);\n if (this.delivered.has(stored.nonce) || this.handlers.size === 0)\n return;\n this.delivered.add(stored.nonce);\n const intent = this.toIntent(stored);\n for (const handler of this.handlers)\n handler(intent);\n }\n toIntent(stored) {\n return {\n raw: stored.raw,\n ...parseIntent(stored.raw),\n resolve: () => this.store.ack(stored.nonce),\n };\n }\n}\n/** Pull a raw intent string out of a bridge `deep-link` payload (string or\n * `{raw}`/`{url}` object). */\nfunction extractRaw(payload) {\n if (typeof payload === \"string\")\n return payload;\n if (payload && typeof payload === \"object\") {\n const o = payload;\n if (typeof o.raw === \"string\")\n return o.raw;\n if (typeof o.url === \"string\")\n return o.url;\n }\n return null;\n}\n","// ── Capturing an invitation, however it arrived ───────────────────────────────\n//\n// Eleven Calimero apps once carried a near-identical copy of this file; this is\n// the one copy now.\n//\n// Three sources funnel into one controller:\n//\n// * the cold-open URL (web/PWA, or the desktop launcher appending\n// `?invitation=…` to this app's frontend URL),\n// * the launcher's warm `deep-link` bridge event (the app is already open),\n// * the PWA `launchQueue`.\n//\n// The SDK dedups them by content nonce, persists to localStorage so an intent\n// survives a reload and the auth redirect, replays to a handler that registers\n// late, and drops an intent only when the app acks it via `resolve()`.\n//\n// Two consequences worth stating, because hand-rolled versions got both wrong:\n//\n// 1. The landing route does not matter. A handler mounted anywhere sees the\n// intent, so an invitation cannot land on a page that cannot redeem it.\n// 2. Arriving before the session is ready is fine. The intent is buffered\n// until something asks for it, so there is no race with login.\n//\n// Storage note: `localStorage` can throw outright (Safari private mode, a\n// browser set to block site data). The store is built behind a probe so an\n// invitation still works in that session — it just does not survive a reload,\n// which is strictly better than failing to boot.\n\nimport {\n DeepLinkController,\n PendingIntentStore,\n createLink,\n getBridge,\n} from \"@calimero-network/mero-platform\";\n\n/** The action an invite link carries: `calimero://<package>/join?invitation=…`. */\nexport const JOIN_ACTION = \"join\";\n/** The query parameter every app's invite builder emits. */\nexport const INVITATION_PARAM = \"invitation\";\n\n/**\n * The link an inviter shares, for every app: `https://links.calimero.network/<slug>/join?invitation=…`.\n *\n * One shape, so one path gets it into the app. The links page opens the app's\n * frontend with the query appended (web, PWA, a cold desktop start), and a\n * desktop that is already running hands it over as a `deep-link` bridge event;\n * `primeInvitationCapture` listens to both. Nobody pastes it anywhere.\n *\n * `slug` is the app's deep-link handler, which for a Calimero app is its package id.\n * `extra` rides along beside the token, for an app whose link carries more\n * than the token (a display name, a target id).\n */\nexport function buildInviteLink(\n slug: string,\n token: string,\n extra: Record<string, string | undefined> = {},\n): string {\n const params: Record<string, string> = { [INVITATION_PARAM]: token };\n for (const [key, value] of Object.entries(extra)) {\n if (value !== undefined && value !== \"\") params[key] = value;\n }\n return createLink(slug, JOIN_ACTION, params);\n}\n\n/** One captured invitation, with the ack the app owes the store. */\nexport interface CapturedInvitation {\n /** The raw invitation token, ready to parse. */\n token: string;\n /** Every query parameter the link carried, the token included. */\n params: Record<string, string>;\n /** Ack it so the store stops replaying it. Call once handled OR declined. */\n resolve: () => void;\n /**\n * Whether to attempt the join without being asked.\n *\n * False once this invitation has spent its automatic attempts. The token is\n * still handed over — so a field can be prefilled and one click retries it —\n * but a link that can never join stops re-firing on every load.\n */\n autoJoin: boolean;\n}\n\ntype Listener = (invitation: CapturedInvitation) => void;\n\n/** Told whenever `peekInvitation()` would answer differently. */\nconst watchers = new Set<() => void>();\nfunction notifyWatchers(): void {\n for (const watcher of watchers) watcher();\n}\n\n/**\n * How many loads may auto-join one invitation before it needs a human.\n *\n * An unacked intent is replayed on every load by design, so that a transient\n * failure (node still starting, no member online yet) is retried rather than\n * lost. Without a ceiling a *permanent* failure is retried just as eagerly and\n * forever — which is what made every restart of the node re-fire a link that\n * had already been used.\n */\nexport const MAX_AUTO_JOIN_ATTEMPTS = 3;\n\nconst listeners = new Set<Listener>();\n/** Captured but not yet taken by a listener. Replayed to a late subscriber. */\nlet buffered: CapturedInvitation | null = null;\n/**\n * The captured invitation, held for the life of the session rather than\n * consumed on delivery — so code that is not a subscriber can still ask. Used\n * by bootstrap paths that need to know an invitation is inbound before they\n * decide where to send the user.\n */\nlet current: CapturedInvitation | null = null;\nlet controller: DeepLinkController | null = null;\n/** Namespaced per app so two apps on one origin cannot spend each other's budget. */\nlet attemptsKey = \"calimero:invitation-attempts\";\n/** The deep-link slugs that name this app; a `join` for any other slug is not ours. */\nlet ownSlugs: ReadonlySet<string> = new Set();\n\n/**\n * An in-memory Storage, for when the real one throws.\n *\n * Not a no-op: dedup within the session still works, so the same link arriving\n * from the URL and the bridge is handled once. Only cross-reload durability is\n * lost.\n */\nfunction memoryStorage(): Storage {\n const map = new Map<string, string>();\n return {\n get length() {\n return map.size;\n },\n clear: () => map.clear(),\n getItem: (k) => map.get(k) ?? null,\n key: (i) => [...map.keys()][i] ?? null,\n removeItem: (k) => void map.delete(k),\n setItem: (k, v) => void map.set(k, v),\n } as Storage;\n}\n\nfunction storage(): Storage {\n try {\n // Touched, not just referenced: some browsers expose `localStorage` and\n // throw only on access.\n const probe = \"__calimero_invite_probe__\";\n window.localStorage.setItem(probe, \"1\");\n window.localStorage.removeItem(probe);\n return window.localStorage;\n } catch {\n return memoryStorage();\n }\n}\n\nfunction readAttempts(): Record<string, number> {\n try {\n const parsed: unknown = JSON.parse(storage().getItem(attemptsKey) ?? \"{}\");\n return parsed && typeof parsed === \"object\"\n ? (parsed as Record<string, number>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction writeAttempts(attempts: Record<string, number>): void {\n try {\n storage().setItem(attemptsKey, JSON.stringify(attempts));\n } catch {\n /* unwritable storage — the cap degrades to per-session, never to a throw */\n }\n}\n\n/** Counts this load's attempt and reports whether it is still within the cap. */\nfunction spendAttempt(token: string): boolean {\n const attempts = readAttempts();\n const spent = attempts[token] ?? 0;\n if (spent >= MAX_AUTO_JOIN_ATTEMPTS) return false;\n attempts[token] = spent + 1;\n writeAttempts(attempts);\n return true;\n}\n\n/** Drops the ledger entry so an acked token cannot leak into it forever. */\nfunction forgetAttempts(token: string): void {\n const attempts = readAttempts();\n if (!(token in attempts)) return;\n delete attempts[token];\n writeAttempts(attempts);\n}\n\n/** The token in a raw deep-link payload, or `null` if it carries none. */\nexport function invitationFromRaw(raw: string): string | null {\n const direct = raw.trim();\n if (!direct) return null;\n // A bare token, or a URL/query carrying one.\n try {\n const params = new URLSearchParams(\n direct.includes(\"?\") ? direct.slice(direct.indexOf(\"?\") + 1) : direct,\n );\n const found = params.get(INVITATION_PARAM);\n if (found && found.trim()) return found.trim();\n } catch {\n /* not a query string — fall through to the bare-token reading */\n }\n if (direct.includes(\"=\") || direct.includes(\"?\")) return null;\n if (direct.startsWith(\"/\") || /^[a-z][a-z0-9+.-]*:/i.test(direct)) return null;\n return direct;\n}\n\n/** The current URL with the invitation parameter removed. */\nexport function urlWithoutInvitation(href: string): string {\n try {\n const url = new URL(href);\n if (!url.searchParams.has(INVITATION_PARAM)) return href;\n url.searchParams.delete(INVITATION_PARAM);\n return url.toString();\n } catch {\n return href;\n }\n}\n\nfunction deliver(invitation: CapturedInvitation): void {\n current = invitation;\n notifyWatchers();\n if (listeners.size === 0) {\n buffered = invitation;\n return;\n }\n for (const listener of listeners) listener(invitation);\n}\n\nfunction ensureController(): void {\n if (controller) return;\n controller = new DeepLinkController(new PendingIntentStore(storage()), {\n location: typeof window !== \"undefined\" ? window.location : null,\n bridge: getBridge(),\n launchQueue:\n typeof window !== \"undefined\"\n ? (window as unknown as { launchQueue?: never }).launchQueue ?? null\n : null,\n });\n\n controller.on((intent) => {\n // `join`, or no action at all — the launcher can append `?invitation=…` to\n // this app's own frontend URL, which parses to a null action with the\n // params intact. Anything else is somebody else's intent.\n //\n // An app page opened with an invitation on it (`/teams/t?invitation=…`)\n // parses as slug `teams`, action `t`: not a deep link at all, but still the\n // app's own URL carrying an invitation, so the parameter decides, not the path.\n if (\n intent.action !== null &&\n intent.action !== JOIN_ACTION &&\n !intent.params[INVITATION_PARAM]\n ) {\n return;\n }\n\n // A join addressed to another app. The launcher routes by slug, so this\n // takes a misrouted event or a link for app A opened inside app B — and\n // joining it would put this app's node into a namespace of an app it\n // cannot run. Acked so it does not replay; never offered.\n if (\n intent.action === JOIN_ACTION &&\n intent.slug !== null &&\n ownSlugs.size > 0 &&\n !ownSlugs.has(intent.slug)\n ) {\n intent.resolve();\n return;\n }\n\n const token = invitationFromRaw(intent.raw);\n if (!token) {\n // Nothing for us in it, but it is still ours to ack or it replays forever.\n intent.resolve();\n return;\n }\n\n // Hygiene, not bookkeeping — the store already remembers this. Done AFTER\n // capture, or the parameter would be gone before the controller read it.\n try {\n const cleaned = urlWithoutInvitation(window.location.href);\n if (cleaned !== window.location.href) {\n window.history.replaceState(null, \"\", cleaned);\n }\n } catch {\n /* no history API (or a non-browser test env) — the intent still stands */\n }\n\n deliver({\n token,\n params: { ...intent.params, [INVITATION_PARAM]: token },\n resolve: () => {\n forgetAttempts(token);\n // Acked before any listener took it (declined on the logged-out\n // invitation screen): it must not be replayed to the redemption\n // hook that subscribes once the person logs in.\n if (buffered?.token === token) buffered = null;\n intent.resolve();\n if (current?.token === token) {\n current = null;\n notifyWatchers();\n }\n },\n autoJoin: spendAttempt(token),\n });\n });\n}\n\n/**\n * Start listening for inbound invitation links.\n *\n * Call once before React mounts: the launcher appends `?invitation=…` to the\n * app's own URL, and a router would otherwise replace the URL before any\n * component could read it.\n *\n * `appKey` namespaces the attempt ledger. Two apps served from one origin (the\n * dev server, a preview deployment) would otherwise share it.\n *\n * `slug` is this app's deep-link slug (its package id). Given it, a `join` link\n * addressed to a different app is dropped instead of being offered here.\n */\nexport function primeInvitationCapture(\n appKey?: string,\n options: { slug?: string | readonly string[] } = {},\n): void {\n if (appKey) attemptsKey = `${appKey}:invitation-attempts`;\n const { slug } = options;\n if (slug) ownSlugs = new Set(typeof slug === \"string\" ? [slug] : slug);\n ensureController();\n}\n\n/**\n * Subscribe to invitations. Replays one already captured, so a component that\n * mounts after the link was opened still sees it.\n */\nexport function onInvitation(listener: Listener): () => void {\n ensureController();\n listeners.add(listener);\n if (buffered) {\n const pending = buffered;\n buffered = null;\n listener(pending);\n }\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The captured invitation right now, without subscribing.\n *\n * Unlike `onInvitation`, this does not consume it and does not register a\n * listener — it answers \"is an invitation inbound?\" for code that only needs\n * to know, such as a bootstrap deciding where to land the user.\n */\nexport function peekInvitation(): CapturedInvitation | null {\n ensureController();\n return current;\n}\n\n/**\n * Be told when the captured invitation changes: one arrives, or it is acked.\n *\n * Unlike `onInvitation` this takes nothing: the invitation stays buffered for\n * whoever redeems it. It is for UI that only needs to know one is pending — the\n * logged-out invitation screen — and pairs with `peekInvitation` as a\n * `useSyncExternalStore` source.\n */\nexport function subscribeInvitation(watcher: () => void): () => void {\n ensureController();\n watchers.add(watcher);\n return () => {\n watchers.delete(watcher);\n };\n}\n\n/** Test seam: drop the controller and any buffered intent. */\nexport function resetInvitationCaptureForTests(): void {\n controller?.dispose();\n controller = null;\n listeners.clear();\n buffered = null;\n current = null;\n attemptsKey = \"calimero:invitation-attempts\";\n ownSlugs = new Set();\n // Watchers outlive a reset (a mounted component keeps its subscription);\n // they hear that the answer changed.\n notifyWatchers();\n}\n","import type { InviteFailureReason } from '@calimero-network/mero-js';\n\n/**\n * What to tell a person about a failed join, or `null` to show the node's own\n * message (an `unknown` failure has nothing better to offer).\n *\n * `noun` is what the app calls the thing being joined: \"team\", \"space\", \"vault\".\n * The reason is mero-js's (`redeemInvitation`), read off the node's status.\n */\nexport function describeInviteFailure(\n reason: InviteFailureReason,\n noun = 'team',\n): string | null {\n switch (reason) {\n case 'expired':\n return 'This invitation has expired. Ask for a new link.';\n case 'invalid':\n return \"This invitation link isn't valid. Ask for a new one.\";\n case 'refused':\n return `You can't join this ${noun} with this invitation. Ask an admin to invite you again.`;\n case 'signed-out':\n return 'Your session with your node has ended. Sign in again to finish joining.';\n case 'no-one-online':\n return `No one in this ${noun} is online to let you in yet. It will try again the next time you open the app.`;\n case 'node-unreachable':\n return \"Couldn't reach your node. Check that it is running, then try again.\";\n case 'unknown':\n return null;\n }\n}\n","/**\n * The set of namespaces this browser session has just joined and is still\n * waiting on.\n *\n * `sessionStorage`, not `localStorage`: the flag exists to cover the window\n * between a join returning and that namespace's state arriving. Surviving a\n * browser restart would mean gating a workspace that settled days ago.\n *\n * One key, shared by every app on the origin, and deliberately so. The value is\n * a namespace id — globally unique — so \"you just joined namespace X\" is true\n * for any app that can see X, not just the one that accepted the invite. The\n * watchdog in `useJoinSync` bounds how long a stale entry can matter, so an app\n * that sets the flag and navigates away cannot strand another one.\n */\nconst KEY = \"calimero:justJoinedNamespaces\";\n\n/** Reading storage can throw outright — Safari private mode, blocked site data. */\nfunction read(): Set<string> {\n try {\n if (typeof sessionStorage === \"undefined\") return new Set();\n const raw = sessionStorage.getItem(KEY);\n if (!raw) return new Set();\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed)\n ? new Set(parsed.filter((v): v is string => typeof v === \"string\"))\n : new Set();\n } catch {\n return new Set();\n }\n}\n\n/** In-page listeners: the invitation dialog waits on a namespace's flag clearing. */\nconst listeners = new Set<() => void>();\n\nfunction notify(): void {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // One listener's failure must not keep the others from hearing it.\n }\n }\n}\n\n/**\n * Hear every mark and clear in this page. The flag is set by redemption (at\n * the app root) and cleared by whichever page reads the namespace's data\n * (`useJoinSync`), so this is how the one learns about the other without the\n * app threading page state up to its root.\n */\nexport function subscribeJustJoined(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\nfunction write(set: Set<string>): void {\n try {\n if (typeof sessionStorage === \"undefined\") return;\n sessionStorage.setItem(KEY, JSON.stringify([...set]));\n } catch {\n // Storage is a convenience here. A session that cannot persist the flag\n // simply does not get the gate; it must never break the join itself.\n }\n}\n\n/**\n * Call this the moment a join succeeds, before navigating. The app that reads\n * the flag is usually a different route from the one that accepted the invite.\n */\nexport function markNamespaceJustJoined(namespaceId: string): void {\n if (!namespaceId) return;\n const set = read();\n if (set.has(namespaceId)) return;\n set.add(namespaceId);\n write(set);\n notify();\n}\n\nexport function clearNamespaceJustJoined(namespaceId: string): void {\n const set = read();\n if (!set.delete(namespaceId)) return;\n write(set);\n notify();\n}\n\nexport function isNamespaceJustJoined(namespaceId: string | null): boolean {\n if (!namespaceId) return false;\n return read().has(namespaceId);\n}\n\n/** Test seam. Not part of the app-facing API. */\nexport function __readJustJoinedSet(): Set<string> {\n return read();\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { markNamespaceJustJoined } from \"./justJoined\";\n\nimport { onInvitation, type CapturedInvitation } from \"./capture\";\nimport {\n redeemInvitation,\n shouldRetain,\n type InviteFailureReason,\n type InviteRedeemer,\n type RedeemOutcome,\n} from \"@calimero-network/mero-js\";\n\n/** What the token carries, once the app's codec has read it. */\nexport interface ParsedInvitation {\n namespaceId: string;\n /** The invitation struct the node's join body expects. */\n invitation: unknown;\n /** The human name the inviter embedded, if any. */\n teamName?: string;\n}\n\n/**\n * Where redemption has got to, for rendering.\n *\n * `joining` is the state the apps used to lack: following an invite\n * link put the app on a page with no sign anything was happening, for as long\n * as the join took — up to 95s when no member of the namespace was online.\n */\nexport type InviteState =\n | { stage: \"idle\" }\n | { stage: \"awaiting-confirmation\"; teamName?: string }\n | { stage: \"joining\"; teamName?: string }\n | { stage: \"joined\"; namespaceId: string; teamName?: string }\n | { stage: \"already-member\"; namespaceId: string; teamName?: string }\n | {\n stage: \"failed\";\n /** The node's own words, or this package's for an unreadable link. */\n message: string;\n /** Why; `describeInviteFailure` turns it into something to show. */\n reason: InviteFailureReason;\n retryable: boolean;\n };\n\nexport interface UseInviteRedemptionOptions<P extends ParsedInvitation = ParsedInvitation> {\n /**\n * Read a raw token into its parts. Return `null` (or throw) if it is not a\n * usable invitation — the app owns this because the codecs differ slightly.\n * Extra fields the app returns (a vault name, a context id) come back as\n * `parsed` and are handed to `redeem`.\n */\n parse: (token: string, params: Record<string, string>) => P | null;\n /**\n * The two calls that differ between apps, for the standard join: join the\n * namespace, then check membership (mero-js `redeemInvitation`).\n */\n redeemer?: InviteRedeemer;\n /**\n * An app's own join flow, for one that does more than join the namespace\n * (enter a context, pick where to land). Takes precedence over `redeemer`.\n * Report a failure as a `failed` outcome rather than throwing; a throw is\n * read as an `unknown`, retryable failure.\n */\n redeem?: (parsed: P) => Promise<RedeemOutcome>;\n /**\n * Ask before joining, rather than joining on arrival.\n *\n * Not a stylistic choice, and deliberately per-app. Joining is a state\n * change: it puts you in someone else's namespace and gives them a peer that\n * syncs their data. For an app holding secrets — mero-pass is the clear case\n * — doing that on page load means a forwarded link, or a background tab that\n * refreshes, joins silently. Decoding is pure and local, so the scope can be\n * shown first and the join can need a click.\n *\n * With this set the state goes `awaiting-confirmation` and waits for\n * `accept()`; `decline()` acks the invitation so it stops coming back.\n *\n * On by default: an invitation reaches an app only by a link being opened,\n * and every app asks before it joins. Off only for a caller that has already\n * asked in its own words.\n */\n confirm?: boolean;\n /**\n * Called once, after a join has landed and before anything navigates. The\n * `already-member` case calls it too: the app still has to go and look at a\n * namespace it may never have opened.\n */\n onJoined?: (namespaceId: string, teamName?: string) => void;\n /**\n * Hold off until the app can actually join — a session, a resolved\n * application id. The invitation is buffered meanwhile, not dropped.\n */\n enabled?: boolean;\n}\n\nexport interface InviteRedemption<P extends ParsedInvitation = ParsedInvitation> {\n state: InviteState;\n /** The captured token, for prefilling a manual join field. */\n token: string | null;\n /** What the invitation names, available while confirming. */\n parsed: P | null;\n /** Go ahead with a join that is `awaiting-confirmation`. */\n accept: () => void;\n /** Decline it, and ack it so it does not come back. */\n decline: () => void;\n /** Retry the captured invitation by hand, past the automatic attempt cap. */\n retry: () => void;\n /** Take the result off the screen. */\n dismiss: () => void;\n}\n\n/**\n * Redeem an invitation that arrived by link, and report progress.\n *\n * Mount this once, high enough that it is not unmounted by routing. Capture is\n * process-wide and buffers, so mounting late is safe; being unmounted mid-join\n * only loses the on-screen state, never the invitation (it is acked on the\n * outcome, not on the render).\n */\nexport function useInviteRedemption<P extends ParsedInvitation = ParsedInvitation>({\n parse,\n redeemer,\n redeem,\n confirm = true,\n onJoined,\n enabled = true,\n}: UseInviteRedemptionOptions<P>): InviteRedemption<P> {\n const [state, setState] = useState<InviteState>({ stage: \"idle\" });\n const [token, setToken] = useState<string | null>(null);\n const [parsed, setParsed] = useState<P | null>(null);\n\n // Read through refs so a re-created `parse`/`redeemer`/`onJoined` — which is\n // every render, in most apps — does not resubscribe and re-fire the join.\n const parseRef = useRef(parse);\n parseRef.current = parse;\n const redeemerRef = useRef(redeemer);\n redeemerRef.current = redeemer;\n const redeemRef = useRef(redeem);\n redeemRef.current = redeem;\n const onJoinedRef = useRef(onJoined);\n onJoinedRef.current = onJoined;\n const confirmRef = useRef(confirm);\n confirmRef.current = confirm;\n\n /** Tokens already attempted this session, so nothing loops within one load. */\n const attempted = useRef<Set<string>>(new Set());\n /** The pending ack for the captured invitation, held for confirm/retry. */\n const pending = useRef<CapturedInvitation | null>(null);\n const parsedRef = useRef<P | null>(null);\n const alive = useRef(true);\n useEffect(() => {\n alive.current = true;\n return () => {\n alive.current = false;\n };\n }, []);\n\n /** Do the join and report the outcome. */\n const perform = useCallback(\n async (captured: CapturedInvitation, invitation: P) => {\n if (alive.current)\n setState({ stage: \"joining\", teamName: invitation.teamName });\n\n const outcome = await runRedeem(\n invitation,\n redeemRef.current,\n redeemerRef.current,\n );\n\n if (!shouldRetain(outcome)) captured.resolve();\n\n if (outcome.status === \"joined\" || outcome.status === \"already-member\") {\n // Before any navigation, so the gate is already set wherever the app\n // sends the user next.\n markNamespaceJustJoined(outcome.namespaceId);\n onJoinedRef.current?.(outcome.namespaceId, outcome.teamName);\n }\n\n if (!alive.current) return;\n setState(\n outcome.status === \"failed\"\n ? {\n stage: \"failed\",\n message: outcome.message,\n reason: outcome.reason,\n retryable: outcome.retryable,\n }\n : {\n stage: outcome.status,\n namespaceId: outcome.namespaceId,\n teamName: outcome.teamName,\n },\n );\n },\n [],\n );\n\n /** Parse, then either ask or go. */\n const begin = useCallback(\n (captured: CapturedInvitation) => {\n let invitation: P | null = null;\n try {\n invitation = parseRef.current(captured.token, captured.params);\n } catch {\n invitation = null;\n }\n if (!invitation?.namespaceId) {\n // Unreadable: retrying cannot help, so ack it rather than leave it to\n // replay forever.\n captured.resolve();\n if (alive.current) {\n setState({\n stage: \"failed\",\n message: \"That invitation could not be read.\",\n reason: \"invalid\",\n retryable: false,\n });\n }\n return;\n }\n\n parsedRef.current = invitation;\n if (alive.current) setParsed(invitation);\n\n if (confirmRef.current) {\n if (alive.current) {\n setState({\n stage: \"awaiting-confirmation\",\n teamName: invitation.teamName,\n });\n }\n return;\n }\n void perform(captured, invitation);\n },\n [perform],\n );\n\n useEffect(() => {\n if (!enabled) return;\n return onInvitation((captured) => {\n pending.current = captured;\n setToken(captured.token);\n if (attempted.current.has(captured.token)) return;\n // The attempt cap stops a link that cannot join from re-firing a join on\n // every load. Asking is not joining: a prompt is still owed, because a\n // link is the only way an invitation reaches the app.\n if (!captured.autoJoin && !confirmRef.current) return;\n attempted.current.add(captured.token);\n begin(captured);\n });\n }, [enabled, begin]);\n\n const accept = useCallback(() => {\n const captured = pending.current;\n const invitation = parsedRef.current;\n if (!captured || !invitation) return;\n void perform(captured, invitation);\n }, [perform]);\n\n const decline = useCallback(() => {\n // \"Not now\" IS handled. Without the ack the same prompt returns on every\n // load, which reads as the app nagging rather than as durability.\n pending.current?.resolve();\n setState({ stage: \"idle\" });\n }, []);\n\n const retry = useCallback(() => {\n const captured = pending.current;\n if (!captured) return;\n attempted.current.add(captured.token);\n // The person already said yes to this invitation: \"Try again\" joins, it\n // does not ask a second time. Only an invitation never read is begun anew.\n const invitation = parsedRef.current;\n if (invitation) void perform(captured, invitation);\n else begin(captured);\n }, [begin, perform]);\n\n const dismiss = useCallback(() => setState({ stage: \"idle\" }), []);\n\n return { state, token, parsed, accept, decline, retry, dismiss };\n}\n\n/** The app's own flow, or the standard join; a throw is an unknown failure. */\nasync function runRedeem<P extends ParsedInvitation>(\n invitation: P,\n redeem: ((parsed: P) => Promise<RedeemOutcome>) | undefined,\n redeemer: InviteRedeemer | undefined,\n): Promise<RedeemOutcome> {\n try {\n if (redeem) return await redeem(invitation);\n if (redeemer) return await redeemInvitation(invitation, redeemer);\n return {\n status: \"failed\",\n namespaceId: invitation.namespaceId,\n message: \"This app cannot redeem invitations: no redeemer is configured.\",\n reason: \"unknown\",\n retryable: false,\n };\n } catch (err) {\n return {\n status: \"failed\",\n namespaceId: invitation.namespaceId,\n message: err instanceof Error ? err.message : String(err),\n reason: \"unknown\",\n retryable: true,\n };\n }\n}\n","import { useEffect, useReducer, useRef } from \"react\";\nimport {\n clearNamespaceJustJoined,\n isNamespaceJustJoined,\n subscribeJustJoined,\n} from \"./justJoined\";\n\n/**\n * Base window for the gate. A governance op plus the namespace's own state\n * typically land in under a second on a healthy mesh; past this we give up\n * ONLY if nothing is actively in flight.\n */\nexport const JOIN_SYNC_WATCHDOG_MS = 30_000;\n/**\n * Hard ceiling. Bounds a genuinely stuck sync so the gate can never pin the UI\n * forever, even while something keeps reporting activity.\n */\nexport const JOIN_SYNC_MAX_MS = 120_000;\n/** How often the watchdog re-checks activity past the base window. */\nexport const JOIN_SYNC_POLL_MS = 2_000;\n\nexport interface JoinSyncOptions {\n /** The namespace being shown. `null` while nothing is selected. */\n namespaceId: string | null;\n /**\n * The app's own answer to \"has this namespace's data actually arrived?\" —\n * the one thing that cannot be shared, because every app reads a different\n * collection. Pass `true` once a real read has come back, INCLUDING an empty\n * one: \"no documents yet\" is a settled answer, and waiting for a non-empty\n * result would gate an genuinely empty workspace forever.\n */\n settled: boolean;\n /**\n * Optional: a sync is making forward progress. Holds the gate open past the\n * base window, up to the hard ceiling. Leave undefined if the app has no\n * such signal — the gate then simply expires at the base window.\n *\n * A stuck or backing-off sync must report `false`, not `true`: the point of\n * the base window is to stop waiting on something that is not coming.\n */\n active?: boolean;\n}\n\nexport interface JoinSyncState {\n /**\n * Show the \"syncing from peers\" affordance. True only for a namespace this\n * session just joined, whose data has not arrived, within the watchdog.\n */\n isSyncing: boolean;\n /** Drop the gate now — for a \"show me anyway\" control. */\n dismiss: () => void;\n}\n\n/**\n * Gate the window between \"you joined\" and \"your data is here\".\n *\n * Without it a just-joined namespace renders its ordinary empty state, and the\n * user cannot tell an empty workspace from one that is still arriving. That\n * ambiguity is the whole reason this exists: the two look identical, and the\n * honest one is the less alarming of the two.\n */\nexport function useJoinSync({\n namespaceId,\n settled,\n active,\n}: JoinSyncOptions): JoinSyncState {\n // The flag, read on every render, with a render on every mark or clear in the\n // page: a join can mark the namespace this page already shows (an invitation\n // to a workspace this node joined before), and a read keyed only on\n // `namespaceId` would never see that mark. Every change, not just a flip of\n // this namespace's flag: a clear and a re-mark in one batch leave the flag\n // where it was, and the clear below still has to run again.\n const [, storeChanged] = useReducer((n: number) => n + 1, 0);\n useEffect(() => {\n const unsubscribe = subscribeJustJoined(storeChanged);\n // A change between the first render and this subscription.\n storeChanged();\n return unsubscribe;\n }, []);\n const flagged = isNamespaceJustJoined(namespaceId);\n // When this namespace was first seen flagged, for the watchdog. Dropped once\n // the flag clears, so a later join of the same namespace gets a full window.\n const firstSeen = useRef<Map<string, number>>(new Map());\n if (namespaceId && flagged && !firstSeen.current.has(namespaceId)) {\n firstSeen.current.set(namespaceId, Date.now());\n } else if (namespaceId && !flagged) {\n firstSeen.current.delete(namespaceId);\n }\n // Read from a ref inside the watchdog so a change in activity does not\n // restart the timer — which would let a chatty sync postpone the deadline\n // indefinitely.\n const activeRef = useRef(active);\n activeRef.current = active;\n\n // Settled is the happy path: the data arrived, so stop gating and forget the\n // namespace. Runs before the watchdog ever fires in the normal case.\n //\n // After every render, reading the store itself: a mark that lands in the\n // same batch as this clear (an app's own mark, then the redemption's) leaves\n // `flagged` true throughout, so an effect keyed on it would not run again and\n // the flag would stay set. The clear notifies, which renders again, so this\n // stops once the flag is gone.\n useEffect(() => {\n if (!namespaceId || !settled || !isNamespaceJustJoined(namespaceId)) return;\n clearNamespaceJustJoined(namespaceId);\n });\n\n useEffect(() => {\n if (!namespaceId || !flagged || settled) return;\n const since = firstSeen.current.get(namespaceId) ?? Date.now();\n let timer: ReturnType<typeof setTimeout>;\n const check = () => {\n const elapsed = Date.now() - since;\n const giveUp =\n elapsed >= JOIN_SYNC_MAX_MS ||\n (elapsed >= JOIN_SYNC_WATCHDOG_MS && !activeRef.current);\n if (giveUp) {\n clearNamespaceJustJoined(namespaceId);\n return;\n }\n timer = setTimeout(check, JOIN_SYNC_POLL_MS);\n };\n timer = setTimeout(check, JOIN_SYNC_WATCHDOG_MS);\n return () => clearTimeout(timer);\n }, [namespaceId, flagged, settled]);\n\n return {\n isSyncing: flagged && !settled,\n dismiss: () => {\n if (!namespaceId) return;\n clearNamespaceJustJoined(namespaceId);\n },\n };\n}\n","/**\n * The one invitation prompt: ask, join, wait for the data, done.\n *\n * Mount it once at the app root with the app's `useInviteRedemption()`. It\n * renders nothing until an invitation link has been opened, then walks the\n * person through every stage in one place:\n *\n * awaiting-confirmation \"Join “Design team”?\" Join / Not now\n * joining \"Joining “Design team”…\" (cannot be closed)\n * syncing \"Syncing “Design team”…\" Continue in background\n * ready \"You're in “Design team”\" closes by itself\n * already-member \"You're already in …\" Done\n * failed the reason, in plain words Try again / Close\n *\n * `syncing` is the stage the apps used to skip: a join returns before the\n * namespace's data has arrived, and an empty page then looks exactly like an\n * empty workspace. It lasts while the namespace's just-joined flag is set\n * (`markNamespaceJustJoined`, set by redemption) and ends when the page that\n * reads the data clears it (`useJoinSync` with `settled`), when the app says so\n * here (`synced`), or at the watchdog's hard ceiling. So the app root needs no\n * page state threaded up to it: the page that knows says so through the flag.\n *\n * Test ids are the contract the apps' two-node journeys drive: `invite-prompt`\n * (with `data-stage`), `invite-accept`, `invite-decline`, `invite-retry`,\n * `invite-continue`, `invite-error`.\n */\nimport {\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n useSyncExternalStore,\n type KeyboardEvent as ReactKeyboardEvent,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { describeInviteFailure } from './describeInviteFailure';\nimport {\n clearNamespaceJustJoined,\n isNamespaceJustJoined,\n subscribeJustJoined,\n} from './justJoined';\nimport type { InviteRedemption } from './useInviteRedemption';\nimport { JOIN_SYNC_MAX_MS, JOIN_SYNC_WATCHDOG_MS } from './useJoinSync';\n\n/** How long \"You're in\" stays up before the dialog closes by itself. */\nexport const INVITATION_READY_MS = 1_200;\n\nexport interface InvitationDialogProps {\n /** The app's `useInviteRedemption(...)`. */\n redemption: InviteRedemption;\n /** What the app calls the thing being joined: \"team\", \"workspace\", \"vault\". */\n noun?: string;\n /** Shown above the title, so a person knows which app is asking. */\n appName?: string;\n /**\n * Optional: the joined namespace's data has been read, empty or not. For an\n * app whose root already knows; others leave this out and let the page that\n * reads the data clear the flag with `useJoinSync({ settled })`.\n */\n synced?: boolean;\n /**\n * Optional: the app's own words under the question, for an invitation whose\n * grant needs spelling out (\"Joining gives you this vault and the rest of\n * the team it belongs to.\").\n */\n detail?: string;\n /** Optional: which step a slow join is on, shown while joining. */\n status?: string | null;\n}\n\n/** The stage the dialog shows: redemption's, plus the wait for the data. */\nexport type InvitationDialogStage =\n | 'awaiting-confirmation'\n | 'joining'\n | 'syncing'\n | 'ready'\n | 'already-member'\n | 'failed';\n\nfunction useJustJoined(namespaceId: string | null): boolean {\n return useSyncExternalStore(\n subscribeJustJoined,\n () => isNamespaceJustJoined(namespaceId),\n () => false,\n );\n}\n\nexport function InvitationDialog({\n redemption,\n noun = 'team',\n appName,\n synced,\n detail,\n status,\n}: InvitationDialogProps) {\n const { state, accept, decline, retry, dismiss } = redemption;\n const joinedId = state.stage === 'joined' ? state.namespaceId : null;\n const stillSyncing = useJustJoined(joinedId);\n\n // The app's own word that the data is here ends the wait just as the page's\n // `useJoinSync` would.\n useEffect(() => {\n if (joinedId && stillSyncing && synced) clearNamespaceJustJoined(joinedId);\n }, [joinedId, stillSyncing, synced]);\n\n // A sync that never settles must not pin the dialog: past the watchdog it\n // says so, and at the hard ceiling it lets go (the flag too, so the page's\n // own banner does not outlive it).\n const [slow, setSlow] = useState(false);\n useEffect(() => {\n setSlow(false);\n if (!joinedId || !stillSyncing) return;\n const slowTimer = setTimeout(() => setSlow(true), JOIN_SYNC_WATCHDOG_MS);\n const ceiling = setTimeout(\n () => clearNamespaceJustJoined(joinedId),\n JOIN_SYNC_MAX_MS,\n );\n return () => {\n clearTimeout(slowTimer);\n clearTimeout(ceiling);\n };\n }, [joinedId, stillSyncing]);\n\n const stage: InvitationDialogStage | null =\n state.stage === 'idle'\n ? null\n : state.stage === 'joined'\n ? stillSyncing\n ? 'syncing'\n : 'ready'\n : state.stage;\n\n // \"You're in\" closes by itself; everything else waits for the person.\n useEffect(() => {\n if (stage !== 'ready') return;\n const t = setTimeout(dismiss, INVITATION_READY_MS);\n return () => clearTimeout(t);\n }, [stage, dismiss]);\n\n const titleId = useId();\n const bodyId = useId();\n const dialogRef = useRef<HTMLDivElement>(null);\n const primaryRef = useRef<HTMLButtonElement>(null);\n\n // Focus follows the stage, so a keyboard user lands on what to do next.\n useEffect(() => {\n if (!stage) return;\n (primaryRef.current ?? dialogRef.current)?.focus();\n }, [stage]);\n\n /** Closing means what the stage says it means; mid-join it means nothing. */\n const close = useCallback(() => {\n if (stage === 'awaiting-confirmation') decline();\n else if (stage && stage !== 'joining') dismiss();\n }, [stage, decline, dismiss]);\n\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.key === 'Escape') {\n event.stopPropagation();\n close();\n return;\n }\n if (event.key !== 'Tab' || !dialogRef.current) return;\n // Keep focus inside while the dialog is up.\n const focusable = dialogRef.current.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), [href], [tabindex]:not([tabindex=\"-1\"])',\n );\n if (focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n if (!stage || typeof document === 'undefined') return null;\n\n const teamName = 'teamName' in state ? state.teamName : undefined;\n const named = teamName ? `“${teamName}”` : `this ${noun}`;\n const busy = stage === 'joining' || stage === 'syncing';\n\n let icon: 'spinner' | 'invite' | 'done' | 'error' = 'invite';\n let title = '';\n let body: string | null = null;\n if (stage === 'awaiting-confirmation') {\n title = teamName ? `Join “${teamName}”?` : `Join this ${noun}?`;\n body =\n detail ??\n `You have been invited. Joining makes this device a member, and the ${noun}'s data syncs to it from the other members.`;\n } else if (stage === 'joining') {\n icon = 'spinner';\n title = `Joining ${named}…`;\n body =\n status ||\n 'Asking a member to let you in. With few members online this can take up to a minute.';\n } else if (stage === 'syncing') {\n icon = 'spinner';\n title = `Syncing ${named}…`;\n body = slow\n ? `Still waiting on the other members. You can carry on; the ${noun} fills in as its data arrives.`\n : `You're in. Getting the ${noun}'s data from the other members.`;\n } else if (stage === 'ready') {\n icon = 'done';\n title = `You're in ${named}`;\n } else if (stage === 'already-member') {\n icon = 'done';\n title = `You're already in ${named}`;\n } else {\n icon = 'error';\n title = \"Couldn't join\";\n body =\n state.stage === 'failed'\n ? (describeInviteFailure(state.reason, noun) ?? state.message)\n : null;\n }\n\n const retryable = state.stage === 'failed' && state.retryable;\n\n return createPortal(\n <div\n className=\"mero-invite-overlay\"\n onMouseDown={(event) => {\n if (event.target === event.currentTarget) close();\n }}\n >\n <div\n ref={dialogRef}\n className=\"mero-invite-dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={titleId}\n aria-describedby={body ? bodyId : undefined}\n aria-busy={busy}\n tabIndex={-1}\n data-testid=\"invite-prompt\"\n data-stage={stage}\n onKeyDown={onKeyDown}\n >\n {appName ? <p className=\"mero-invite-app\">{appName}</p> : null}\n <div className=\"mero-invite-head\">\n <InviteIcon kind={icon} />\n <h2 id={titleId} className=\"mero-invite-title\">\n {title}\n </h2>\n </div>\n {body ? (\n <p\n id={bodyId}\n className={\n stage === 'failed'\n ? 'mero-invite-body mero-invite-body-error'\n : 'mero-invite-body'\n }\n role={stage === 'failed' ? 'alert' : undefined}\n data-testid={stage === 'failed' ? 'invite-error' : undefined}\n >\n {body}\n </p>\n ) : null}\n {stage === 'syncing' || stage === 'joining' ? (\n <div className=\"mero-invite-progress\" aria-hidden=\"true\">\n <span className=\"mero-invite-progress-bar\" />\n </div>\n ) : null}\n\n <div className=\"mero-invite-actions\">\n {stage === 'awaiting-confirmation' ? (\n <>\n <button\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={decline}\n data-testid=\"invite-decline\"\n >\n Not now\n </button>\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={accept}\n data-testid=\"invite-accept\"\n >\n Join\n </button>\n </>\n ) : null}\n {stage === 'syncing' ? (\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={dismiss}\n data-testid=\"invite-continue\"\n >\n Continue in background\n </button>\n ) : null}\n {stage === 'ready' || stage === 'already-member' ? (\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={dismiss}\n data-testid=\"invite-done\"\n >\n Done\n </button>\n ) : null}\n {stage === 'failed' ? (\n <>\n <button\n ref={retryable ? undefined : primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={dismiss}\n data-testid=\"invite-decline\"\n >\n Close\n </button>\n {retryable ? (\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={retry}\n data-testid=\"invite-retry\"\n >\n Try again\n </button>\n ) : null}\n </>\n ) : null}\n </div>\n </div>\n </div>,\n document.body,\n );\n}\n\nfunction InviteIcon({ kind }: { kind: 'spinner' | 'invite' | 'done' | 'error' }) {\n if (kind === 'spinner') {\n return <span className=\"mero-invite-icon mero-invite-spinner\" aria-hidden=\"true\" />;\n }\n const path =\n kind === 'done'\n ? 'M5 12.5l4.5 4.5L19 7.5'\n : kind === 'error'\n ? 'M12 7v6m0 4h.01'\n : 'M4 7l8 6 8-6M5 6h14a1 1 0 011 1v10a1 1 0 01-1 1H5a1 1 0 01-1-1V7a1 1 0 011-1z';\n return (\n <span className={`mero-invite-icon mero-invite-icon-${kind}`} aria-hidden=\"true\">\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d={path} />\n </svg>\n </span>\n );\n}\n","import type { CSSProperties, ReactNode } from \"react\";\n\nexport interface JoinSyncBannerProps {\n /** Usually `useJoinSync(...).isSyncing`. Renders nothing when false. */\n show: boolean;\n /** What is arriving, in the app's own words: \"documents\", \"vaults\", \"sheets\". */\n what?: string;\n /** Wire to `useJoinSync(...).dismiss` for a \"show me anyway\" escape. */\n onDismiss?: () => void;\n /** Escape hatches for apps with their own design system. */\n className?: string;\n style?: CSSProperties;\n children?: ReactNode;\n}\n\n/**\n * Deliberately inline-styled rather than using a stylesheet or utility classes.\n *\n * The apps in this monorepo do not share a CSS stack — Tailwind, CSS modules\n * and plain stylesheets are all represented — so anything class-based would\n * render unstyled in most of them. Inline styles are the only thing that looks\n * the same everywhere, and `className`/`style` are there for apps that want to\n * take it over. Colours come from CSS custom properties with literal\n * fallbacks, so an app that defines them gets its own palette for free and one\n * that does not still gets something legible in both themes.\n */\nexport function JoinSyncBanner({\n show,\n what = \"data\",\n onDismiss,\n className,\n style,\n children,\n}: JoinSyncBannerProps) {\n if (!show) return null;\n\n return (\n <div\n role=\"status\"\n aria-live=\"polite\"\n className={className}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"0.625rem\",\n padding: \"0.625rem 0.875rem\",\n borderRadius: \"0.5rem\",\n border: \"1px solid var(--join-sync-border, rgba(127,127,127,0.28))\",\n background: \"var(--join-sync-bg, rgba(127,127,127,0.08))\",\n color: \"var(--join-sync-fg, inherit)\",\n font: \"inherit\",\n fontSize: \"0.875rem\",\n lineHeight: 1.4,\n ...style,\n }}\n >\n <Spinner />\n <span style={{ flex: 1 }}>\n {children ?? (\n <>\n Joined. Syncing {what} from peers&hellip;{\" \"}\n <span style={{ opacity: 0.75 }}>\n This can take a moment on a cold connection.\n </span>\n </>\n )}\n </span>\n {onDismiss && (\n <button\n type=\"button\"\n onClick={onDismiss}\n style={{\n font: \"inherit\",\n fontSize: \"0.8125rem\",\n background: \"none\",\n border: \"none\",\n padding: 0,\n color: \"inherit\",\n opacity: 0.75,\n textDecoration: \"underline\",\n cursor: \"pointer\",\n }}\n >\n Show anyway\n </button>\n )}\n </div>\n );\n}\n\n/**\n * An inline SVG rather than a CSS-class spinner, for the same reason as above —\n * and `<animateTransform>` rather than a keyframe, because injecting a\n * `@keyframes` rule from a shared component would collide across apps.\n */\nfunction Spinner() {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 16 16\"\n aria-hidden=\"true\"\n style={{ flexShrink: 0, opacity: 0.85 }}\n >\n <circle\n cx=\"8\"\n cy=\"8\"\n r=\"6.5\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeOpacity=\"0.25\"\n strokeWidth=\"2\"\n />\n <path\n d=\"M8 1.5A6.5 6.5 0 0 1 14.5 8\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n >\n <animateTransform\n attributeName=\"transform\"\n type=\"rotate\"\n from=\"0 8 8\"\n to=\"360 8 8\"\n dur=\"0.8s\"\n repeatCount=\"indefinite\"\n />\n </path>\n </svg>\n );\n}\n","/**\n * The page an invite link lands on when you are not logged in.\n *\n * Before this, a logged-out person who opened an invite link saw the app's\n * ordinary logged-out page, usually its marketing landing, with nothing saying\n * they had been invited: the invitation sat captured in storage, and the\n * `InvitationDialog` only appeared once they had worked out on their own that\n * they should log in. This screen is the missing step:\n *\n * session restoring a blank page with a spinner (no landing-page flash)\n * logged out \"You're invited to join “Design team”\"\n * Not now / Log in to join (the app's usual login)\n * unreadable link \"This invitation can't be read\" Continue\n * logged in nothing: `InvitationDialog` asks, joins and syncs\n *\n * It reads the captured invitation without taking it (`subscribeInvitation`,\n * `peekInvitation`), so the app's `useInviteRedemption` still receives it after\n * login. \"Not now\" acks it, exactly as the dialog's does.\n *\n * Two ways to mount it, both inside `MeroProvider` (outside one it shows\n * nothing, since there is no session to ask about):\n *\n * - beside the app's `InvitationDialog`, with no children: the screen covers\n * whatever page is underneath (a full-page layer, opaque). One line in the\n * component that already owns the dialog.\n * - around the app, `<InvitationGate …>{app}</InvitationGate>`: the screen is\n * rendered instead of the children, so the landing page does not mount.\n *\n * Test ids: `invite-landing` (with `data-state`: `checking`, `invited`,\n * `invalid`), `invite-landing-login`, `invite-landing-decline`.\n */\nimport {\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useSyncExternalStore,\n type KeyboardEvent as ReactKeyboardEvent,\n type ReactNode,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { ConnectButton, type ConnectButtonProps } from '../components/ConnectButton';\nimport { MeroContext } from '../context';\nimport { peekInvitation, subscribeInvitation, type CapturedInvitation } from './capture';\nimport type { ParsedInvitation } from './useInviteRedemption';\n\nexport interface InvitationGateProps {\n /**\n * The app, shown as usual unless an invitation is waiting on a login. Leave\n * out to mount the gate beside the app instead, as a full-page layer.\n */\n children?: ReactNode;\n /**\n * The app's invitation codec, the same `parse` it gives `useInviteRedemption`.\n * Decoding needs no session, so the screen can name what is being joined.\n * Without it the screen falls back to the noun.\n */\n parse?: (token: string, params: Record<string, string>) => ParsedInvitation | null;\n /** What the app calls the thing being joined: \"team\", \"workspace\", \"vault\". */\n noun?: string;\n /** The app's name, so a person knows where the invitation is taking them. */\n appName?: string;\n /** Optional: the app's own words about what joining gives you. */\n detail?: string;\n /** Passed to the login button (theme, `cloud`, `connectionType`). */\n connectButtonProps?: Omit<ConnectButtonProps, 'label'>;\n}\n\ntype GateState = 'checking' | 'invited' | 'invalid';\n\n/** The captured invitation, re-rendering when one arrives or is acked. */\nexport function usePendingInvitation(): CapturedInvitation | null {\n return useSyncExternalStore(subscribeInvitation, peekInvitation, () => null);\n}\n\nexport function InvitationGate({\n children,\n parse,\n noun = 'team',\n appName,\n detail,\n connectButtonProps,\n}: InvitationGateProps) {\n // Read directly rather than through `useMero`, which throws: with no\n // provider there is no session to ask about, so the gate stays out of the\n // way (as it does in an app's unit tests that stub `useMero` itself).\n const session = useContext(MeroContext);\n const pending = usePendingInvitation();\n\n // `undefined`: not readable at all. `null`: no codec given, so no name.\n const parsed = useMemo((): ParsedInvitation | null | undefined => {\n if (!pending || !parse) return null;\n try {\n const result = parse(pending.token, pending.params);\n return result?.namespaceId ? result : undefined;\n } catch {\n return undefined;\n }\n }, [pending, parse]);\n\n const state: GateState | null =\n !pending || !session || session.isAuthenticated\n ? null\n : session.isLoading\n ? 'checking'\n : parsed === undefined\n ? 'invalid'\n : 'invited';\n\n if (!state) return children === undefined ? null : <>{children}</>;\n\n const page = (\n <InvitationScreen\n state={state}\n teamName={parsed?.teamName}\n noun={noun}\n appName={appName}\n detail={detail}\n connectButtonProps={connectButtonProps}\n onDecline={() => pending?.resolve()}\n />\n );\n if (children !== undefined || typeof document === 'undefined') return page;\n return createPortal(page, document.body);\n}\n\ninterface InvitationScreenProps {\n state: GateState;\n teamName?: string;\n noun: string;\n appName?: string;\n detail?: string;\n connectButtonProps?: Omit<ConnectButtonProps, 'label'>;\n onDecline: () => void;\n}\n\nfunction InvitationScreen({\n state,\n teamName,\n noun,\n appName,\n detail,\n connectButtonProps,\n onDecline,\n}: InvitationScreenProps) {\n const titleId = useId();\n const bodyId = useId();\n const cardRef = useRef<HTMLDivElement>(null);\n const loginRef = useRef<HTMLDivElement>(null);\n const continueRef = useRef<HTMLButtonElement>(null);\n\n // Focus lands on what to do next: the login, or Continue past a bad link.\n useEffect(() => {\n if (state === 'checking') return;\n const target =\n state === 'invited'\n ? loginRef.current?.querySelector<HTMLElement>('button')\n : continueRef.current;\n (target ?? cardRef.current)?.focus();\n }, [state]);\n\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n // No Escape: on a full page it would decline by accident. Keep Tab inside.\n if (event.key !== 'Tab' || !cardRef.current) return;\n const focusable = cardRef.current.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), [href], [tabindex]:not([tabindex=\"-1\"])',\n );\n if (focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n if (state === 'checking') {\n // Deliberately wordless: a restored session goes straight to the dialog,\n // and a card that says \"invited\" for a blink before it would be noise.\n return (\n <div\n className=\"mero-invite-landing\"\n role=\"status\"\n aria-busy=\"true\"\n aria-label=\"Checking your session\"\n data-testid=\"invite-landing\"\n data-state=\"checking\"\n >\n <span className=\"mero-invite-icon mero-invite-spinner\" aria-hidden=\"true\" />\n </div>\n );\n }\n\n const invalid = state === 'invalid';\n const title = invalid\n ? \"This invitation can't be read\"\n : teamName\n ? `You're invited to join “${teamName}”`\n : `You're invited to join a ${noun}`;\n const where = appName ? ` in ${appName}` : '';\n const body = invalid\n ? 'The link may have been cut short when it was shared. Ask whoever sent it for a new one.'\n : `Someone sent you a link to join this ${noun}${where}. Log in to accept it; you'll be asked to confirm before you join.`;\n\n return (\n <div className=\"mero-invite-landing\">\n <div\n ref={cardRef}\n className=\"mero-invite-dialog mero-invite-landing-card\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={titleId}\n aria-describedby={bodyId}\n tabIndex={-1}\n data-testid=\"invite-landing\"\n data-state={state}\n onKeyDown={onKeyDown}\n >\n {appName ? <p className=\"mero-invite-app\">{appName}</p> : null}\n <div className=\"mero-invite-head\">\n <InviteIcon error={invalid} />\n <h1 id={titleId} className=\"mero-invite-title\">\n {title}\n </h1>\n </div>\n <p id={bodyId} className=\"mero-invite-body\">\n {body}\n </p>\n {detail && !invalid ? <p className=\"mero-invite-body\">{detail}</p> : null}\n\n <div className=\"mero-invite-actions\">\n {invalid ? (\n <button\n ref={continueRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={onDecline}\n data-testid=\"invite-landing-decline\"\n >\n Continue\n </button>\n ) : (\n <>\n <button\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={onDecline}\n data-testid=\"invite-landing-decline\"\n >\n Not now\n </button>\n <div\n ref={loginRef}\n className=\"mero-invite-landing-login\"\n data-testid=\"invite-landing-login\"\n >\n <ConnectButton {...connectButtonProps} label=\"Log in to join\" />\n </div>\n </>\n )}\n </div>\n </div>\n </div>\n );\n}\n\nfunction InviteIcon({ error }: { error: boolean }) {\n const path = error\n ? 'M12 7v6m0 4h.01'\n : 'M4 7l8 6 8-6M5 6h14a1 1 0 011 1v10a1 1 0 01-1 1H5a1 1 0 01-1-1V7a1 1 0 011-1z';\n return (\n <span\n className={error ? 'mero-invite-icon mero-invite-icon-error' : 'mero-invite-icon'}\n aria-hidden=\"true\"\n >\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d={path} />\n </svg>\n </span>\n );\n}\n","/**\n * Join a namespace and one of its contexts from an invitation — the same call\n * whatever the connection is.\n *\n * - A node login publishes its own membership op (`joinNamespace`) and joins\n * the context (`joinContext`) on that node.\n * - An account (no node) signs the join with its device key and hands it to\n * an admitter the invitation names (`useDelegatedBootstrap`); from then on it\n * reaches the namespace through that relay.\n *\n * The app gets one result shape back either way, including whether the failure\n * is FINAL — worth discarding the invitation for — or worth retrying.\n */\nimport { useCallback, useState } from 'react';\nimport type { InviteRedeemer, SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { useDelegatedBootstrap } from '../delegated/useDelegatedBootstrap';\nimport type { BootstrapFailure } from '@calimero-network/mero-js';\nimport { listDelegatedNamespaces, readDelegatedSession } from '@calimero-network/mero-js';\n\n/** The HTTP status an error carries, read the way mero-js's classifier reads it. */\nfunction statusOf(err: unknown): number | undefined {\n if (!err || typeof err !== 'object') return undefined;\n const e = err as { status?: unknown; statusCode?: unknown; response?: { status?: unknown } };\n for (const c of [e.status, e.response?.status, e.statusCode]) {\n if (typeof c === 'number' && Number.isFinite(c)) return c;\n }\n return undefined;\n}\n\nexport interface JoinInvitationInput {\n readonly namespaceId: string;\n /** The context the invitation was for, when it names one; a workspace invitation names none. */\n readonly contextId?: string;\n readonly invitation: SignedGroupOpenInvitation;\n}\n\nexport type JoinInvitationStep = BootstrapFailure['step'] | 'node-join';\n\nexport type JoinInvitationResult =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly step: JoinInvitationStep;\n /** What went wrong, in words a person can act on. */\n readonly reason: string;\n /** True when no retry can succeed: a fresh invitation is the only cure. */\n readonly final: boolean;\n /** The HTTP status of the refusal, when there was one. */\n readonly status?: number;\n };\n\n/** Which step failed, in the words a person can act on. */\nconst STEP_LABEL: Record<BootstrapFailure['step'], string> = {\n 'no-credential': 'No enrolled account',\n 'admitters-lookup': 'Admitters lookup failed',\n 'no-nodes': 'No hosted node serves this namespace',\n 'not-invited': 'This invitation names none of the serving nodes',\n 'invited-unreachable': 'The invited admitter cannot take a join right now',\n 'no-relay-url': 'The invited admitter has no address yet',\n sign: 'The join could not be signed',\n admit: 'The admitter refused the join',\n};\n\n/**\n * Whether an account's join failure is final. Per step: an admitter's 400/403\n * judged the op or the invitation; `not-invited` and `sign` fail identically\n * next time. Everything else (a lookup, an unreachable admitter, no fleet\n * assignment yet, a 409) is kept for a retry.\n */\nfunction accountJoinIsFinal(failure: BootstrapFailure): boolean {\n if (failure.step === 'admit') return failure.status === 400 || failure.status === 403;\n return failure.step === 'not-invited' || failure.step === 'sign';\n}\n\n/**\n * Whether a node's join failure means the invitation itself will never work.\n *\n * Errs toward false: a dropped invitation is unrecoverable for the user, a\n * retried one costs a round trip, so a timeout or anything unfamiliar keeps\n * it. Phrases, not bare words — `\"invalid\"` alone would also match an\n * \"invalid response\" from a proxy, a transient failure.\n */\nexport function isFinalInvitationError(message: string | undefined | null): boolean {\n if (!message) return false;\n const m = message.toLowerCase();\n return [\n 'invitation expired',\n 'expired invitation',\n 'invalid invitation',\n 'invitation is invalid',\n 'malformed invitation',\n 'malformed payload',\n 'invalid signature',\n 'signature verification failed',\n 'not admin',\n 'revoked',\n 'already a member',\n ].some((t) => m.includes(t));\n}\n\nexport function useJoinInvitation(): {\n joinInvitation: (input: JoinInvitationInput) => Promise<JoinInvitationResult>;\n joining: boolean;\n /** The namespaces this connection is a member of: a node's own, or an account's across its relays. */\n memberships: () => Promise<string[]>;\n /**\n * The `{ join, memberships }` pair mero-js's `redeemInvitation` drives, for\n * whichever connection this is, so an app redeems an invitation (join once,\n * then check membership) with no transport of its own. `join` throws on a\n * refusal, carrying its HTTP status for the outcome's reason.\n */\n invitationRedeemer: (input: JoinInvitationInput) => InviteRedeemer;\n} {\n const { mero, isDelegated } = useMero();\n const { credential, bootstrap } = useDelegatedBootstrap();\n const [joining, setJoining] = useState(false);\n\n const joinInvitation = useCallback(\n async (input: JoinInvitationInput): Promise<JoinInvitationResult> => {\n setJoining(true);\n try {\n // An account joins through an admitter: when the connection is one, or\n // when an account is enrolled and no node session exists. A node login\n // joins on its own node even if a credential lingers in this tab.\n const asAccount = isDelegated || (credential !== null && mero === null);\n if (asAccount) {\n const outcome = await bootstrap({\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n contextId: input.contextId,\n });\n if (outcome.ok) return { ok: true };\n return {\n ok: false,\n step: outcome.step,\n reason: `${STEP_LABEL[outcome.step]}. ${outcome.reason}`,\n final: accountJoinIsFinal(outcome),\n ...(outcome.status !== undefined ? { status: outcome.status } : {}),\n };\n }\n\n if (!mero) {\n return { ok: false, step: 'node-join', reason: 'Not connected to a node.', final: false };\n }\n // The admin client directly, not the join hooks: those swallow errors\n // (they resolve to null), which would report a failed join as joined.\n await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });\n if (input.contextId) await mero.admin.joinContext(input.contextId);\n return { ok: true };\n } catch (e) {\n const reason = e instanceof Error ? e.message : String(e);\n const status = statusOf(e);\n return {\n ok: false,\n step: 'node-join',\n reason,\n final: isFinalInvitationError(reason),\n ...(status !== undefined ? { status } : {}),\n };\n } finally {\n setJoining(false);\n }\n },\n [mero, isDelegated, credential, bootstrap],\n );\n\n const memberships = useCallback(async (): Promise<string[]> => {\n const asAccount = isDelegated || (credential !== null && mero === null);\n const ids = (list: ReadonlyArray<{ namespaceId?: string; groupId?: string; id?: string }>) =>\n list.map((n) => n.namespaceId ?? n.groupId ?? n.id ?? '').filter(Boolean);\n if (asAccount) {\n const session = readDelegatedSession();\n return session ? ids(await listDelegatedNamespaces(session)) : [];\n }\n if (!mero) return [];\n return ids((await mero.admin.listNamespaces()) as Array<{ namespaceId?: string; groupId?: string; id?: string }>);\n }, [mero, isDelegated, credential]);\n\n const invitationRedeemer = useCallback(\n (input: JoinInvitationInput): InviteRedeemer => ({\n join: async () => {\n const outcome = await joinInvitation(input);\n if (!outcome.ok) {\n throw Object.assign(new Error(outcome.reason), outcome.status !== undefined ? { status: outcome.status } : {});\n }\n },\n memberships,\n }),\n [joinInvitation, memberships],\n );\n\n return { joinInvitation, joining, memberships, invitationRedeemer };\n}\n"]}
1
+ {"version":3,"sources":["#style-inject:#style-inject","../src/components/styles.css","../src/types.ts","../src/auth/node-trust.ts","../src/auth/token-adoption.ts","../src/storage/index.ts","../src/context/MeroContext.tsx","../src/components/CalimeroLogo.tsx","../src/theme.ts","../src/components/AccountSignInPanel.tsx","../src/delegated/useAccountEnrolment.ts","../src/utils/desktop.ts","../src/components/LoginModal.tsx","../src/components/ConnectButton.tsx","../src/components/ConnectButtonAccount.tsx","../src/utils/base58.ts","../src/hooks/index.ts","../src/components/MigrationPendingBanner.tsx","../src/components/MigrationAdminPanel.tsx","../src/delegated/useDelegatedBootstrap.ts","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/bridge/index.js","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/deep-link/link.js","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/deep-link/pending-intent.js","../node_modules/.pnpm/@calimero-network+mero-platform@0.1.0/node_modules/@calimero-network/mero-platform/dist/deep-link/index.js","../src/invitations/capture.ts","../src/invitations/describeInviteFailure.ts","../src/invitations/justJoined.ts","../src/invitations/useInviteRedemption.ts","../src/invitations/useJoinSync.ts","../src/invitations/InvitationDialog.tsx","../src/invitations/JoinSyncBanner.tsx","../src/invitations/InvitationGate.tsx","../src/join/useJoinInvitation.ts"],"names":["AppMode","ConnectionType","current","refreshToken","createContext","useMemo","LocalStorageTokenStore","useState","readDelegatedSession","useRef","parseAuthCallback","useCallback","MeroJs","buildAuthLoginUrl","saveDelegatedSession","saveDelegatedCredential","clearDelegatedSession","clearDelegatedCredential","useEffect","relayForContext","buildDelegatedClient","readPinnedRelayNodeKey","learnRelayNodeKey","resolveApplicationIdFromRegistry","listDelegatedContexts","AuthRevokedError","HTTPError","joinAsAccount","foundDelegatedNamespace","CloudClient","createAccountAdmin","createNodeAdmin","useContext","jsxs","jsx","readEnrolmentCallback","completeDeviceEnrolment","deviceEnrolmentUrl","DEFAULT_LOCAL_NODE_PORTS","controller","discoverLocalNodes","nodeEndpoint","Fragment","selected","createPortal","classifyError","createDelegatedContext","createDelegatedPrivateContext","governRoot","memberJoinedOpenOp","signerFromSecret","listDelegatedNamespaces","compareSemver","read","readDelegatedCredential","bootstrapFromInvitation","rememberRelay","carryExecutorAccount","storage","listeners","shouldRetain","redeemInvitation","useReducer","useSyncExternalStore","useId","InviteIcon"],"mappings":";;;;;;;;AACyB,SAAR,YAA6B,GAAA,EAAK,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG;AAC1D,EAAA,IAAY,OAAO,QAAA,KAAa,WAAA,EAAa;AAE7C,EAAA,MAAM,OAAO,QAAA,CAAS,IAAA,IAAQ,SAAS,oBAAA,CAAqB,MAAM,EAAE,CAAC,CAAA;AACrE,EAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AAC5C,EAAA,KAAA,CAAM,IAAA,GAAO,UAAA;AAEb,EAAA,IAAI,aAAa,KAAA,EAAO;AACtB,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,IAAA,CAAK,YAAA,CAAa,KAAA,EAAO,IAAA,CAAK,UAAU,CAAA;AAAA,IAC1C,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AAAA,IACxB;AAAA,EACF,CAAA,MAAO;AACL,IAAA,IAAA,CAAK,YAAY,KAAK,CAAA;AAAA,EACxB;AAEA,EAAA,IAAI,MAAM,UAAA,EAAY;AACpB,IAAA,KAA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AQ,OAAA,CAAQ,MAAA,EAAO,GAAI,EAAE,CAAA;AAAA,QAC/G;AAAA,MACF,CAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,gBAAgB,WAAW;AAAA,GAC9B;AAEA,EAAA,OAAO,EAAE,cAAA,EAAgB,OAAA,EAAS,WAAA,EAAa,kBAAA,EAAmB;AACpE","file":"index.cjs","sourcesContent":["\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\":root {\\n --mero-bg: #0d1117;\\n --mero-bg-secondary: #161b22;\\n --mero-bg-tertiary: #1c2128;\\n --mero-text: #e6edf3;\\n --mero-text-secondary: #8b949e;\\n --mero-accent: #a5ff11;\\n --mero-accent-hover: #8ed40d;\\n --mero-on-primary: #0d1117;\\n --mero-error: #ff6b6b;\\n --mero-border: #30363d;\\n --mero-disabled: #555555;\\n --mero-shadow: rgba(0, 0, 0, 0.5);\\n --mero-overlay: rgba(0, 0, 0, 0.75);\\n --mero-radius: 8px;\\n}\\n.mero-connect-button {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n gap: 8px;\\n padding: 10px 20px;\\n background-color: var(--mero-accent);\\n border: 1px solid var(--mero-accent);\\n border-radius: var(--mero-radius);\\n cursor: pointer;\\n font-size: 14px;\\n font-weight: 600;\\n letter-spacing: 0.01em;\\n color: var(--mero-on-primary);\\n transition:\\n background-color 0.15s ease,\\n border-color 0.15s ease,\\n box-shadow 0.15s ease,\\n transform 0.1s ease;\\n min-width: 140px;\\n box-sizing: border-box;\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n -moz-osx-font-smoothing: grayscale;\\n line-height: 1;\\n}\\n.mero-connect-button:hover:not(.mero-connected):not(.mero-reconnecting) {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n box-shadow: 0 0 0 4px rgba(165, 255, 17, 0.18);\\n box-shadow: 0 0 0 4px color-mix(in srgb, var(--mero-accent) 18%, transparent);\\n}\\n.mero-connect-button:active:not(.mero-connected):not(.mero-reconnecting) {\\n transform: translateY(1px);\\n}\\n.mero-connect-button:focus-visible {\\n outline: none;\\n box-shadow: 0 0 0 3px rgba(165, 255, 17, 0.45);\\n box-shadow: 0 0 0 3px color-mix(in srgb, var(--mero-accent) 45%, transparent);\\n}\\n.mero-connect-button.mero-logo-only {\\n min-width: 0;\\n width: 40px;\\n height: 40px;\\n padding: 0;\\n gap: 0;\\n}\\n.mero-connect-button.mero-connected {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n border-color: var(--mero-accent);\\n}\\n.mero-connect-button.mero-connected:hover {\\n background-color: var(--mero-accent-hover);\\n border-color: var(--mero-accent-hover);\\n}\\n.mero-connect-button.mero-reconnecting {\\n background-color: var(--mero-bg-secondary);\\n color: var(--mero-text-secondary);\\n border-color: var(--mero-border);\\n cursor: not-allowed;\\n}\\n.mero-connect-container {\\n position: relative;\\n display: inline-block;\\n}\\n.mero-dropdown {\\n position: absolute;\\n top: 100%;\\n left: 0;\\n background-color: var(--mero-bg-secondary);\\n border: 1px solid var(--mero-border);\\n border-radius: var(--mero-radius);\\n margin-top: 6px;\\n padding: 0;\\n z-index: 1001;\\n width: 100%;\\n min-width: 180px;\\n overflow: hidden;\\n box-shadow: 0 8px 24px var(--mero-shadow);\\n}\\n.mero-dropdown-info {\\n padding: 10px 16px;\\n color: var(--mero-text-secondary);\\n font-size: 13px;\\n border-bottom: 1px solid var(--mero-border);\\n white-space: nowrap;\\n overflow: hidden;\\n text-overflow: ellipsis;\\n max-width: 220px;\\n}\\n.mero-dropdown-item {\\n display: block;\\n width: 100%;\\n padding: 10px 16px;\\n background: none;\\n border: none;\\n color: var(--mero-text);\\n text-align: left;\\n cursor: pointer;\\n font-size: 14px;\\n text-decoration: none;\\n font-family: inherit;\\n}\\n.mero-dropdown-item:hover {\\n background-color: var(--mero-accent);\\n color: var(--mero-on-primary);\\n}\\n.mero-logo {\\n width: 24px;\\n height: 24px;\\n color: currentColor;\\n}\\n@keyframes meroFadeIn {\\n from {\\n opacity: 0;\\n }\\n to {\\n opacity: 1;\\n }\\n}\\n@keyframes meroSlideIn {\\n from {\\n transform: translateY(-12px);\\n opacity: 0;\\n }\\n to {\\n transform: translateY(0);\\n opacity: 1;\\n }\\n}\\n@keyframes meroSpin {\\n to {\\n transform: rotate(360deg);\\n }\\n}\\n.mero-invite-overlay {\\n position: fixed;\\n inset: 0;\\n z-index: 2147483646;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n padding: 16px;\\n background: var(--mero-overlay);\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n}\\n.mero-invite-dialog {\\n box-sizing: border-box;\\n width: min(420px, 100%);\\n padding: 24px;\\n border: 1px solid var(--mero-border);\\n border-radius: calc(var(--mero-radius) * 1.5);\\n background: var(--mero-bg-secondary);\\n color: var(--mero-text);\\n box-shadow: 0 16px 48px var(--mero-shadow);\\n outline: none;\\n animation: mero-invite-in 0.16s ease-out;\\n}\\n.mero-invite-app {\\n margin: 0 0 12px;\\n font-size: 12px;\\n font-weight: 600;\\n letter-spacing: 0.06em;\\n text-transform: uppercase;\\n color: var(--mero-text-secondary);\\n}\\n.mero-invite-head {\\n display: flex;\\n align-items: center;\\n gap: 12px;\\n}\\n.mero-invite-title {\\n margin: 0;\\n min-width: 0;\\n font-size: 18px;\\n font-weight: 600;\\n line-height: 1.3;\\n overflow-wrap: anywhere;\\n}\\n.mero-invite-body {\\n margin: 12px 0 0;\\n font-size: 14px;\\n line-height: 1.5;\\n color: var(--mero-text-secondary);\\n}\\n.mero-invite-body-error {\\n color: var(--mero-error);\\n}\\n.mero-invite-icon {\\n flex: none;\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n width: 36px;\\n height: 36px;\\n border-radius: 50%;\\n background: var(--mero-bg-tertiary);\\n color: var(--mero-accent);\\n}\\n.mero-invite-icon-error {\\n color: var(--mero-error);\\n}\\n.mero-invite-spinner {\\n box-sizing: border-box;\\n width: 36px;\\n height: 36px;\\n border: 3px solid var(--mero-bg-tertiary);\\n border-top-color: var(--mero-accent);\\n background: none;\\n animation: mero-invite-spin 0.8s linear infinite;\\n}\\n.mero-invite-progress {\\n position: relative;\\n height: 3px;\\n margin-top: 16px;\\n overflow: hidden;\\n border-radius: 2px;\\n background: var(--mero-bg-tertiary);\\n}\\n.mero-invite-progress-bar {\\n position: absolute;\\n top: 0;\\n bottom: 0;\\n width: 40%;\\n border-radius: 2px;\\n background: var(--mero-accent);\\n animation: mero-invite-progress 1.4s ease-in-out infinite;\\n}\\n.mero-invite-actions {\\n display: flex;\\n flex-wrap: wrap;\\n justify-content: flex-end;\\n gap: 8px;\\n margin-top: 20px;\\n}\\n.mero-invite-actions:empty {\\n display: none;\\n}\\n.mero-invite-button {\\n padding: 9px 16px;\\n border-radius: var(--mero-radius);\\n font: inherit;\\n font-size: 14px;\\n font-weight: 600;\\n line-height: 1.2;\\n cursor: pointer;\\n transition: background-color 0.15s ease, border-color 0.15s ease;\\n}\\n.mero-invite-button:focus-visible {\\n outline: 2px solid var(--mero-accent);\\n outline-offset: 2px;\\n}\\n.mero-invite-primary {\\n border: 1px solid var(--mero-accent);\\n background: var(--mero-accent);\\n color: var(--mero-on-primary);\\n}\\n.mero-invite-primary:hover {\\n border-color: var(--mero-accent-hover);\\n background: var(--mero-accent-hover);\\n}\\n.mero-invite-secondary {\\n border: 1px solid var(--mero-border);\\n background: transparent;\\n color: var(--mero-text);\\n}\\n.mero-invite-secondary:hover {\\n background: var(--mero-bg-tertiary);\\n}\\n.mero-invite-landing {\\n position: fixed;\\n inset: 0;\\n z-index: 9999;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n padding: 16px;\\n overflow-y: auto;\\n background: var(--mero-bg);\\n color: var(--mero-text);\\n font-family:\\n \\\"Inter\\\",\\n -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n Roboto,\\n Oxygen,\\n Ubuntu,\\n sans-serif;\\n -webkit-font-smoothing: antialiased;\\n}\\n.mero-invite-landing-card {\\n width: min(460px, 100%);\\n}\\n.mero-invite-landing-card .mero-invite-title {\\n font-size: 22px;\\n}\\n.mero-invite-landing-login {\\n display: inline-flex;\\n}\\n.mero-invite-landing-login .mero-connect-button {\\n min-width: 0;\\n padding: 9px 16px;\\n line-height: 1.2;\\n}\\n@keyframes mero-invite-spin {\\n to {\\n transform: rotate(360deg);\\n }\\n}\\n@keyframes mero-invite-progress {\\n from {\\n left: -40%;\\n }\\n to {\\n left: 100%;\\n }\\n}\\n@keyframes mero-invite-in {\\n from {\\n opacity: 0;\\n transform: translateY(6px) scale(0.98);\\n }\\n}\\n@media (prefers-reduced-motion: reduce) {\\n .mero-invite-dialog,\\n .mero-invite-spinner,\\n .mero-invite-progress-bar {\\n animation: none;\\n }\\n}\\n\")","/**\n * Types for mero-react\n */\n\nimport type { MeroClient, MeroJs, TokenStore } from '@calimero-network/mero-js';\nimport type { DelegatedAccountSession as DelegatedSession } from '@calimero-network/mero-js';\n\n/**\n * Application mode determines the permission scope\n */\nexport enum AppMode {\n /**\n * @deprecated since 2.1.0 — SingleContext is no longer supported and will\n * be removed in 3.0.0. Auth-frontend no longer drives\n * context/namespace/group selection; the auth callback returns only\n * `access_token`, `refresh_token`, `application_id`, and `node_url`.\n * Switch to {@link AppMode.MultiContext} and have your app manage\n * context selection itself.\n *\n * Migration: see `example/app/src/pages/context/SelectContext.tsx` for a\n * reference implementation. It uses `useContexts` /\n * `useNamespacesForApplication` for listing, then calls\n * `mero.admin.createNamespace` / `createGroupInNamespace` /\n * `createContext` directly (rather than the `useCreate*` hooks) so the\n * underlying server error surfaces to the user instead of being\n * swallowed by `useAsyncMutation`.\n */\n SingleContext = 'single-context',\n /** Multi-context: user can manage multiple contexts */\n MultiContext = 'multi-context',\n /** Admin: full administrative access */\n Admin = 'admin',\n}\n\n/**\n * Connection type for the login modal\n */\nexport enum ConnectionType {\n /**\n * @deprecated The login modal no longer has Local/Remote tabs — it always\n * shows node discovery + manual URL entry. Behaves the same as `Remote`.\n */\n RemoteAndLocal = 'remote-and-local',\n /** Open the login modal (node discovery + manual URL entry) */\n Remote = 'remote',\n /**\n * @deprecated The hardcoded default-local-node view was removed. Behaves\n * the same as `Remote`.\n */\n Local = 'local',\n /** Custom URL (skip modal) */\n Custom = 'custom',\n}\n\n/**\n * Custom connection configuration\n */\nexport interface CustomConnectionConfig {\n type: ConnectionType.Custom;\n url: string;\n}\n\n/**\n * Context for an application\n */\nexport interface AppContext {\n contextId: string;\n executorId: string;\n applicationId: string;\n}\n\n/**\n * Result of an RPC execution\n */\nexport interface ExecutionResult<T = unknown> {\n success: boolean;\n result?: T;\n error?: string;\n}\n\nexport interface ApplicationContextRecord {\n contextId: string;\n applicationId: string;\n}\n\nexport interface ContextDiscoveryOptions {\n applicationId: string;\n knownContextIds?: string[];\n targetAlias?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface ContextDiscoveryState {\n context: ApplicationContextRecord | null;\n loading: boolean;\n error: Error | null;\n discover: () => Promise<ApplicationContextRecord | null>;\n reset: () => void;\n}\n\n/**\n * Mero context value exposed by useMero hook\n */\nexport interface MeroContextValue {\n /**\n * The connected client, or null.\n *\n * Two shapes, because there are two ways to connect: a node login yields a\n * `MeroJs`, an account + relay connection yields a relay-transport\n * `MeroClient`. Both expose `rpc` as an `ExecuteTransport`, which is what a\n * generated ABI client depends on — so application logic is identical across\n * the two and needs no branch.\n *\n * The union is deliberately not flattened behind a cast. A relay client has\n * no `admin`, so code reaching for one should not typecheck as though it\n * were there; narrow with {@link MeroContextValue.isDelegated} first.\n */\n mero: MeroJs | MeroClient | null;\n /** Whether the user is authenticated */\n isAuthenticated: boolean;\n /** Whether the connection is online */\n isOnline: boolean;\n /** The current node URL */\n nodeUrl: string | null;\n /** The application ID */\n applicationId: string | null;\n /** The context ID (from auth flow) */\n contextId: string | null;\n /** The context identity / executor public key (from auth flow) */\n contextIdentity: string | null;\n /** Connect to a node URL and start auth flow */\n connectToNode: (url: string) => void;\n /**\n * Adopt a delegated connection: an account, a device that account certified,\n * and a relay that writes on its behalf.\n *\n * Installs the relay client immediately — there is no redirect and no token to\n * wait for, because every request carries its own warrant.\n */\n connectWithAccount: (session: DelegatedSession) => void;\n /**\n * Whether the connection is delegated (account + relay) rather than a node\n * login. True means `mero` is a relay-transport client, authenticated by the\n * account's device certificate: `rpc` writes under warrants, and `admin` and\n * `events` answer caller-scoped — this account's own contexts and namespaces,\n * and events only for contexts it is a member of.\n */\n isDelegated: boolean;\n /**\n * What this connection may do, so an app asks WHAT IS ALLOWED instead of\n * which transport it runs on. A node login can do everything; an account on\n * a relay can create contexts (delegated creation) but not namespaces or\n * invitations — those are a node's own operations today. A capability that\n * later becomes available to accounts turns true here with no app change.\n */\n can: MeroCapabilities;\n /**\n * The admin API to write against, whatever the session: the node's own admin\n * client on a node, the account admin (`createAccountAdmin`) on an account.\n * `null` until connected.\n */\n admin: import('@calimero-network/mero-js').AdminApiClient | null;\n /**\n * The app's registry identity, as the provider was given it. An account\n * founding a namespace names this application for it, since a namespace\n * founded through a relay starts with none.\n */\n app: { packageName?: string; packageVersion?: string; registryUrl?: string };\n /** The cloud an account asks for routing; the hosted one when unset. */\n cloudBaseUrl?: string;\n /** Logout and clear tokens */\n logout: () => void;\n /** Loading state */\n isLoading: boolean;\n}\n\n/**\n * MeroProvider configuration\n */\nexport interface MeroProviderConfig {\n /** Application mode */\n mode: AppMode;\n /** Package name (for registry-based apps) */\n packageName?: string;\n /** Package version (optional, defaults to latest) */\n packageVersion?: string;\n /** Registry URL (optional) */\n registryUrl?: string;\n /**\n * The cloud an account asks which relay serves a namespace or an account.\n * Unset is the hosted cloud, which is right for every deployed app; this is\n * for a local or staging setup whose namespaces the hosted cloud never saw.\n */\n cloudBaseUrl?: string;\n /** Request timeout in milliseconds */\n timeoutMs?: number;\n /**\n * Origins the OAuth callback is allowed to authenticate against. Defends\n * against a malicious `node_url` in the callback URL (token exfiltration):\n * the node login was initiated with is always trusted, and this allowlist\n * additionally permits direct-callback entry to known nodes. When neither is\n * available (no initiated node and no allowlist) a callback node_url is\n * rejected and a security error is logged.\n */\n allowedNodeUrls?: string[];\n /**\n * Token store for access/refresh tokens. Defaults to a localStorage-backed\n * store that persists across reloads.\n *\n * SECURITY: localStorage tokens — including the refresh token — are readable\n * by any script on the page, so an XSS bug can exfiltrate them. For sensitive\n * deployments pass a `MemoryTokenStore` (session-only) or a store backed by an\n * HttpOnly cookie set by your auth service.\n */\n tokenStore?: TokenStore;\n}\n\n/** See {@link MeroContextValue.can}. */\nexport interface MeroCapabilities {\n /** Found a namespace. */\n readonly createNamespace: boolean;\n /** Create a context inside a namespace this connection belongs to. */\n readonly createContext: boolean;\n /** Mint an invitation to a namespace. */\n readonly invite: boolean;\n /** Upgrade a group's application. A node's only: a relay carries just the first choice. */\n readonly upgrade: boolean;\n}\n","/**\n * Trust decision for the node URL an OAuth callback wants us to authenticate\n * against.\n *\n * The auth flow redirects the browser to a node's auth UI and back to the app\n * with `access_token` / `refresh_token` / `node_url` in the callback URL. That\n * URL is attacker-influenceable, so a malicious `node_url` would otherwise make\n * the SDK send the freshly-minted tokens to an attacker's node (exfiltration).\n *\n * Defense: only authenticate against a node we can independently trust — the\n * node login was *initiated* with (saved before the redirect), or an\n * app-configured allowlist.\n */\n\n/** True iff both URLs parse and share the same origin (scheme + host + port). */\nexport function sameOrigin(a: string, b: string): boolean {\n try {\n return new URL(a).origin === new URL(b).origin;\n } catch {\n return false;\n }\n}\n\nexport interface ResolveTrustedNodeParams {\n /** `node_url` from the OAuth callback (untrusted, attacker-influenceable). */\n candidate: string | null | undefined;\n /** Node URL login was initiated with, saved before the redirect (trusted). */\n initiated: string | null;\n /** Additional trusted origins, for direct-callback entry without an initiated node. */\n allowedNodeUrls?: string[];\n}\n\nexport interface TrustedNodeResult {\n /** The node URL that is safe to authenticate against, or null. */\n url: string | null;\n /** A candidate node_url was present but could not be trusted (likely an attack). */\n rejected: boolean;\n}\n\n/**\n * Decide which node URL, if any, is safe to authenticate against.\n *\n * - No candidate → fall back to the initiated node.\n * - Candidate + initiated node → must share the initiated node's origin, else reject.\n * - Candidate + no initiated node + allowlist → must be in the allowlist, else reject.\n * - Candidate + no trust anchor (no initiated node and no allowlist) → reject. There is\n * nothing to validate the attacker-influenceable callback against, so refusing is the\n * safe default. The normal flow always records the initiated node (via `connectToNode`)\n * before redirecting; configure `allowedNodeUrls` to permit direct-callback entry.\n */\nexport function resolveTrustedNodeUrl(params: ResolveTrustedNodeParams): TrustedNodeResult {\n const { candidate, initiated, allowedNodeUrls } = params;\n\n if (!candidate) {\n return { url: initiated ?? null, rejected: false };\n }\n\n if (initiated) {\n return sameOrigin(candidate, initiated)\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n if (allowedNodeUrls && allowedNodeUrls.length > 0) {\n return allowedNodeUrls.some((u) => sameOrigin(candidate, u))\n ? { url: candidate, rejected: false }\n : { url: null, rejected: true };\n }\n\n return { url: null, rejected: true };\n}\n","/**\n * Decide whether the token bundle carried in an SSO callback hash may replace\n * the bundle already in the token store.\n *\n * Since core 0.11.0 (calimero-network/core#3083) refresh tokens are SINGLE-USE:\n * every `POST /auth/refresh` consumes the presented refresh token and returns a\n * new one. Re-presenting a consumed refresh token is treated as theft — the node\n * answers 401 `x-auth-error: token_reuse` and revokes the whole token family, so\n * *every* holder is hard-logged-out.\n *\n * That makes an unconditional `tokenStore.setTokens(callbackBundle)` on the SSO\n * callback path actively dangerous. A desktop host (or any SSO initiator) hands\n * the app a token bundle in the URL hash; if mero-js has already rotated the\n * stored refresh token, writing the hash bundle over it resurrects a *consumed*\n * refresh token. The next refresh presents it → `token_reuse` → family revoked.\n *\n * So the hash bundle is adopted only when it is safe:\n * - there is no stored bundle (a genuinely fresh login), or\n * - the node changed (the stored bundle belongs to a different node), or\n * - the hash tokens are genuinely NEWER than what is stored, or\n * - the stored bundle is missing a refresh token that the hash can supply.\n *\n * Anything else — a stale hash, or a hash replaying the access token we already\n * hold — is ignored, leaving the live (possibly rotated) bundle untouched.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\nimport { sameOrigin } from './node-trust';\n\nconst HOUR_MS = 3_600_000;\n\ninterface JwtClaims {\n /** Issued-at (seconds). The authoritative rotation-order signal when present. */\n iat?: number;\n /** Expiry (seconds). */\n exp?: number;\n}\n\n/**\n * Decode a JWT's payload claims without verifying the signature.\n *\n * Verification is the node's job — we only need the ordering claims to decide\n * which of two bundles is newer, and both bundles are already node-trusted by\n * the time we get here (see `resolveTrustedNodeUrl`).\n *\n * Returns null for anything that is not a decodable three-part JWT (opaque\n * tokens, test fixtures, garbage).\n */\nexport function decodeJwtClaims(token: string): JwtClaims | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n let b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');\n while (b64.length % 4) b64 += '=';\n const payload: unknown = JSON.parse(atob(b64));\n if (!payload || typeof payload !== 'object') return null;\n const { iat, exp } = payload as JwtClaims;\n return {\n iat: typeof iat === 'number' && iat > 0 ? iat : undefined,\n exp: typeof exp === 'number' && exp > 0 ? exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Absolute expiry (ms) of an access token, from its `exp` claim.\n *\n * Mirrors mero-js's internal `expiresAtFromJwt` (which it does not export —\n * checked against mero-js 6.1.0), including the \"assume one hour\" fallback for\n * tokens whose expiry we cannot read.\n */\nexport function expiresAtFromJwt(token: string, fallbackMs: number = Date.now() + HOUR_MS): number {\n const exp = decodeJwtClaims(token)?.exp;\n return exp ? exp * 1000 : fallbackMs;\n}\n\n/**\n * Is the callback's access token newer than the one we already hold?\n *\n * Prefers `iat` (issued-at) — the direct rotation-order signal — and falls back\n * to `exp`, then to the stored bundle's recorded `expires_at`. When the answer\n * cannot be established the token is NOT considered newer: refusing to adopt\n * costs a redundant login at worst, whereas adopting a stale bundle burns the\n * whole token family.\n */\nfunction isCallbackNewer(callbackAccessToken: string, stored: TokenData): boolean {\n const incoming = decodeJwtClaims(callbackAccessToken);\n if (!incoming) return false;\n\n const current = decodeJwtClaims(stored.access_token);\n if (current) {\n if (incoming.iat !== undefined && current.iat !== undefined && incoming.iat !== current.iat) {\n return incoming.iat > current.iat;\n }\n if (incoming.exp !== undefined && current.exp !== undefined && incoming.exp !== current.exp) {\n return incoming.exp > current.exp;\n }\n // Same claims (a replay of the token we already hold), or nothing to compare\n // on — either way the callback brings nothing new.\n return false;\n }\n\n // Stored access token is not a decodable JWT — compare against the expiry the\n // store recorded for it.\n return incoming.exp !== undefined && incoming.exp * 1000 > stored.expires_at;\n}\n\n/** Why the SSO hash bundle was (or was not) written to the token store. */\nexport type TokenAdoptionReason =\n /** No stored bundle — a genuinely fresh login. Seed from the hash. */\n | 'fresh-login'\n /** The stored bundle belongs to a different node. Re-seed from the hash. */\n | 'node-changed'\n /** The hash tokens are genuinely newer than the stored ones. */\n | 'newer'\n /** Same session, but the stored bundle has no refresh token and the hash does. */\n | 'fill-refresh'\n /** The hash tokens are stale, or replay the access token we already hold. */\n | 'stale';\n\nexport type TokenAdoptionDecision =\n | { adopt: true; tokens: TokenData; reason: Exclude<TokenAdoptionReason, 'stale'> }\n | { adopt: false; reason: 'stale' };\n\nexport interface ResolveTokenAdoptionParams {\n /** Access token from the callback hash. Always present (mero-js returns null otherwise). */\n callbackAccessToken: string;\n /**\n * Refresh token from the callback hash. `parseAuthCallback` yields `''` when the\n * hash carries no `refresh_token` — hosts are moving to access-only bundles\n * precisely so they cannot hand back a rotated-away refresh token.\n */\n callbackRefreshToken: string;\n /** Trusted node URL the callback resolved to (see `resolveTrustedNodeUrl`). */\n callbackNodeUrl: string;\n /** Bundle currently in the token store — mero-js may have rotated it already. */\n stored: TokenData | null;\n /** Node URL the stored bundle was issued by, i.e. the node URL before this callback. */\n storedNodeUrl: string | null;\n}\n\n/**\n * Decide what (if anything) to write to the token store for an SSO callback.\n *\n * Never returns a bundle with an empty `refresh_token` when a refresh token for\n * the same node is already stored: an access-only hash bundle is MERGED over the\n * stored one, so adopting a fresher access token cannot strip the session's\n * ability to refresh.\n */\nexport function resolveTokenAdoption(params: ResolveTokenAdoptionParams): TokenAdoptionDecision {\n const { callbackAccessToken, callbackRefreshToken, callbackNodeUrl, stored, storedNodeUrl } =\n params;\n\n const bundle = (refreshToken: string): TokenData => ({\n access_token: callbackAccessToken,\n refresh_token: refreshToken,\n expires_at: expiresAtFromJwt(callbackAccessToken),\n });\n\n // Fresh login — nothing to protect.\n if (!stored?.access_token) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'fresh-login' };\n }\n\n // Different node — the stored bundle is for someone else's token family, and\n // its refresh token is meaningless here, so it must NOT be carried over.\n const sameNode = !!storedNodeUrl && sameOrigin(callbackNodeUrl, storedNodeUrl);\n if (!sameNode) {\n return { adopt: true, tokens: bundle(callbackRefreshToken), reason: 'node-changed' };\n }\n\n // Same node, live bundle. Keep the stored refresh token unless the hash carries\n // one — the hash's refresh token may be a copy that mero-js has already rotated\n // away, but an *empty* one would strip refresh from the session entirely.\n const refreshToken = callbackRefreshToken || stored.refresh_token;\n\n if (isCallbackNewer(callbackAccessToken, stored)) {\n return { adopt: true, tokens: bundle(refreshToken), reason: 'newer' };\n }\n\n // The access token is not newer, but the stored bundle cannot refresh and the\n // hash can repair that. Keep the *stored* access token (it is at least as new).\n if (!stored.refresh_token && callbackRefreshToken) {\n return {\n adopt: true,\n tokens: { ...stored, refresh_token: callbackRefreshToken },\n reason: 'fill-refresh',\n };\n }\n\n // Stale (or a replay of the bundle we already hold). Writing it would resurrect\n // a consumed refresh token → `token_reuse` → the node revokes the whole family.\n return { adopt: false, reason: 'stale' };\n}\n","/**\n * Storage utilities for mero-react\n * \n * Provides localStorage-based token storage and other persistence utilities.\n */\n\nimport type { TokenData } from '@calimero-network/mero-js';\n\n// Storage keys\nconst STORAGE_KEYS = {\n ACCESS_TOKEN: 'mero:access_token',\n REFRESH_TOKEN: 'mero:refresh_token',\n EXPIRES_AT: 'mero:expires_at',\n NODE_URL: 'mero:node_url',\n // The node the token bundle currently in the TokenStore was issued by. Distinct\n // from NODE_URL, which `connectToNode` overwrites with the *target* node before\n // redirecting to login — so at callback time NODE_URL names where we are going,\n // not who minted the tokens we still hold. Telling those apart is what lets the\n // SSO callback re-seed on a node change without mistaking a different node's\n // bundle for a rotated one (see auth/token-adoption.ts).\n TOKEN_NODE_URL: 'mero:token_node_url',\n APPLICATION_ID: 'mero:application_id',\n CONTEXT_ID: 'mero:context_id',\n CONTEXT_IDENTITY: 'mero:context_identity',\n} as const;\n\nlet _storageAvailable: boolean | null = null;\n\nfunction isLocalStorageAvailable(): boolean {\n if (_storageAvailable !== null) return _storageAvailable;\n try {\n if (typeof window === 'undefined' || !window.localStorage) {\n _storageAvailable = false;\n return false;\n }\n const testKey = '__mero_test__';\n localStorage.setItem(testKey, 'test');\n localStorage.removeItem(testKey);\n _storageAvailable = true;\n } catch {\n _storageAvailable = false;\n }\n return _storageAvailable;\n}\n\nexport const localStorageTokenStorage = {\n async get(): Promise<TokenData | null> {\n if (!isLocalStorageAvailable()) {\n return null;\n }\n\n try {\n const accessToken = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);\n const refreshToken = localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);\n const expiresAt = localStorage.getItem(STORAGE_KEYS.EXPIRES_AT);\n\n if (!accessToken || !refreshToken) {\n return null;\n }\n\n return {\n access_token: accessToken,\n refresh_token: refreshToken,\n expires_at: expiresAt ? parseInt(expiresAt, 10) : Date.now() + 3600000,\n };\n } catch (e) {\n console.error('[mero-react] Failed to get token from storage:', e);\n return null;\n }\n },\n\n async set(token: TokenData): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.setItem(STORAGE_KEYS.ACCESS_TOKEN, token.access_token);\n localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, token.refresh_token);\n localStorage.setItem(STORAGE_KEYS.EXPIRES_AT, token.expires_at.toString());\n } catch (e) {\n console.error('[mero-react] Failed to save token to storage:', e);\n }\n },\n\n async clear(): Promise<void> {\n if (!isLocalStorageAvailable()) {\n return;\n }\n\n try {\n localStorage.removeItem(STORAGE_KEYS.ACCESS_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);\n localStorage.removeItem(STORAGE_KEYS.EXPIRES_AT);\n } catch (e) {\n console.error('[mero-react] Failed to clear token from storage:', e);\n }\n },\n};\n\n/**\n * Get the stored node URL\n */\nexport function getNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Set the node URL\n */\nexport function setNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.NODE_URL, url);\n}\n\n/**\n * Clear the node URL\n */\nexport function clearNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.NODE_URL);\n}\n\n/**\n * Get the node URL that minted the token bundle currently in the TokenStore.\n */\nexport function getTokenNodeUrl(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Record the node URL that minted the token bundle now in the TokenStore.\n */\nexport function setTokenNodeUrl(url: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.TOKEN_NODE_URL, url);\n}\n\n/**\n * Clear the token bundle's node URL\n */\nexport function clearTokenNodeUrl(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.TOKEN_NODE_URL);\n}\n\n/**\n * Get the stored application ID\n */\nexport function getApplicationId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Set the application ID\n */\nexport function setApplicationId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.APPLICATION_ID, id);\n}\n\n/**\n * Clear the application ID\n */\nexport function clearApplicationId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.APPLICATION_ID);\n}\n\n/**\n * Get the stored context ID\n */\nexport function getContextId(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Set the context ID\n */\nexport function setContextId(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_ID, id);\n}\n\n/**\n * Clear the context ID\n */\nexport function clearContextId(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_ID);\n}\n\n/**\n * Get the stored context identity\n */\nexport function getContextIdentity(): string | null {\n if (!isLocalStorageAvailable()) return null;\n return localStorage.getItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Set the context identity\n */\nexport function setContextIdentity(id: string): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.setItem(STORAGE_KEYS.CONTEXT_IDENTITY, id);\n}\n\n/**\n * Clear the context identity\n */\nexport function clearContextIdentity(): void {\n if (!isLocalStorageAvailable()) return;\n localStorage.removeItem(STORAGE_KEYS.CONTEXT_IDENTITY);\n}\n\n/**\n * Clear all mero-react storage\n */\nexport function clearAllStorage(): void {\n if (!isLocalStorageAvailable()) return;\n Object.values(STORAGE_KEYS).forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n","import React, {\n createContext,\n useContext,\n useState,\n useEffect,\n useCallback,\n useRef,\n useMemo,\n} from 'react';\nimport {\n MeroJs,\n LocalStorageTokenStore,\n parseAuthCallback,\n buildAuthLoginUrl,\n AuthRevokedError,\n HTTPError,\n} from '@calimero-network/mero-js';\nimport { AppMode } from '../types';\nimport { CloudClient } from '@calimero-network/mero-js';\nimport type { AdminApiClient, AuthCallbackResult, MeroClient, TokenStore } from '@calimero-network/mero-js';\nimport { createNodeAdmin } from '@calimero-network/mero-js';\nimport { createAccountAdmin } from '@calimero-network/mero-js';\nimport { joinAsAccount } from '@calimero-network/mero-js';\nimport { foundDelegatedNamespace } from '@calimero-network/mero-js';\nimport { resolveTrustedNodeUrl } from '../auth/node-trust';\nimport { resolveTokenAdoption } from '../auth/token-adoption';\nimport {\n getNodeUrl,\n setNodeUrl,\n getTokenNodeUrl,\n setTokenNodeUrl,\n getApplicationId,\n setApplicationId,\n getContextId,\n setContextId,\n getContextIdentity,\n setContextIdentity,\n clearAllStorage,\n} from '../storage';\nimport type { MeroContextValue, MeroProviderConfig } from '../types';\n\nimport {\n buildDelegatedClient,\n clearDelegatedCredential,\n clearDelegatedSession,\n readDelegatedSession,\n listDelegatedContexts,\n readPinnedRelayNodeKey,\n learnRelayNodeKey,\n relayForContext,\n saveDelegatedCredential,\n saveDelegatedSession,\n type DelegatedAccountSession as DelegatedSession,\n} from '@calimero-network/mero-js';\nimport { resolveApplicationIdFromRegistry } from '@calimero-network/mero-js';\n\nconst MeroContext = createContext<MeroContextValue | null>(null);\n\n/** The registry an app's package is looked up in when none is configured; the account admin's default too. */\nconst DEFAULT_REGISTRY_URL = 'https://apps.calimero.network';\n\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Permission grants requested for the client token at login.\n *\n * Cores since 0.11.0-rc.9 default-deny admin-api routes the token holds no\n * scope for; cores >=0.11.0-rc.11 map the governance/blob/alias routes to the\n * client-grantable `namespace` / `group` / `blob` / `context:alias`\n * permissions, so app tokens must request them here or every workspace,\n * group, blob and context-alias call 403s.\n *\n * `context:list` is included even in single-context mode because every app\n * calls GET /admin-api/contexts/:id/identities-owned right after login, which\n * maps to a `context:list` requirement.\n *\n * `context:subscribe` is what `/sse`, `/sse/subscription` and `/ws` require\n * (core's `PermissionValidator`, `validator.rs`, maps all three to\n * `Context(Subscribe(Global))`). Without it every event stream an app opens is\n * refused `403` + `X-Auth-Error: permission_denied`, so the app renders, reads\n * and writes, and simply never receives a live update. Only `AppMode.Admin`\n * escaped, because `admin` covers every route.\n *\n * MEASURED against merod 0.11.0-rc.41 (build 88e323b): a client key minted with\n * the MultiContext list below minus `context:subscribe` gets `403` on\n * `GET /sse`; the same list with it gets `200`.\n *\n * `context:delete` is what `DELETE /admin-api/contexts/:id` requires\n * (`validator.rs`). An app that may create contexts may delete them, so\n * `useDeleteContext` works on a node instead of answering 403.\n *\n * Public: whatever mints a token for a mero-react app on its behalf (the\n * desktop's per-app key, admin-dashboard's, auth-frontend's allowlist) should\n * test against this rather than a hand copy. Three copies went without\n * `context:delete` and every app's context delete answered 403.\n */\nexport function getPermissionsForMode(mode: AppMode): string[] {\n switch (mode) {\n case AppMode.SingleContext:\n return [\n 'context:execute',\n 'context:list',\n 'context:subscribe',\n 'application:list',\n 'blob',\n 'context:alias',\n ];\n case AppMode.MultiContext:\n return [\n 'context:create',\n 'context:delete',\n 'context:list',\n 'context:execute',\n 'context:subscribe',\n 'application:list',\n 'namespace',\n 'group',\n 'blob',\n 'context:alias',\n ];\n case AppMode.Admin:\n return ['admin'];\n default:\n throw new Error(`Unsupported application mode: ${mode}`);\n }\n}\n\nexport interface MeroProviderProps extends MeroProviderConfig {\n children: React.ReactNode;\n}\n\nexport function MeroProvider({\n children,\n mode,\n packageName,\n packageVersion,\n registryUrl,\n cloudBaseUrl,\n timeoutMs = 30000,\n allowedNodeUrls,\n tokenStore: tokenStoreProp,\n}: MeroProviderProps) {\n const tokenStore = useMemo<TokenStore>(\n () => tokenStoreProp ?? new LocalStorageTokenStore(),\n [tokenStoreProp],\n );\n const [mero, setMero] = useState<MeroJs | MeroClient | null>(null);\n /**\n * The delegated record, or null for the node-login path.\n *\n * Read from storage in the initializer rather than an effect: a reload of a\n * delegated tab should render connected, not flash the connect button and\n * then replace it.\n */\n const [delegated, setDelegated] = useState<DelegatedSession | null>(() =>\n readDelegatedSession(),\n );\n const [isAuthenticated, setIsAuthenticated] = useState(false);\n const [isOnline, setIsOnline] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [nodeUrl, setNodeUrlState] = useState<string | null>(() => getNodeUrl());\n const [applicationId, setApplicationIdState] = useState<string | null>(\n () => getApplicationId() || null,\n );\n const [contextId, setContextIdState] = useState<string | null>(() => getContextId());\n const [contextIdentity, setContextIdentityState] = useState<string | null>(() => getContextIdentity());\n\n const meroRef = useRef<MeroJs | null>(null);\n // Guards the SSE 401 recovery below, so a burst of reconnect failures can't\n // stack concurrent validate/refresh attempts over one single-use refresh token.\n const recoveringRef = useRef(false);\n\n // Parse auth callback ONCE in a ref (StrictMode-safe: refs persist across unmount/remount)\n const callbackRef = useRef<AuthCallbackResult | null | undefined>(undefined);\n if (callbackRef.current === undefined && isBrowser) {\n callbackRef.current = parseAuthCallback(window.location.href);\n }\n\n const createMeroInstance = useCallback(\n (url: string): MeroJs => {\n if (meroRef.current) {\n meroRef.current.close();\n }\n const instance = new MeroJs({\n baseUrl: url,\n tokenStore,\n timeoutMs,\n });\n meroRef.current = instance;\n return instance;\n },\n [timeoutMs, tokenStore],\n );\n\n const checkAuth = useCallback(\n async (instance: MeroJs): Promise<boolean> => {\n // Validate the session via /auth/validate (signature, revocation, node\n // binding — no permission requirement) instead of probing\n // GET /admin-api/contexts. Since core 0.11.0-rc.9 the node enforces\n // token permission scopes, and /admin-api/contexts requires Global\n // `context:list` — which single-context tokens (execute-only) and\n // app-scoped tokens don't hold, so probing it 403'd valid sessions and\n // bounced every app straight back to the login page.\n // Through the client: it reads back only the bundle its own node issued.\n const accessToken = instance.getTokenData()?.access_token;\n if (!accessToken) return false;\n\n const validate = async (token: string): Promise<boolean> => {\n try {\n const { valid } = await instance.auth.validateToken(token);\n return valid;\n } catch {\n return false;\n }\n };\n\n if (await validate(accessToken)) return true;\n\n // An expired access token does NOT mean the session is over: refresh\n // tokens last 30 days against core's 1-hour access TTL, so on any reload\n // more than an hour after login we land here holding a perfectly good\n // refresh token.\n //\n // `validateToken` has in fact already spent it. It pins the token under\n // test into an explicit `Authorization` header, and mero-js's init\n // headers override the transport's own token (mero-js\n // http-client/web-client.js `buildHeaders`). So the 401 + `x-auth-error:\n // token_expired` trips the transport's refresh hook — rotating the stored\n // bundle — and then the retry re-sends the SAME stale header, 401s again,\n // and reports `valid: false`. The session was silently renewed and thrown\n // away, and the app bounced to login; a second reload would then \"fix\"\n // itself, which is exactly how this reads as a random logout.\n //\n // So: re-read the token, and if the transport rotated it underneath us,\n // judge the session on the token we ACTUALLY hold now. We never call\n // /auth/refresh ourselves — doing so would race mero-js's single-flight\n // lock over a single-use refresh token and get the whole family revoked\n // (calimero-network/core#3083).\n const rotated = instance.getTokenData()?.access_token;\n if (!rotated || rotated === accessToken) return false;\n return validate(rotated);\n },\n [],\n );\n\n const connectToNode = useCallback(\n (url: string) => {\n if (!isBrowser) return;\n setNodeUrl(url);\n setNodeUrlState(url);\n\n const callbackUrl = new URL(window.location.href);\n callbackUrl.hash = '';\n\n const loginUrl = buildAuthLoginUrl(url, {\n callbackUrl: callbackUrl.toString(),\n permissions: getPermissionsForMode(mode),\n mode,\n packageName,\n packageVersion,\n registryUrl,\n });\n\n window.location.href = loginUrl;\n },\n [mode, packageName, packageVersion, registryUrl],\n );\n\n /**\n * Adopt a delegated connection.\n *\n * No redirect and nothing to await: a delegated client carries its own\n * credential on every request, so it is usable the moment it is built. The\n * record is persisted first so a reload finds it.\n */\n const connectWithAccount = useCallback((session: DelegatedSession) => {\n saveDelegatedSession(session);\n // Kept as a credential too, so the identity outlives the connection. A relay\n // can be lost without the certificate being lost — the fleet row goes stale,\n // or the record is cleared — and re-enrolling to recover a key this tab still\n // holds would be a new device for no reason.\n const { account, credential, deviceSecret } = session;\n saveDelegatedCredential({ account, credential, deviceSecret });\n setDelegated(session);\n }, []);\n\n const logout = useCallback(() => {\n if (meroRef.current) {\n meroRef.current.clearToken();\n meroRef.current.close();\n }\n // Always clear the token store, even when not connected (meroRef is null) —\n // otherwise the access/refresh tokens persist in storage after logout.\n tokenStore.clear();\n clearAllStorage();\n clearDelegatedSession();\n // The certificate goes too. Logging out of an account and leaving its device\n // key in storage would leave the next visitor able to bootstrap as it from\n // any invitation they hold.\n clearDelegatedCredential();\n setDelegated(null);\n setMero(null);\n setIsAuthenticated(false);\n setNodeUrlState(null);\n setApplicationIdState(null);\n setContextIdState(null);\n setContextIdentityState(null);\n meroRef.current = null;\n }, [tokenStore]);\n\n /**\n * Install the relay client for a delegated record.\n *\n * Separate effect from the node-login initializer below, and the two are\n * mutually exclusive: a delegated connection has no token to adopt, no node\n * URL to validate and no callback to consume, so running that machinery for\n * it would only find nothing and log out.\n */\n useEffect(() => {\n if (!delegated) return;\n // Re-keys the warrant-nonce ledger when the chosen context changes, which is\n // why `contextId` is a dependency. The context itself is NOT set from here —\n // it comes from storage (the initializer above) or from whatever the app's\n // own picker selected, exactly as on the node-login path.\n // The open context's own relay: an account's namespaces may each be served\n // by a different one. Unknown (no context yet, or one not listed yet) →\n // the session's relay, which is the one that admitted it most recently.\n const relayUrl =\n (contextId ? relayForContext(delegated.account, contextId) : null) ?? delegated.relayUrl;\n const routed = { ...delegated, relayUrl };\n const client = buildDelegatedClient(routed, contextId);\n // A relay whose node key is not known yet: learn it before handing the app a\n // client. Published without it, the app's subscriptions open `/sse` on a\n // client with no session, which a hosted relay refuses with a 401 — the\n // client rebuilt a moment later reconnects, but the refusal is noise.\n const awaitingKey = Boolean(client && relayUrl && !readPinnedRelayNodeKey(relayUrl));\n // `null` when the account holds no relay yet, and the session is still\n // authenticated. Being signed in is how an account comes to be invited, so a\n // relay cannot be a precondition for it — and `mero: null` is what makes a\n // write say \"there is no relay\" instead of failing against a guessed node.\n if (!awaitingKey) setMero(client);\n setIsAuthenticated(true);\n setIsOnline(true);\n setNodeUrlState(relayUrl);\n setIsLoading(awaitingKey);\n\n /*\n * Which application this tab is for, asked rather than told.\n *\n * The node-login path is handed an `applicationId` by the auth callback. A\n * delegated tab has no callback, so it had none — and an app's context\n * picker that filters on it (correctly: \"I cannot tell which are mine\" and\n * \"all of them are mine\" are different answers) then had nothing to filter\n * with and stayed empty forever. That, not the relay, was the last reason\n * anyone had to type a context id in.\n *\n * `admin.getContexts()` on this client is caller-scoped through the request\n * proof — it answers this ACCOUNT's own contexts, each naming its\n * application — so the id is derivable from the credential already held.\n *\n * Not persisted with `setApplicationId`: it is derived from a cheap,\n * authoritative read, so caching it would only create a value to invalidate\n * when the account's contexts change.\n */\n let active = true;\n const stop = new AbortController();\n (async () => {\n // No relay, so no client and nothing to ask. A brand-new account is a\n // member of nothing — there are no contexts to derive an application from,\n // which is exactly the state an invitation changes.\n if (!client || !relayUrl) return;\n // Admin reads and events need a session the relay accepts, which needs\n // its node key. Pinned, or learned from the relay's attestation; learned\n // now, the client is rebuilt so its session and events use it too. With\n // neither, a hosted relay answers the proof-only path with 401: do not ask.\n //\n // Learning it can fail on the way — the release mirror timing out, the\n // relay not answering — and one such failure used to leave the whole\n // session unsigned: every read a 401 until a reload. So it is waited out,\n // with backoff, and the client stays unpublished (and the session\n // loading) meanwhile: handing the app a client now would only send its\n // reads unsigned, to be refused as if the account had no access.\n if (awaitingKey) {\n const nodeKey = await learnRelayNodeKey(relayUrl, { signal: stop.signal });\n if (!active) return;\n // `null` here is a refusal: the relay's quote did not verify, and asking\n // again would get the same answer. The client still writes (intents\n // carry their own warrant); only admin reads and events need the\n // session a verified key enables, and those stay off.\n setMero(nodeKey ? (buildDelegatedClient(routed, contextId) ?? client) : client);\n setIsLoading(false);\n if (!nodeKey) return;\n }\n // The app names its application by `packageName`, and that decides. The\n // account's contexts do not: one account is used across apps, so a\n // kv-store tab may well see chess's contexts — two applications, or only\n // another app's. Reading the id off them would leave it null when several\n // appear and, worse, point this app at another's contract when exactly\n // one foreign one does (founding a namespace signs `TargetApplicationSet`\n // with that id). The id is a pure function of the package and its\n // publisher's signing key (core's `ApplicationId::for_bundle`), both of\n // which the registry lists, so it is derived from there — also for a\n // brand-new account with no contexts, which has to found its first\n // namespace from somewhere. Should the registry not answer, warn once and\n // fall back to the contexts below, so an app without registry access\n // keeps working as before.\n if (packageName) {\n try {\n const { applicationId: derived } = await resolveApplicationIdFromRegistry(\n registryUrl ?? DEFAULT_REGISTRY_URL,\n packageName,\n );\n if (!active) return;\n setApplicationIdState(derived);\n return;\n } catch (e) {\n // Once: a registry that did not answer is not asked again until the\n // session or its chosen context changes.\n console.warn(`[mero-react] could not learn the application id of ${packageName} from the registry`, e);\n if (!active) return;\n }\n }\n try {\n // Without a `packageName` (or with a registry that did not answer), the\n // contexts are the only thing that names an application. Across every\n // relay this account uses, each answering for itself.\n const contexts = await listDelegatedContexts(delegated);\n if (!active) return;\n const apps = [\n ...new Set((contexts ?? []).map((c) => c.applicationId).filter(Boolean)),\n ];\n if (apps.length === 1) {\n setApplicationIdState(apps[0]);\n }\n // More than one, and this stays null ON PURPOSE — only without a\n // `packageName`, which would have decided above. A tab holds one\n // application's UI and nothing here says which — the account simply has\n // contexts for several. Picking the first would silently point the app at\n // another app's contract, which answers none of its methods; admitting\n // \"I don't know\" leaves the app's own \"waiting for this session to report\n // which application\" message honest, and a chooser is the follow-up.\n // Zero contexts and no `packageName`: nothing to derive from, null too.\n } catch {\n // Left null, and deliberately not surfaced as a connection failure. The\n // writes work — every one carries its own warrant — and a read that did\n // not answer must not unwind a connection that did.\n }\n })();\n\n return () => {\n active = false;\n stop.abort();\n // `close` is a node-client concern; a relay client has nothing to tear\n // down, so do not reach for it.\n };\n }, [delegated, contextId, packageName, registryUrl]);\n\n // Initialization effect\n useEffect(() => {\n // A delegated tab is already connected by the effect above. This whole\n // path — callback parsing, token adoption, node-URL trust, /auth/validate —\n // describes a session the delegated client does not have.\n if (delegated) return;\n\n let active = true;\n\n const init = async () => {\n const callback = callbackRef.current;\n let nodeFromCallback: string | null = null;\n let instance: MeroJs | null = null;\n\n if (callback) {\n // Read BEFORE the callback overwrites either of them.\n // - initiatedNodeUrl: the node login was initiated with — the trust anchor.\n // - tokenNodeUrl: the node that minted the bundle currently in the store.\n // They differ exactly when the user is switching nodes: `connectToNode`\n // points NODE_URL at the *target* node before redirecting, while the store\n // still holds the *previous* node's bundle. Falling back to the initiated\n // node keeps sessions that predate TOKEN_NODE_URL working.\n const initiatedNodeUrl = getNodeUrl();\n const tokenNodeUrl = getTokenNodeUrl() ?? initiatedNodeUrl;\n\n // The callback URL is attacker-influenceable, so validate its node_url\n // BEFORE storing tokens or connecting — otherwise a malicious node_url\n // would receive the freshly-minted tokens (exfiltration).\n const { url, rejected } = resolveTrustedNodeUrl({\n candidate: callback.nodeUrl,\n initiated: initiatedNodeUrl,\n allowedNodeUrls,\n });\n\n // Always strip the callback params (tokens + node_url) from the address\n // bar and consume the parsed callback, whatever the trust outcome.\n if (isBrowser) {\n window.history.replaceState({}, '', window.location.pathname + window.location.search);\n }\n callbackRef.current = null;\n\n if (rejected) {\n // Untrusted node_url — likely a token-exfiltration attempt. Drop the\n // callback's tokens, but DON'T return: fall through to restore any\n // existing session from storage so a tampered callback can't log a\n // legitimately authenticated user out.\n console.error(\n '[MeroProvider] OAuth callback node_url is not trusted (it does not match the node ' +\n 'login was initiated with, nor `allowedNodeUrls`). Ignoring the callback; no tokens stored.',\n );\n } else if (url) {\n // Trusted node → the callback's tokens MAY be persisted. Whether they\n // SHOULD be is a separate question: refresh tokens are single-use since\n // core 0.11.0 (calimero-network/core#3083), so blindly writing the hash\n // bundle over a bundle mero-js has already rotated resurrects a consumed\n // refresh token — the node reads that as theft (`x-auth-error:\n // token_reuse`) and revokes the entire token family, hard-logging out\n // every holder. Adopt only a fresh, newer, or different-node bundle, and\n // merge rather than replace so an access-only hash (hosts are dropping\n // `refresh_token` from the hash) can never strip a live refresh token.\n // Written through the client, which binds the bundle to its node.\n instance = createMeroInstance(url);\n const decision = resolveTokenAdoption({\n callbackAccessToken: callback.accessToken,\n callbackRefreshToken: callback.refreshToken,\n callbackNodeUrl: url,\n stored: instance.getTokenData(),\n storedNodeUrl: tokenNodeUrl,\n });\n\n if (decision.adopt) {\n instance.setTokenData(decision.tokens);\n setTokenNodeUrl(url);\n } else {\n console.warn(\n '[MeroProvider] Ignoring the SSO callback token bundle: it is stale (not newer than ' +\n 'the tokens already stored for this node). Adopting it would replay an already-rotated ' +\n 'refresh token, which the node revokes the whole token family for.',\n );\n }\n\n if (callback.applicationId) {\n setApplicationId(callback.applicationId);\n if (active) setApplicationIdState(callback.applicationId);\n }\n if (callback.contextId) {\n setContextId(callback.contextId);\n if (active) setContextIdState(callback.contextId);\n }\n if (callback.contextIdentity) {\n setContextIdentity(callback.contextIdentity);\n if (active) setContextIdentityState(callback.contextIdentity);\n }\n\n setNodeUrl(url);\n if (active) setNodeUrlState(url);\n nodeFromCallback = url;\n }\n // url === null && !rejected → callback had no node to bind to; ignore it.\n }\n\n const savedUrl = nodeFromCallback || getNodeUrl();\n if (!savedUrl) {\n if (active) setIsLoading(false);\n return;\n }\n\n instance ??= createMeroInstance(savedUrl);\n const authed = await checkAuth(instance);\n\n if (!active) return;\n\n if (authed) {\n setMero(instance);\n setIsAuthenticated(true);\n setIsOnline(true);\n } else if (nodeFromCallback) {\n setMero(instance);\n }\n\n setIsLoading(false);\n };\n\n init().catch((err) => {\n console.error('[MeroProvider] Initialization failed:', err);\n if (active) setIsLoading(false);\n });\n\n return () => {\n active = false;\n };\n }, [createMeroInstance, checkAuth, allowedNodeUrls, delegated]);\n\n // SSE connection for online/offline detection — no polling.\n useEffect(() => {\n if (!isAuthenticated || !meroRef.current) return;\n\n let active = true;\n const sse = meroRef.current.events;\n\n const onConnect = () => { if (active) setIsOnline(true); };\n const onError = (err: Error) => {\n if (!active) return;\n setIsOnline(false);\n\n // A delegated stream has no token to renew. It is authenticated by a\n // request proof the device key signs for each connect, so a 401 here is\n // not an expiry the recovery below can fix — and that recovery ends in\n // `logout()`, which would tear down a connection whose credential is\n // still perfectly good. Report offline and let the client reconnect.\n if (delegated) return;\n\n // ── Which stream failures are worth acting on ──────────────────────────\n //\n // This used to be `if (!err.message.includes('401')) return;`, and the\n // comment under it explained that mero-js threw a bare\n // `SSE connection failed: <status>`, so nothing better was available.\n // That stopped being true in mero-js 19.14.1 (#166): the SSE path now\n // throws the same typed errors the request path does, carrying the\n // status and the `x-auth-error` header.\n //\n // Matching on '401' was not merely coarse, it was aimed at the wrong\n // number. Core answers a dead or under-scoped token on `/sse` with\n // **403**, not 401 — `token_expired` is the only 401 a stream sees. So\n // every failure that actually needed acting on was the one this gate\n // dropped, and the app sat at `isOnline = false` with no way back and no\n // prompt to log in again.\n //\n // Three cases now, because they need three different answers.\n\n // 1. The token family is gone (403 `token_revoked`, or a 401\n // `token_reuse`). mero-js has already STOPPED reconnecting — every\n // retry re-sends the same dead credential — so nothing will reopen\n // this stream, and there is no refresh token left to spend either.\n if (err instanceof AuthRevokedError) {\n logout();\n return;\n }\n\n if (err instanceof HTTPError && err.status === 403) {\n // 2. The token is live but was minted without `context:subscribe`.\n // Core requires that grant for `/sse`, `/sse/subscription` and\n // `/ws`, and the grant set is baked in at MINT time — so a refresh\n // re-issues the same unusable token and the stream 403s again,\n // forever. mero-react 9.1.2 (#73) fixed what we ASK for; a client\n // key minted before it can only be replaced by a fresh login.\n // `checkAuth` would return true here and reconnect us into that\n // loop, which is why this case must not go through it.\n if (err.headers?.get('x-auth-error') === 'permission_denied') {\n console.warn(\n '[MeroProvider] This session cannot open an event stream ' +\n '(403 permission_denied): its token predates the context:subscribe ' +\n 'grant. Logging out — a fresh login mints a key that can subscribe.',\n );\n logout();\n return;\n }\n // 3. Any other 403 is core refusing this caller for a reason a new\n // token would not change — \"Forbidden: not the session owner\". Not\n // an auth-token problem, so do not spend the session on it.\n return;\n }\n\n // A 401 is NOT proof the session is over, and it used to be treated as\n // such: `logout()` wipes the token store, so an expired access token cost\n // the user their still-valid 30-day refresh token and forced a real\n // re-login.\n //\n // The stream authenticates only at connect time (an open stream survives\n // expiry), so this fires on the first reconnect after the access token\n // ages out — a sleep/wake, a network blip, a PWA resume, a node restart.\n // Routine events, all of them. Ask `checkAuth`, which recovers a\n // merely-expired token via the transport's refresh and returns false only\n // when the session is genuinely dead.\n //\n // The string check stays as a fallback: not every caller is on 19.14.1,\n // and an older mero-js still reports this as `SSE connection failed: 401`.\n const status = err instanceof HTTPError ? err.status : null;\n if (status !== 401 && !err.message.includes('401')) return;\n\n if (recoveringRef.current) return;\n recoveringRef.current = true;\n void (async () => {\n try {\n const instance = meroRef.current;\n if (!instance) return;\n if (await checkAuth(instance)) {\n // Renewed. mero-js's `onTokenRefresh` hook has already updated the\n // instance's in-memory token, so the SseClient's `getAuthToken`\n // hands the reconnect the new one.\n if (active) await instance.events.connect().catch(() => {});\n return;\n }\n if (active) logout();\n } finally {\n recoveringRef.current = false;\n }\n })();\n };\n\n sse.on('connect', onConnect);\n sse.on('error', onError);\n sse.connect().catch(() => { if (active) setIsOnline(false); });\n\n return () => {\n active = false;\n sse.off('connect', onConnect);\n sse.off('error', onError);\n };\n // `checkAuth` and `logout` are both useCallback-stable (`logout` closes over\n // the memoized `tokenStore`), so listing them does not re-subscribe the stream.\n // Not for a delegated client: this stream is opened from the node client's\n // own `events`, and a relay client observes only when it was given the\n // relay's node key — which `buildDelegatedClient` wires up itself.\n }, [isAuthenticated, mero, checkAuth, logout, delegated]);\n\n // The admin API an app writes against, whatever the session, with the same\n // calls and results on both: on a node, the node's client (installing the\n // app when a namespace needs it); on an account, the account admin, whose\n // reads go to the relay and whose writes go through it as delegated ops.\n // Never null for a signed-in account: one with no relay yet is a member of\n // nothing, and says so, rather than leaving the app to special-case it.\n const admin = useMemo<AdminApiClient | null>(() => {\n const app = { packageName, packageVersion, registryUrl };\n if (delegated !== null) {\n // No relay at all: the empty admin. A relay still being connected to (its\n // node key not learned yet) is loading, not empty — null until it is up.\n // `admin.joinNamespace` redeems for the account, relay or not: the join is\n // how it gets one, and the session moves onto that relay once it is in.\n const deps = {\n join: (namespaceId: string, invitation: Parameters<typeof joinAsAccount>[2]) =>\n joinAsAccount(delegated, namespaceId, invitation, { cloudBaseUrl, onJoined: connectWithAccount }),\n // Founding enables HA on the same cloud the joins resolve relays from.\n found: (session: Parameters<typeof foundDelegatedNamespace>[0], req: Parameters<typeof foundDelegatedNamespace>[1]) =>\n foundDelegatedNamespace(session, req, { cloudBaseUrl }),\n // Invitations are checked against the routing their claimants will use.\n routing: (namespaceId: string) =>\n new CloudClient({\n cloudBaseUrl,\n routingCredential: { credential: delegated.credential, deviceSecret: delegated.deviceSecret },\n }).getNamespaceRouting(namespaceId),\n };\n if (delegated.relayUrl === null) return createAccountAdmin({ session: delegated, read: null, app }, deps);\n if (!mero) return null;\n return createAccountAdmin(\n { session: delegated, read: (mero as unknown as { admin: AdminApiClient }).admin, app },\n deps,\n );\n }\n const nodeAdmin = (mero as { admin?: AdminApiClient } | null)?.admin;\n return nodeAdmin ? createNodeAdmin({ admin: nodeAdmin, app }) : null;\n }, [mero, delegated, packageName, packageVersion, registryUrl, cloudBaseUrl, connectWithAccount]);\n\n const contextValue = useMemo<MeroContextValue>(\n () => ({\n mero,\n isAuthenticated,\n isOnline,\n nodeUrl,\n applicationId,\n contextId,\n contextIdentity,\n connectToNode,\n connectWithAccount,\n isDelegated: delegated !== null,\n admin,\n can: delegated !== null\n // An account founds a namespace through its relay and gives it this\n // app's application (core#4269), possible only when the app names its\n // registry package, and signs its own invitations (mero-js #221). Only\n // upgrades stay a node's: just a group's first application choice can\n // go through a relay.\n ? { createNamespace: Boolean(packageName), createContext: true, invite: true, upgrade: false }\n : { createNamespace: true, createContext: true, invite: true, upgrade: true },\n app: { packageName, packageVersion, registryUrl },\n cloudBaseUrl,\n logout,\n isLoading,\n }),\n [mero, admin, isAuthenticated, isOnline, nodeUrl, applicationId, contextId, contextIdentity, connectToNode, connectWithAccount, delegated, logout, isLoading, packageName, packageVersion, registryUrl, cloudBaseUrl],\n );\n\n return (\n <MeroContext.Provider value={contextValue}>\n {children}\n </MeroContext.Provider>\n );\n}\n\nexport function useMero(): MeroContextValue {\n const context = useContext(MeroContext);\n if (!context) {\n throw new Error('useMero must be used within a MeroProvider');\n }\n return context;\n}\n\nexport { MeroContext };\n","/**\n * CalimeroLogo - the official Calimero emblem.\n *\n * Uses `currentColor` for fills so the consumer can theme it with `color`,\n * a `style.color` override, or by passing `color` directly.\n */\n\nimport React from 'react';\n\nexport interface CalimeroLogoProps extends React.SVGAttributes<SVGSVGElement> {\n /** Width / height shorthand (applied to both). Default: 24. */\n size?: number | string;\n}\n\nexport function CalimeroLogo({\n size = 24,\n color,\n style,\n ...rest\n}: CalimeroLogoProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 193 193\"\n fill={color ?? 'currentColor'}\n style={style}\n xmlns=\"http://www.w3.org/2000/svg\"\n aria-hidden=\"true\"\n {...rest}\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M13.5969 23.2235C63.4924 -4.81833 123.53 2.55678 148.374 10.0273C153.006 11.4201 155.606 16.2198 154.181 20.7478C152.757 25.2758 147.846 27.8173 143.214 26.4245C120.866 19.7045 66.3988 13.3369 22.3442 38.0961C21.3748 38.6409 20.8298 39.6384 20.8808 40.6778C22.5544 74.7376 40.6646 139.735 103.059 173.709C107.293 176.015 108.813 181.238 106.455 185.377C104.096 189.516 98.7523 191.002 94.5186 188.696C24.7767 150.721 5.18199 78.7606 3.35124 41.5008C2.98177 33.9812 6.96683 26.9496 13.5969 23.2235Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M180.214 22.5271C185.054 22.2785 189.183 25.9121 189.437 30.6429C192.776 92.7591 159.782 138.316 138.517 157.587C133.185 162.419 125.221 164.303 117.934 161.241C102.817 154.887 88.1835 141.52 76.3001 128.189C64.2403 114.66 54.1712 100.2 48.3006 90.492C45.8345 86.4139 47.2173 81.1537 51.3891 78.743C55.561 76.3323 60.9421 77.684 63.4082 81.7621C68.803 90.6832 78.2588 104.272 89.5315 116.919C100.981 129.763 113.488 140.698 124.866 145.48C125.179 145.612 125.851 145.671 126.586 145.006C145.206 128.132 174.903 87.1988 171.912 31.5431C171.657 26.8122 175.374 22.7756 180.214 22.5271Z\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M85.9137 55.4487C70.263 57.0264 57.2007 60.7039 50.4014 63.4262C45.9168 65.2218 40.7922 63.1236 38.9553 58.7397C37.1184 54.3559 39.2649 49.3464 43.7495 47.5508C52.2083 44.164 66.9167 40.1173 84.1135 38.3837C101.323 36.649 121.62 37.1693 140.947 43.4423C149.244 46.1351 155.088 53.9217 154.482 62.8728C153.225 81.429 144.514 100.403 127.158 122.145C124.177 125.88 118.663 126.546 114.842 123.631C111.021 120.717 110.341 115.327 113.322 111.592C129.481 91.3484 136.032 75.6017 136.971 61.7394C137.02 61.0029 136.547 60.0904 135.417 59.7238C119.18 54.4537 101.552 53.8722 85.9137 55.4487Z\"\n />\n </svg>\n );\n}\n\nexport default CalimeroLogo;\n","/**\n * Theme tokens for mero-react components.\n *\n * Defaults match the green palette used across Calimero apps (admin-dashboard,\n * tauri-app, app-registry). Pass a partial `MeroTheme` to `ConnectButton` or\n * `LoginModal` to override any token.\n */\n\nimport type { CSSProperties } from 'react';\n\nexport interface MeroTheme {\n /** Primary accent / CTA color */\n primary?: string;\n /** Primary accent on hover */\n primaryHover?: string;\n /** Text color rendered on top of `primary` (e.g. inside the Connect button when connected) */\n primaryText?: string;\n /** Main surface color (modal background, button background) */\n background?: string;\n /** Secondary surface color (input fields, info chips) */\n backgroundSecondary?: string;\n /** Tertiary surface color (subtle elevation) */\n backgroundTertiary?: string;\n /** Border color */\n border?: string;\n /** Primary text color */\n text?: string;\n /** Muted / secondary text color */\n textSecondary?: string;\n /** Error / danger color */\n error?: string;\n /** Modal backdrop color */\n overlay?: string;\n /** Border radius (any CSS length) */\n radius?: string;\n}\n\nexport type ResolvedMeroTheme = Required<MeroTheme>;\n\nexport const defaultMeroTheme: Readonly<ResolvedMeroTheme> = Object.freeze({\n primary: '#a5ff11',\n primaryHover: '#8ed40d',\n primaryText: '#0d1117',\n background: '#0d1117',\n backgroundSecondary: '#161b22',\n backgroundTertiary: '#1c2128',\n border: '#30363d',\n text: '#e6edf3',\n textSecondary: '#8b949e',\n error: '#ff6b6b',\n overlay: 'rgba(0, 0, 0, 0.75)',\n radius: '8px',\n});\n\n/**\n * Merge a partial theme with the defaults.\n *\n * Filtering rules — values that fall back to the default:\n * - `undefined` (the prop key wasn't set, or was set to `undefined`)\n * - empty string `''`\n * - whitespace-only strings (e.g. `' '`)\n *\n * These are dropped because they're invalid CSS and would produce\n * invisible elements (transparent backgrounds, missing borders, etc.).\n * If you genuinely want the browser default for a token, omit the key\n * from the theme prop rather than passing an empty string.\n *\n * Any other non-empty string is forwarded as-is — CSS syntax itself\n * is NOT validated.\n */\nexport function resolveMeroTheme(theme?: MeroTheme): ResolvedMeroTheme {\n if (!theme) return { ...defaultMeroTheme };\n const filtered = Object.fromEntries(\n Object.entries(theme).filter(\n ([, v]) => v !== undefined && typeof v === 'string' && v.trim() !== '',\n ),\n ) as Partial<MeroTheme>;\n return { ...defaultMeroTheme, ...filtered };\n}\n\n/**\n * Single source of truth mapping each `MeroTheme` token name to the CSS\n * custom-property name it surfaces as. Used by `themeToCssVars` to emit the\n * inline-style map and by component code (e.g. `LoginModal`) to read the\n * variable in inline styles via `var(--mero-*, fallback)`.\n *\n * Adding a new token? Add it here, in `MeroTheme`, and in `defaultMeroTheme`,\n * and the rest of the system picks it up automatically.\n */\nexport const MERO_CSS_VARS: Record<keyof MeroTheme, string> = {\n background: '--mero-bg',\n backgroundSecondary: '--mero-bg-secondary',\n backgroundTertiary: '--mero-bg-tertiary',\n text: '--mero-text',\n textSecondary: '--mero-text-secondary',\n primary: '--mero-accent',\n primaryHover: '--mero-accent-hover',\n primaryText: '--mero-on-primary',\n border: '--mero-border',\n error: '--mero-error',\n overlay: '--mero-overlay',\n radius: '--mero-radius',\n};\n\n/**\n * Build a `style` object that exposes a resolved theme as CSS variables, so\n * descendant CSS rules (e.g. those in `styles.css`) pick up the overrides.\n */\nexport function themeToCssVars(theme: ResolvedMeroTheme): CSSProperties {\n const vars: Record<string, string> = {};\n for (const key of Object.keys(MERO_CSS_VARS) as Array<keyof MeroTheme>) {\n vars[MERO_CSS_VARS[key]] = theme[key];\n }\n return vars as CSSProperties;\n}\n\n/**\n * Returns a `var(--mero-*, fallback)` reference for a theme token, suitable\n * for inline styles in portal-rendered components where descendant CSS\n * variables also need to support global `:root` overrides.\n */\nexport function cssVar(theme: ResolvedMeroTheme, key: keyof MeroTheme): string {\n return `var(${MERO_CSS_VARS[key]}, ${theme[key]})`;\n}\n","/**\n * AccountSignInPanel — the Cloud tab of the connect dialog.\n *\n * Presentational only: the button, what pressing it does, and whatever the last\n * enrolment had to say. The flow itself is {@link useAccountEnrolment}; this\n * renders its outputs, so it can sit inside `LoginModal` without the modal\n * knowing anything about device keys or wallets.\n *\n * The copy is `ConnectButtonAccount`'s, unchanged.\n */\n\nimport { useMemo } from 'react';\nimport { cssVar, resolveMeroTheme, type MeroTheme } from '../theme';\n\nexport interface AccountSignInPanelProps {\n /** Start enrolment — normally `useAccountEnrolment().goToWallet`. */\n onEnrol: () => void;\n /** What the last enrolment had to say (an error, or \"nowhere to write yet\"). */\n note?: string | null;\n /** The wallet enrolment goes to. Shown only when `customWallet`. */\n walletUrl?: string;\n /** Whether `walletUrl` is an override rather than the hosted wallet. */\n customWallet?: boolean;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n}\n\nexport function AccountSignInPanel({\n onEnrol,\n note,\n walletUrl,\n customWallet = false,\n theme,\n}: AccountSignInPanelProps) {\n // Same tokens as LoginModal: `var(--mero-*, fallback)`, so the panel follows\n // the modal's inline variables and any global `:root` overrides.\n const styles = useMemo(() => {\n const t = resolveMeroTheme(theme);\n const radius = cssVar(t, 'radius');\n const error = cssVar(t, 'error');\n return {\n root: { display: 'flex', flexDirection: 'column' as const, gap: '1rem' },\n info: {\n color: cssVar(t, 'textSecondary'),\n textAlign: 'center' as const,\n fontSize: '0.875rem',\n margin: 0,\n },\n hint: {\n color: cssVar(t, 'textSecondary'),\n textAlign: 'center' as const,\n fontSize: '0.8125rem',\n margin: 0,\n opacity: 0.8,\n overflowWrap: 'anywhere' as const,\n },\n note: {\n color: error,\n backgroundColor: `color-mix(in srgb, ${error} 10%, transparent)`,\n border: `1px solid color-mix(in srgb, ${error} 30%, transparent)`,\n borderRadius: radius,\n padding: '0.75rem',\n fontSize: '0.875rem',\n textAlign: 'center' as const,\n margin: 0,\n },\n buttonGroup: { display: 'flex', justifyContent: 'center' },\n button: {\n padding: '0.75rem 2rem',\n borderRadius: radius,\n border: 'none',\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n backgroundColor: cssVar(t, 'primary'),\n color: cssVar(t, 'primaryText'),\n transition: 'all 0.15s ease',\n },\n };\n }, [theme]);\n\n return (\n <div\n className=\"mero-login-account\"\n style={styles.root}\n data-testid=\"account-sign-in-panel\"\n >\n {note && (\n <p\n className=\"mero-login-note\"\n style={styles.note}\n role=\"status\"\n data-testid=\"account-note\"\n >\n {note}\n </p>\n )}\n <p className=\"mero-login-info\" style={styles.info}>\n You will approve a device key on the wallet&apos;s own page, then come\n back here. The relay never sees your account root — only the\n certificate it signed.\n </p>\n <p className=\"mero-login-info\" style={styles.info}>\n That one certificate is all of it: finding the relay that serves your\n account, writing through it, reading your own contexts and namespaces,\n and live events. Nothing to paste in.\n </p>\n <div className=\"mero-login-actions\" style={styles.buttonGroup}>\n <button\n type=\"button\"\n className=\"mero-login-button mero-login-primary\"\n style={styles.button}\n onClick={onEnrol}\n data-testid=\"enrol-button\"\n >\n Enrol with your account\n </button>\n </div>\n {customWallet && walletUrl && (\n /* Shown only when an app overrode it, so a local rig can see at a\n glance that it is not enrolling against the hosted wallet. */\n <p className=\"mero-login-hint\" style={styles.hint}>\n Enrolling at <code>{walletUrl}</code>, not the hosted wallet.\n </p>\n )}\n </div>\n );\n}\n\nexport default AccountSignInPanel;\n","/**\n * useAccountEnrolment — the account sign-in flow, with no UI.\n *\n * Moved out of {@link ConnectButtonAccount} unchanged, so that `ConnectButton`'s\n * Cloud tab and `ConnectButtonAccount` share one copy of it: the device keys,\n * the redirect to the wallet, and the completion when the tab comes back.\n *\n * - `goToWallet` generates (or reuses) this tab's device keys, remembers a state\n * parameter, and leaves for the wallet.\n * - On the way back, the callback is read ONCE during render, the state is\n * checked against the one sent, the certificate is completed and saved, the\n * account's relays are looked up, and `connectWithAccount` connects.\n * - `note` is what the person should be told about that — an error, or a\n * connection with nowhere to write yet.\n * - `returning` is true when this page load carries an enrolment callback,\n * success or error, so a caller can show the place the note appears.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n CloudClient,\n completeDeviceEnrolment,\n deviceEnrolmentUrl,\n readEnrolmentCallback,\n type CloudAccountRelay,\n type DeviceEnrolmentCallback,\n} from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { saveDelegatedCredential } from '@calimero-network/mero-js';\n\n/** Where this tab's device keypair lives. */\nconst DEVICE_KEY = 'calimero.device';\n/** The state parameter this tab sent to the wallet, to check what comes back. */\nconst STATE_KEY = 'calimero.enrol.state';\n\n/**\n * The hosted wallet, which is a property of the platform rather than of any app.\n *\n * A default here and not a required prop: every app that enrols an account\n * enrols it at the same wallet, so making each one name it would be asking a\n * question with one answer — and an app that got it wrong would send a device key\n * to the wrong origin.\n */\nconst HOSTED_WALLET = 'https://wallet.cloud.calimero.network/account-enroll';\n\nconst hex = (b: ArrayBuffer | Uint8Array): string =>\n [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, '0')).join('');\n\n/**\n * The relay's own account, as the cloud names it beside the relay — the\n * executor a founding warrant must name.\n *\n * It is what lets a brand-new account found a namespace on the relay the cloud\n * just assigned it, with nothing typed in: a namespace that does not exist yet\n * cannot be asked who its relay is, and the account is a member of nothing that\n * could tell it. A server that does not name one (older ones omit the field)\n * leaves it `null`, and founding falls back to learning it from a namespace the\n * account is already in, as before.\n *\n * Read defensively, so this builds against a mero-js whose `CloudAccountRelay`\n * does not declare the field yet; mero-js already drops anything that is not\n * 64 lowercase hex, and this re-checks it rather than trusting the type.\n */\nfunction executorOf(relay: CloudAccountRelay): string | null {\n const value = (relay as { executorAccount?: unknown }).executorAccount;\n return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) ? value : null;\n}\n\n/**\n * Which of the account's relays to talk to, and what to say about it.\n *\n * Four outcomes, and the connection is made in ALL of them — what differs is\n * whether there is somewhere to write yet, and what the person is told:\n *\n * - a **fresh** relay with an address: use it, say nothing;\n * - only **stale** ones: use one anyway — the cloud reports `fresh` from a\n * heartbeat, and a heartbeat that lapsed a minute ago is not the same claim as\n * a node that is gone — but say so, because if the writes then fail this is\n * why;\n * - **rows with no address**: relays are assigned and the cloud has no URL for\n * any of them yet, which is the shape a node reports before its first\n * heartbeat lands. A wait.\n * - **no rows at all**: the normal state of a brand-new account. It is a member\n * of nothing, so nothing serves it.\n *\n * ## Why the last two connect instead of refusing\n *\n * This used to return \"not connected\" for both, and that was wrong in the case\n * it mattered most: you get invited *because* you are signed in, and accepting\n * an invitation is what earns a relay. Refusing to log the account in until it\n * had one locked a new account out of the only path that would give it one.\n *\n * Nothing is faked to achieve it. The session carries `relayUrl: null`, so no\n * client is built, `mero` stays `null`, and a write is told the relay is\n * missing rather than being sent to a guess.\n *\n * A current cloud assigns a relay to an account that has none on this very\n * read, so \"no rows at all\" is now mostly an older server's answer. The chosen\n * relay's `executorAccount` comes back with it, so the session can found a\n * namespace there straight away.\n */\nfunction chooseRelay(relays: readonly CloudAccountRelay[]): {\n relayUrl: string | null;\n executorAccount: string | null;\n note: string | null;\n} {\n const reachable = relays.filter(\n (r): r is CloudAccountRelay & { relayUrl: string } => typeof r.relayUrl === 'string' && r.relayUrl.length > 0,\n );\n const fresh = reachable.find((r) => r.fresh);\n if (fresh) return { relayUrl: fresh.relayUrl, executorAccount: executorOf(fresh), note: null };\n if (reachable.length > 0) {\n return {\n relayUrl: reachable[0].relayUrl,\n executorAccount: executorOf(reachable[0]),\n note:\n 'Connected through a relay whose last heartbeat has lapsed — it may not answer. It was ' +\n 'the only one with an address.',\n };\n }\n if (relays.length > 0) {\n return {\n relayUrl: null,\n executorAccount: null,\n note:\n `Signed in. Your account has ${relays.length} relay${relays.length === 1 ? '' : 's'} ` +\n 'assigned, but the cloud knows no address for any of them yet, so there is nowhere to ' +\n 'write through for the moment. Reads and writes resume as soon as one reports in.',\n };\n }\n return {\n relayUrl: null,\n executorAccount: null,\n note:\n 'Signed in, with nowhere to write yet: a new account is a member of nothing, so no node ' +\n 'serves it. Redeeming an invitation admits this account to a namespace and gives it a ' +\n 'relay — that is the normal first step, not an error.',\n };\n}\n\ninterface DeviceKeys {\n /** Ed25519 public key — what the certificate names, and what signs. */\n signPk: string;\n /** Ed25519 secret, hex seed. Signs warrants and the login statement. */\n signSk: string;\n /** X25519 public key — where wrapped scope keys are delivered. */\n kemPk: string;\n /** X25519 secret. Without it, anything delivered to `kemPk` is unreadable. */\n kemSk: string;\n}\n\n/**\n * This tab's device keys, generated once.\n *\n * TWO keypairs, for two jobs the `DeviceCert` names separately: an Ed25519 pair\n * that signs, and an X25519 pair that receives. Both halves of both are kept —\n * a public key certified without its private half is a key nothing can ever use.\n *\n * In `localStorage`, not session: they have to survive the redirect to the\n * wallet and back. A key regenerated on the way home would not match the\n * certificate the wallet just minted, and `completeDeviceEnrolment` would\n * rightly refuse it.\n */\nasync function deviceKeys(): Promise<DeviceKeys> {\n const had = localStorage.getItem(DEVICE_KEY);\n if (had) {\n const parsed = JSON.parse(had) as Partial<DeviceKeys>;\n // Keys minted before the agreement pair was real carry 32 random bytes as\n // `kemPk` and no `kemSk`. They cannot receive a wrapped scope key, ever, so\n // they are discarded rather than carried forward — the cost is re-enrolling\n // this device, which is cheap; the cost of keeping them is a delivery that\n // silently cannot be decrypted.\n if (parsed.kemSk && parsed.signSk && parsed.signPk && parsed.kemPk) {\n return parsed as DeviceKeys;\n }\n localStorage.removeItem(DEVICE_KEY);\n }\n\n const sign = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [\n 'sign',\n 'verify',\n ])) as CryptoKeyPair;\n\n let agree: CryptoKeyPair;\n try {\n agree = (await crypto.subtle.generateKey({ name: 'X25519' }, true, [\n 'deriveBits',\n ])) as CryptoKeyPair;\n } catch {\n // Better to refuse than to certify a delivery key with no private half:\n // enrolment would appear to succeed and the failure would surface much\n // later, as an undecryptable scope key.\n throw new Error(\n 'this browser cannot generate an X25519 key, so it cannot receive wrapped ' +\n 'scope keys. Chrome 133+ and Safari 17+ support it; enrolling without one ' +\n 'would certify a delivery key nothing holds the secret for.',\n );\n }\n\n // pkcs8 wraps the 32-byte seed behind a 16-byte header, for both curves.\n const keys: DeviceKeys = {\n signPk: hex(await crypto.subtle.exportKey('raw', sign.publicKey)),\n signSk: hex((await crypto.subtle.exportKey('pkcs8', sign.privateKey)).slice(16)),\n kemPk: hex(await crypto.subtle.exportKey('raw', agree.publicKey)),\n kemSk: hex((await crypto.subtle.exportKey('pkcs8', agree.privateKey)).slice(16)),\n };\n localStorage.setItem(DEVICE_KEY, JSON.stringify(keys));\n return keys;\n}\n\n\n/**\n * Whether this page load is the one coming back from the wallet — a completed\n * enrolment or a declined one — WITHOUT consuming it.\n *\n * `useAccountEnrolment` reads the callback once and strips it from the address\n * bar, so a second reader finds nothing. That makes `returning` from the hook\n * unusable for the one decision that has to be taken before the hook runs: a\n * component that owns `LoginModal`'s `isOpen` and wants the dialog open on the\n * way back. This is the answer for it, as a `useState` initialiser:\n *\n * ```tsx\n * const [open, setOpen] = useState(isReturningFromWallet);\n * <LoginModal isOpen={open} ... /> // sources its own Cloud tab, lands on it\n * ```\n *\n * The parent's initialiser runs before the modal's hook reads the fragment, so\n * the two agree. `ConnectButton` needs none of this: it owns both.\n */\nexport function isReturningFromWallet(\n location: { hash: string } | undefined = typeof window === 'undefined' ? undefined : window.location,\n): boolean {\n if (!location) return false;\n const params = new URLSearchParams(location.hash.replace(/^#/, ''));\n if (params.get('error')) return true;\n return Boolean(params.get('credential') && params.get('account') && params.get('device'));\n}\n\nexport interface UseAccountEnrolmentOptions {\n /**\n * Point enrolment at a wallet other than the hosted one.\n *\n * Exists for working ON the wallet: a wallet served from `localhost:8090`\n * cannot be reached through the hosted URL, and without this the only way to\n * test a wallet change would be to deploy it.\n */\n walletUrl?: string;\n /**\n * When false, the hook reads no callback and completes nothing, so a\n * component that has the account path switched off leaves the fragment for\n * whichever component does handle it. Default true.\n */\n enabled?: boolean;\n}\n\nexport interface AccountEnrolment {\n /** Leave for the wallet to enrol this tab's device key. */\n goToWallet: () => Promise<void>;\n /** What to tell the person about the last enrolment, or null. */\n note: string | null;\n /** Whether this page load carries an enrolment callback (success or error). */\n returning: boolean;\n /** The wallet enrolment goes to: the override, else the hosted one. */\n walletUrl: string;\n /** Whether `walletUrl` is an override rather than the hosted wallet. */\n customWallet: boolean;\n}\n\nexport function useAccountEnrolment({\n walletUrl: walletOverride,\n enabled = true,\n}: UseAccountEnrolmentOptions = {}): AccountEnrolment {\n const { connectWithAccount, cloudBaseUrl } = useMero();\n const [note, setNote] = useState<string | null>(null);\n\n const walletUrl = walletOverride ?? HOSTED_WALLET;\n\n /**\n * Read the enrolment callback ONCE, during render.\n *\n * `readEnrolmentCallback` consumes the fragment — it strips it from the\n * address bar so a reload cannot replay the credential. That makes it unsafe\n * to call from an effect: React's StrictMode double-invokes effects in dev,\n * so the first run would swallow the credential and then abort through its\n * own cleanup, and the second would find nothing and silently show the\n * connect prompt again. `MeroContext` reads its auth callback this way for\n * the same reason.\n *\n * The throw case (`error=cancelled`) is captured rather than propagated: a\n * declined approval is an ordinary outcome to report, not a render failure.\n */\n const callbackRef = useRef<DeviceEnrolmentCallback | null | undefined>(undefined);\n const callbackErrorRef = useRef<string | null>(null);\n if (enabled && callbackRef.current === undefined && typeof window !== 'undefined') {\n try {\n callbackRef.current = readEnrolmentCallback();\n } catch (e) {\n callbackRef.current = null;\n callbackErrorRef.current = e instanceof Error ? e.message : String(e);\n }\n }\n /**\n * Whether this load came back from the wallet. Fixed at the first read: the\n * effect below clears the error ref once it has reported it.\n */\n const returningRef = useRef<boolean | null>(null);\n if (returningRef.current === null && callbackRef.current !== undefined) {\n returningRef.current = callbackRef.current !== null || callbackErrorRef.current !== null;\n }\n /** One completion per callback, however many times the effect runs. */\n const completingRef = useRef(false);\n\n /**\n * Finish an enrolment we are returning from.\n *\n * Runs before the button paints anything, so a tab coming back from the\n * wallet lands connected rather than showing the connect prompt again.\n */\n useEffect(() => {\n if (callbackErrorRef.current) {\n setNote(callbackErrorRef.current);\n callbackErrorRef.current = null;\n return;\n }\n const back = callbackRef.current;\n if (!back || completingRef.current) return;\n completingRef.current = true;\n let cancelled = false;\n\n (async () => {\n try {\n const keys = await deviceKeys();\n\n // Nothing is carried across the redirect any more beyond the device keys\n // themselves. There used to be a `sessionStorage` record holding the\n // typed relay and context; both are now answered by the credential this\n // returns, so the record held nothing and the \"they were lost, try\n // again\" failure it guarded cannot happen.\n // The state we sent, not the one that came back. `expectState: back.state`\n // compared the returned value against itself and therefore always passed,\n // which left the parameter as decoration: any page able to drive this\n // origin's callback could have had a credential adopted here.\n const sent = (() => {\n try {\n return sessionStorage.getItem(STATE_KEY);\n } catch {\n return null;\n }\n })();\n try {\n sessionStorage.removeItem(STATE_KEY);\n } catch {\n /* single-use where storage allows it; the comparison below is the gate */\n }\n if (!sent) {\n // No record of having started this. Refused rather than adopted: this is\n // either a callback we did not initiate, or storage that lost the value\n // mid-flow, and neither justifies accepting a certificate.\n setNote(\n 'This enrolment could not be verified as one this tab started, so it was not ' +\n 'accepted. Start again from \"Enrol with your account\".',\n );\n return;\n }\n const enrolled = await completeDeviceEnrolment({\n ...back,\n devicePublicKey: keys.signPk,\n kemPublicKey: keys.kemPk,\n expectState: sent,\n });\n\n /*\n * Where to write: asked, not typed.\n *\n * The certificate that just came back is the only input this needs. The\n * cloud mints an account-bound nonce, the device key signs it, and the\n * relay list comes back attributed to this account — no cloud session,\n * no Google sign-in, no account root. Which is why this can run here, on\n * the way home from the wallet, for a person who has none of those.\n *\n * `CloudClient`'s default base URL is the prod manager\n * (`manager.cloud.calimero.network`), which is the right default for a\n * hosted account and the only deployment that answers this route today.\n */\n // Saved BEFORE the relay lookup, and kept whatever that lookup answers.\n //\n // A first-time account is a member of nothing, so `getAccountRelays`\n // correctly answers `[]` and no connection is made below. That is not a\n // failed enrolment: the certificate is real, and it is the input that\n // resolves a relay from an INVITATION instead\n // (`useDelegatedBootstrap`). Discarding it here would make \"no relay\n // yet\" mean \"enrol again\", which mints a second device for an account\n // whose first one was fine.\n saveDelegatedCredential({\n account: enrolled.account,\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n });\n\n const cloud = new CloudClient({\n cloudBaseUrl,\n routingCredential: {\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n },\n });\n const chosen = chooseRelay(await cloud.getAccountRelays(enrolled.account));\n // Connected either way — see `chooseRelay`. A null relay is an\n // authenticated account with nowhere to write yet, and the note says\n // what changes that.\n if (chosen.note) setNote(chosen.note);\n\n // Nothing else to obtain. The certificate this enrolment just returned\n // authenticates the reads and the event stream as well as the writes —\n // the device key signs each request and the node verifies it against the\n // certificate. There used to be a `login()` here, minting a session\n // against the relay node's signing key; that key had to be learned out of\n // band and the hosted case has never published one, so the picker was\n // dark on exactly the deployment it was written for.\n\n // Deliberately NOT gated on `cancelled`: the fragment has already been\n // consumed, so abandoning here would strand a credential that cannot be\n // read again. The context outlives this component, so installing the\n // connection after a StrictMode teardown is correct.\n // The relay's executor rides along when the cloud named one, so a\n // brand-new account can found a namespace on it with no join first.\n // Left off entirely otherwise, so an older server's session is the\n // same record it always was.\n connectWithAccount({\n relayUrl: chosen.relayUrl,\n account: enrolled.account,\n credential: enrolled.credential,\n deviceSecret: keys.signSk,\n ...(chosen.executorAccount ? { executorAccount: chosen.executorAccount } : {}),\n });\n } catch (e) {\n if (!cancelled) setNote(e instanceof Error ? e.message : String(e));\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [connectWithAccount, cloudBaseUrl]);\n\n const goToWallet = useCallback(async () => {\n // No inputs to validate: there is nothing left to ask for. A device key this\n // browser cannot make (no X25519, blocked storage) is reported in the note,\n // where the person is looking, rather than lost as an unhandled rejection.\n let keys: DeviceKeys;\n try {\n keys = await deviceKeys();\n } catch (e) {\n setNote(e instanceof Error ? e.message : String(e));\n return;\n }\n // Remembered before leaving, so what comes back can be checked against what\n // we sent. Without this the state parameter is decoration: comparing the\n // returned value to itself always passes, which is what it did here.\n const state = hex(crypto.getRandomValues(new Uint8Array(16)));\n try {\n sessionStorage.setItem(STATE_KEY, state);\n } catch {\n // Storage unavailable (private mode, blocked site data). The redirect\n // still works and the check below reports it as unverifiable rather than\n // silently passing.\n }\n window.location.assign(\n deviceEnrolmentUrl({\n walletUrl,\n devicePublicKey: keys.signPk,\n kemPublicKey: keys.kemPk,\n returnTo: window.location.origin + window.location.pathname,\n state,\n }),\n );\n }, [walletUrl]);\n\n return {\n goToWallet,\n note,\n returning: returningRef.current === true,\n walletUrl,\n customWallet: walletOverride !== undefined,\n };\n}\n","/**\n * Is this page running inside a Calimero Desktop (Tauri) window?\n *\n * The desktop opens every app in its own webview, already bound to the node it\n * runs, so the Cloud sign-in (wallet → relay, no node) is the wrong door there:\n * it would leave the desktop's own node behind, and the wallet redirect would\n * navigate the app window off to another origin.\n *\n * Two signals, either is enough:\n * - `__TAURI_INTERNALS__`, which Tauri injects natively into every webview it\n * creates, remote URLs included — what mero-js's own Tauri check reads;\n * - `__TAURI_FETCH_PROXY_INJECTED__`, the marker the desktop's app-window\n * init script sets, in case a future Tauri stops exposing the former there.\n *\n * Read at call time and SSR-safe: false whenever there is no `window`.\n */\nexport function isDesktopWindow(): boolean {\n if (typeof window === 'undefined') return false;\n const w = window as unknown as Record<string, unknown>;\n return '__TAURI_INTERNALS__' in w || w.__TAURI_FETCH_PROXY_INJECTED__ === true;\n}\n","/**\n * LoginModal - Modal for connecting to a Calimero node\n *\n * A single section: the modal auto-discovers nodes on the well-known local\n * ports (see `nodeDiscovery`) and offers whatever is running as radio choices,\n * plus an always-available \"enter URL manually\" option. With nothing found it\n * falls straight through to manual URL entry.\n *\n * The old Local/Remote tabs are gone — the \"Local\" tab pointed at a hardcoded\n * default node (`node1.127.0.0.1.nip.io`) that doesn't resolve in most setups;\n * discovery + manual entry covers both cases properly.\n *\n * By default the modal has two tabs: **Node** (everything above, unchanged,\n * selected by default) and **Cloud** (sign in with a Calimero account — see\n * `AccountSignInPanel` / `useAccountEnrolment`). The Cloud tab is sourced from\n * `useAccountEnrolment` inside the modal, so an app that mounts `LoginModal`\n * itself gets account sign-in with no wiring; `cloud={false}` removes it, and\n * a `cloud` object (what `ConnectButton` passes) replaces it with the caller's.\n *\n * Because of that the modal reads `useMero()` and must sit inside a\n * `MeroProvider`, as every app's does.\n *\n * Styling: colors and radius are `--mero-*` tokens (a `theme` prop, or global\n * variables). Every part also carries a stable `mero-login-*` class, as\n * `InvitationDialog` does with `mero-invite-*`, so an app can restyle what the\n * tokens do not reach. Inline styles outrank classes, so the look that is not a\n * token stays out of them where it can: the font is inherited (set it on\n * `.mero-login-overlay`), and the dialog's shadow reads `--mero-login-shadow`\n * with today's shadow as the fallback.\n */\n\nimport { useMemo, useState, useEffect, useCallback, useRef } from 'react';\nimport { createPortal } from 'react-dom';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport { AccountSignInPanel } from './AccountSignInPanel';\nimport { useAccountEnrolment } from '../delegated/useAccountEnrolment';\nimport { isDesktopWindow } from '../utils/desktop';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport {\n discoverLocalNodes,\n nodeEndpoint,\n DEFAULT_LOCAL_NODE_PORTS,\n} from '@calimero-network/mero-js';\nimport {\n cssVar,\n resolveMeroTheme,\n themeToCssVars,\n type MeroTheme,\n type ResolvedMeroTheme,\n} from '../theme';\n\n/** Sentinel selection value for the manual \"enter a URL\" option. */\nconst CUSTOM_SELECTION = '__custom__';\n\nexport interface LoginModalProps {\n /** Callback when user connects */\n onConnect: (url: string) => void;\n /** Callback when modal is closed */\n onClose: () => void;\n /**\n * @deprecated Ignored. The modal always shows node discovery + manual URL\n * entry; the old hardcoded-default \"Local\" view was removed. Kept so\n * existing call sites keep compiling.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Whether the modal is open */\n isOpen: boolean;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Ports probed when discovering local nodes. Defaults to the well-known\n * Calimero dev ports (2428, 2429, 2528, 2529). Mostly an escape hatch for\n * non-standard setups and tests.\n */\n localNodePorts?: readonly number[];\n /**\n * The second way in: a **Cloud** tab, signing in with a Calimero account by\n * enrolling this tab's device key at the wallet.\n *\n * - **Omitted** (the default): the tab is shown, sourced from\n * `useAccountEnrolment()` inside the modal — enrolment starts from the tab,\n * and a page coming back from the wallet is completed here, whether or not\n * the modal is open. Nothing to wire; the modal must be inside a\n * `MeroProvider`.\n * - **`false`**: no Cloud tab and no tabs at all — the node dialog as it was.\n * - **omitted inside a Calimero Desktop window**: as `false` — the window is\n * already bound to the desktop's node. Pass a `cloud` object to override.\n * The modal reads no enrolment callback, leaving it to whichever component\n * does.\n * - **An object**: the caller's own enrolment, used verbatim; the modal reads\n * none itself. The values are `useAccountEnrolment`'s, as `ConnectButton`\n * passes them.\n */\n cloud?:\n | false\n | {\n /** Start enrolment — normally `useAccountEnrolment().goToWallet`. */\n onEnrol: () => void;\n /** What the last enrolment had to say, shown on the Cloud tab. */\n note?: string | null;\n /** The wallet enrolment goes to. Shown only when `customWallet`. */\n walletUrl?: string;\n /** Whether `walletUrl` is an override rather than the hosted wallet. */\n customWallet?: boolean;\n };\n /**\n * The tab selected when the modal opens. Ignored with `cloud={false}`.\n *\n * Default `'node'` — except that a modal sourcing its own Cloud tab opens on\n * `'cloud'` when the page is coming back from the wallet, so whatever the\n * completion has to say is where the person is looking. An explicit value\n * always wins.\n */\n initialTab?: LoginModalTab;\n}\n\n/** The two tabs of the connect dialog, when it has a Cloud tab. */\nexport type LoginModalTab = 'node' | 'cloud';\n\nconst TABS: readonly { id: LoginModalTab; label: string }[] = [\n { id: 'node', label: 'Node' },\n { id: 'cloud', label: 'Cloud' },\n];\n\n/**\n * Validate URL format\n */\nfunction isValidUrl(urlString: string): boolean {\n if (!urlString || urlString.trim() === '') {\n return false;\n }\n\n try {\n const urlToTest =\n urlString.startsWith('http://') || urlString.startsWith('https://')\n ? urlString\n : `https://${urlString}`;\n\n const url = new URL(urlToTest);\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return false;\n }\n\n if (!url.hostname) {\n return false;\n }\n\n const hostname = url.hostname;\n\n // Allow localhost\n if (hostname === 'localhost') {\n return true;\n }\n\n // Check for valid IP address\n const ipv4Regex = /^(\\d{1,3}\\.){3}\\d{1,3}$/;\n if (ipv4Regex.test(hostname)) {\n const octets = hostname.split('.').map(Number);\n return octets.every((octet) => octet >= 0 && octet <= 255);\n }\n\n // Check for valid domain name\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n return domainRegex.test(hostname);\n } catch {\n return false;\n }\n}\n\n/** Strip the scheme for a compact node label (e.g. `localhost:2428`). */\nfunction displayNodeUrl(url: string): string {\n return url.replace(/^https?:\\/\\//, '').replace(/\\/+$/, '');\n}\n\n/**\n * Mix a color with transparent using CSS `color-mix`. Works for any valid CSS\n * color value (hex of any length, rgb(), hsl(), named colors, var(...)) — not\n * just 6-digit hex.\n */\nfunction tint(color: string, percent: number): string {\n return `color-mix(in srgb, ${color} ${percent}%, transparent)`;\n}\n\n/**\n * Build the inline-style map from a resolved theme. Each value is emitted as\n * `var(--mero-*, fallback)` so a global `:root { --mero-* }` rule reaches the\n * portal-rendered modal; the fallback ensures the modal still renders correctly\n * if the consumer hasn't imported `styles.css`.\n */\nfunction buildStyles(t: ResolvedMeroTheme) {\n const bg = cssVar(t, 'background');\n const bgSecondary = cssVar(t, 'backgroundSecondary');\n const text = cssVar(t, 'text');\n const textSecondary = cssVar(t, 'textSecondary');\n const accent = cssVar(t, 'primary');\n const onPrimary = cssVar(t, 'primaryText');\n const border = cssVar(t, 'border');\n const error = cssVar(t, 'error');\n const overlay = cssVar(t, 'overlay');\n const radius = cssVar(t, 'radius');\n\n const errorBg = tint(error, 10);\n const errorBorder = tint(error, 30);\n const accentGlow = tint(accent, 15);\n\n return {\n overlay: {\n position: 'fixed' as const,\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n backgroundColor: overlay,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n zIndex: 10000,\n padding: '1rem',\n animation: 'meroFadeIn 0.2s ease-out',\n },\n content: {\n backgroundColor: bg,\n borderRadius: radius,\n padding: '2rem',\n maxWidth: '420px',\n width: '100%',\n position: 'relative' as const,\n border: `1px solid ${border}`,\n // Not a theme token, so an app could not reach it past the inline style:\n // `--mero-login-shadow` replaces it whole. Unset, it is the shadow and\n // accent ring the dialog always had.\n boxShadow: `var(--mero-login-shadow, 0 25px 50px -12px rgba(0, 0, 0, 0.6), 0 0 0 1px ${accentGlow})`,\n animation: 'meroSlideIn 0.25s ease-out',\n color: text,\n },\n closeButton: {\n position: 'absolute' as const,\n top: '0.75rem',\n right: '0.75rem',\n background: 'none',\n border: 'none',\n fontSize: '1.5rem',\n color: textSecondary,\n cursor: 'pointer',\n padding: '0.25rem',\n lineHeight: 1,\n },\n header: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n marginBottom: '1.5rem',\n },\n title: {\n fontSize: '1.25rem',\n fontWeight: 600,\n color: text,\n margin: 0,\n },\n info: {\n color: textSecondary,\n textAlign: 'center' as const,\n marginBottom: '1.5rem',\n fontSize: '0.875rem',\n },\n error: {\n color: error,\n backgroundColor: errorBg,\n border: `1px solid ${errorBorder}`,\n borderRadius: radius,\n padding: '0.75rem',\n marginBottom: '1rem',\n fontSize: '0.875rem',\n textAlign: 'center' as const,\n },\n radioList: {\n display: 'flex',\n flexDirection: 'column' as const,\n gap: '0.5rem',\n marginBottom: '1rem',\n },\n radioItem: {\n display: 'flex',\n alignItems: 'center',\n gap: '0.625rem',\n color: text,\n cursor: 'pointer',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n transition: 'all 0.15s ease',\n fontSize: '0.875rem',\n },\n radioItemActive: {\n // Override the full `border` shorthand (not just borderColor) so React\n // never has to mix shorthand + longhand on the same element.\n border: `1px solid ${accent}`,\n backgroundColor: accentGlow,\n color: text,\n },\n radioIndicator: {\n flexShrink: 0,\n width: '1rem',\n height: '1rem',\n borderRadius: '50%',\n border: `2px solid ${border}`,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n },\n radioIndicatorActive: {\n border: `2px solid ${accent}`,\n },\n radioDot: {\n width: '0.5rem',\n height: '0.5rem',\n borderRadius: '50%',\n backgroundColor: accent,\n },\n nodeMeta: {\n marginLeft: 'auto',\n fontSize: '0.75rem',\n color: textSecondary,\n },\n input: {\n width: '100%',\n padding: '0.75rem 1rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n color: text,\n fontSize: '0.875rem',\n outline: 'none',\n marginBottom: '1rem',\n boxSizing: 'border-box' as const,\n },\n toolbar: {\n display: 'flex',\n justifyContent: 'center',\n marginBottom: '1rem',\n },\n rescan: {\n background: 'none',\n border: 'none',\n color: accent,\n cursor: 'pointer',\n fontSize: '0.8125rem',\n padding: '0.25rem 0.5rem',\n },\n buttonGroup: {\n display: 'flex',\n justifyContent: 'center',\n },\n button: {\n padding: '0.75rem 2rem',\n borderRadius: radius,\n border: 'none',\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n backgroundColor: accent,\n color: onPrimary,\n transition: 'all 0.15s ease',\n },\n buttonDisabled: {\n opacity: 0.5,\n cursor: 'not-allowed',\n },\n loading: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '1rem',\n padding: '2rem',\n color: textSecondary,\n },\n discovering: {\n display: 'flex',\n flexDirection: 'column' as const,\n alignItems: 'center',\n gap: '0.75rem',\n padding: '1rem',\n color: textSecondary,\n fontSize: '0.875rem',\n },\n spinner: {\n width: '2rem',\n height: '2rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n tabList: {\n display: 'flex',\n gap: '0.25rem',\n padding: '0.25rem',\n marginBottom: '1.5rem',\n borderRadius: radius,\n border: `1px solid ${border}`,\n backgroundColor: bgSecondary,\n },\n tab: {\n flex: 1,\n padding: '0.5rem 1rem',\n borderRadius: radius,\n border: '1px solid transparent',\n backgroundColor: 'transparent',\n color: textSecondary,\n fontSize: '0.875rem',\n fontWeight: 600,\n cursor: 'pointer',\n transition: 'all 0.15s ease',\n },\n tabActive: {\n border: `1px solid ${accent}`,\n backgroundColor: accentGlow,\n color: text,\n },\n spinnerSmall: {\n width: '1.5rem',\n height: '1.5rem',\n border: `3px solid ${border}`,\n borderTopColor: accent,\n borderRadius: '50%',\n animation: 'meroSpin 1s linear infinite',\n },\n };\n}\n\n/**\n * LoginModal - Connection modal component\n */\nexport function LoginModal({\n onConnect,\n onClose,\n isOpen,\n theme,\n localNodePorts = DEFAULT_LOCAL_NODE_PORTS,\n cloud,\n initialTab: initialTabProp,\n}: LoginModalProps) {\n // The modal's own enrolment, for the default case only. A caller that passed\n // its own `cloud` already holds an enabled hook, and the callback it reads is\n // single-use: a second enabled reader here would find nothing, or — if it\n // rendered first — take the callback away from the caller. So this is on\n // exactly when nobody else is. Called before the `isOpen` early return, so a\n // tab coming back from the wallet is completed while the modal is closed too.\n //\n // Inside a Calimero Desktop window there is no default Cloud tab: the window\n // is already bound to the desktop's node (see `isDesktopWindow`). A caller\n // that passes its own `cloud` object still gets it.\n const ownCloud = cloud === undefined && !isDesktopWindow();\n const own = useAccountEnrolment({ enabled: ownCloud });\n const cloudTab = useMemo(\n () =>\n ownCloud\n ? {\n onEnrol: () => {\n void own.goToWallet();\n },\n note: own.note,\n walletUrl: own.walletUrl,\n customWallet: own.customWallet,\n }\n : cloud || null,\n [cloud, ownCloud, own.goToWallet, own.note, own.walletUrl, own.customWallet],\n );\n const initialTab: LoginModalTab =\n initialTabProp ?? (ownCloud && own.returning ? 'cloud' : 'node');\n\n const [tab, setTab] = useState<LoginModalTab>(initialTab);\n // Each opening starts on `initialTab`: the modal stays mounted while closed,\n // so without this a reopen would land on whatever tab was left selected.\n useEffect(() => {\n if (isOpen) setTab(initialTab);\n }, [isOpen, initialTab]);\n const tabRefs = useRef<Record<LoginModalTab, HTMLButtonElement | null>>({\n node: null,\n cloud: null,\n });\n const activeTab: LoginModalTab = cloudTab ? tab : 'node';\n\n // `selected` is a discovered node URL or CUSTOM.\n const [selected, setSelected] = useState<string>(CUSTOM_SELECTION);\n const [discovered, setDiscovered] = useState<string[]>([]);\n const [discovering, setDiscovering] = useState<boolean>(false);\n const [customUrl, setCustomUrl] = useState<string>('');\n\n const [loading, setLoading] = useState<boolean>(false);\n const [error, setError] = useState<string | null>(null);\n\n const resolved = useMemo(() => resolveMeroTheme(theme), [theme]);\n const styles = useMemo(() => buildStyles(resolved), [resolved]);\n // Only emit inline `--mero-*` variables when a `theme` prop was actually\n // provided. Without a prop, we let global `:root { --mero-* }` rules cascade\n // through to the portal-rendered modal (with `var()` fallbacks in buildStyles\n // covering the case where no global rules are loaded).\n const themeVars = useMemo(\n () => (theme ? themeToCssVars(resolved) : undefined),\n [theme, resolved],\n );\n\n // Load saved URL into the manual field\n useEffect(() => {\n const savedUrl = localStorage.getItem('mero:node_url');\n if (savedUrl) {\n setCustomUrl(savedUrl);\n }\n }, []);\n\n // Probe local ports whenever the modal is open; a bumpable nonce lets the\n // user trigger a re-scan.\n const [scanNonce, setScanNonce] = useState(0);\n const portsKey = useMemo(() => localNodePorts.join(','), [localNodePorts]);\n\n useEffect(() => {\n if (!isOpen) {\n return;\n }\n\n const controller = new AbortController();\n let active = true;\n setDiscovering(true);\n // Clear any prior results so a re-scan never shows stale nodes.\n setDiscovered([]);\n setError(null);\n\n discoverLocalNodes({ ports: localNodePorts, signal: controller.signal })\n .then((nodes) => {\n if (!active) return;\n setDiscovered(nodes);\n // Default to the first discovered node, else fall through to manual.\n setSelected(nodes.length > 0 ? nodes[0] : CUSTOM_SELECTION);\n })\n // discoverLocalNodes is designed never to reject; the catch is purely\n // defensive so a future change can't surface an unhandled rejection.\n .catch(() => {\n if (active) setSelected(CUSTOM_SELECTION);\n })\n .finally(() => {\n if (active) setDiscovering(false);\n });\n\n return () => {\n active = false;\n controller.abort();\n };\n // portsKey captures localNodePorts content; scanNonce forces a re-scan.\n }, [isOpen, portsKey, scanNonce]);\n\n const isCustom = selected === CUSTOM_SELECTION;\n const hasDiscovered = discovered.length > 0;\n\n // Whether the connect button can fire in the current state.\n const canConnect =\n !loading && !discovering && (isCustom ? isValidUrl(customUrl) : true);\n\n // Keep a ref so the input's keydown handler always sees current validity.\n const canConnectRef = useRef(canConnect);\n canConnectRef.current = canConnect;\n\n const handleConnect = useCallback(async () => {\n const usingDiscovered = selected !== CUSTOM_SELECTION;\n const targetUrl = usingDiscovered ? selected : customUrl;\n\n // Manual URLs must look valid before we try them.\n if (!usingDiscovered && !isValidUrl(targetUrl)) {\n return;\n }\n\n const normalizedUrl = targetUrl.replace(/\\/+$/, '');\n\n // A discovered node already answered a health check — connect straight away.\n if (usingDiscovered) {\n onConnect(normalizedUrl);\n return;\n }\n\n // Manually entered URLs are verified via is-authed.\n setLoading(true);\n setError(null);\n\n try {\n const response = await fetch(\n nodeEndpoint(normalizedUrl, 'admin-api/is-authed'),\n );\n\n if (response.ok || response.status === 401) {\n setLoading(false);\n onConnect(normalizedUrl);\n } else {\n throw new Error(`Connection failed: ${response.statusText}`);\n }\n } catch (err) {\n console.error('Connection failed:', err);\n setError('Failed to connect. Please check the URL and try again.');\n setLoading(false);\n }\n }, [selected, customUrl, onConnect]);\n\n if (!isOpen) {\n return null;\n }\n\n const showManualInput = isCustom;\n const renderRadio = (value: string, label: string, meta?: string) => {\n const active = selected === value;\n return (\n // Selection is driven solely by the radio input's `onChange` — clicking\n // anywhere on the wrapping label forwards to the input, and keyboard\n // users can tab to / arrow through the (visually hidden but focusable)\n // input. A label `onClick` here would double-fire `setSelected`.\n <label\n key={value}\n className={\n active ? 'mero-login-option mero-login-option-active' : 'mero-login-option'\n }\n data-testid={`node-option-${value === CUSTOM_SELECTION ? 'custom' : displayNodeUrl(value)}`}\n style={{\n ...styles.radioItem,\n ...(active ? styles.radioItemActive : {}),\n }}\n >\n <input\n type=\"radio\"\n name=\"mero-node\"\n value={value}\n checked={active}\n onChange={() => setSelected(value)}\n style={{ position: 'absolute', opacity: 0 }}\n />\n <span\n className=\"mero-login-option-indicator\"\n style={{\n ...styles.radioIndicator,\n ...(active ? styles.radioIndicatorActive : {}),\n }}\n >\n {active && (\n <span className=\"mero-login-option-dot\" style={styles.radioDot} />\n )}\n </span>\n {label}\n {meta && (\n <span className=\"mero-login-option-meta\" style={styles.nodeMeta}>\n {meta}\n </span>\n )}\n </label>\n );\n };\n\n const renderNodeSection = () => {\n if (discovering) {\n return (\n <div\n className=\"mero-login-discovering\"\n style={styles.discovering}\n data-testid=\"node-discovering\"\n >\n <div className=\"mero-login-spinner\" style={styles.spinnerSmall} />\n <p>Searching for local nodes...</p>\n </div>\n );\n }\n\n return (\n <>\n <p className=\"mero-login-info\" style={styles.info}>\n {hasDiscovered\n ? 'Select your Calimero node to continue.'\n : 'No local node found. Enter a node URL to continue.'}\n </p>\n\n {hasDiscovered && (\n <div\n className=\"mero-login-options\"\n style={styles.radioList}\n role=\"radiogroup\"\n aria-label=\"Available nodes\"\n >\n {discovered.map((url) =>\n renderRadio(url, displayNodeUrl(url), 'local'),\n )}\n {/* Manual entry is always offered alongside discovered nodes. */}\n {renderRadio(CUSTOM_SELECTION, 'Enter node URL manually')}\n </div>\n )}\n\n {showManualInput && (\n <input\n type=\"text\"\n value={customUrl}\n onChange={(e) => setCustomUrl(e.target.value)}\n placeholder=\"https://your-node-url.calimero.network\"\n className=\"mero-login-input\"\n style={styles.input}\n data-testid=\"node-url-input\"\n autoFocus={!hasDiscovered}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && canConnectRef.current) {\n handleConnect();\n }\n }}\n />\n )}\n\n <div className=\"mero-login-toolbar\" style={styles.toolbar}>\n <button\n type=\"button\"\n className=\"mero-login-rescan\"\n style={styles.rescan}\n onClick={() => setScanNonce((n) => n + 1)}\n data-testid=\"rescan-button\"\n >\n ↻ Rescan local nodes\n </button>\n </div>\n </>\n );\n };\n\n // The node dialog's body, exactly as it was before there were tabs. With a\n // Cloud tab it is wrapped as the Node tabpanel; without one it is the whole\n // modal body, with no wrapper, so a direct LoginModal user sees no change.\n const renderNodeBody = () => {\n const body = loading ? (\n <div className=\"mero-login-loading\" style={styles.loading}>\n <p>Connecting to node...</p>\n <div className=\"mero-login-spinner\" style={styles.spinner} />\n </div>\n ) : (\n <>\n {error && (\n <p className=\"mero-login-error\" style={styles.error}>\n {error}\n </p>\n )}\n\n {renderNodeSection()}\n\n <div className=\"mero-login-actions\" style={styles.buttonGroup}>\n <button\n className=\"mero-login-button mero-login-primary\"\n onClick={handleConnect}\n disabled={!canConnect}\n style={{\n ...styles.button,\n ...(!canConnect ? styles.buttonDisabled : {}),\n }}\n data-testid=\"connect-button\"\n >\n Connect\n </button>\n </div>\n </>\n );\n if (!cloudTab) return body;\n return (\n <div\n className=\"mero-login-panel\"\n role=\"tabpanel\"\n id=\"mero-login-panel-node\"\n aria-labelledby=\"mero-login-tab-node\"\n >\n {body}\n </div>\n );\n };\n\n // WAI-ARIA tabs with automatic activation: the selected tab is the one tab\n // stop, and the arrow keys (plus Home/End) move selection and focus.\n const selectTab = (id: LoginModalTab) => {\n setTab(id);\n tabRefs.current[id]?.focus();\n };\n const onTabKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {\n const i = TABS.findIndex((t) => t.id === activeTab);\n let next: number | null = null;\n if (e.key === 'ArrowRight') next = (i + 1) % TABS.length;\n else if (e.key === 'ArrowLeft') next = (i - 1 + TABS.length) % TABS.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = TABS.length - 1;\n if (next === null) return;\n e.preventDefault();\n selectTab(TABS[next].id);\n };\n const renderTabs = () => (\n <div\n className=\"mero-login-tabs\"\n role=\"tablist\"\n aria-label=\"How to connect\"\n style={styles.tabList}\n >\n {TABS.map((t) => {\n const selected = activeTab === t.id;\n return (\n <button\n key={t.id}\n ref={(el) => {\n tabRefs.current[t.id] = el;\n }}\n type=\"button\"\n className={\n selected ? 'mero-login-tab mero-login-tab-active' : 'mero-login-tab'\n }\n role=\"tab\"\n id={`mero-login-tab-${t.id}`}\n aria-selected={selected}\n aria-controls={`mero-login-panel-${t.id}`}\n tabIndex={selected ? 0 : -1}\n onClick={() => setTab(t.id)}\n onKeyDown={onTabKeyDown}\n style={{ ...styles.tab, ...(selected ? styles.tabActive : {}) }}\n data-testid={`login-tab-${t.id}`}\n >\n {t.label}\n </button>\n );\n })}\n </div>\n );\n\n const modalContent = (\n <>\n <style>{`\n @keyframes meroSpin { to { transform: rotate(360deg); } }\n @keyframes meroFadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes meroSlideIn { from { transform: translateY(-12px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n `}</style>\n <div\n className=\"mero-login-overlay\"\n style={{ ...themeVars, ...styles.overlay }}\n onClick={onClose}\n >\n <div\n className=\"mero-login-dialog\"\n style={styles.content}\n onClick={(e) => e.stopPropagation()}\n >\n <button\n className=\"mero-login-close\"\n style={styles.closeButton}\n onClick={onClose}\n aria-label=\"Close\"\n >\n &times;\n </button>\n\n <div className=\"mero-login-header\" style={styles.header}>\n <CalimeroLogo\n size={44}\n color={cssVar(resolved, 'primary')}\n className=\"mero-login-logo\"\n />\n <h1 className=\"mero-login-title\" style={styles.title}>\n Connect to Calimero\n </h1>\n </div>\n\n {cloudTab && renderTabs()}\n\n {activeTab === 'cloud' && cloudTab ? (\n <div\n className=\"mero-login-panel\"\n role=\"tabpanel\"\n id=\"mero-login-panel-cloud\"\n aria-labelledby=\"mero-login-tab-cloud\"\n tabIndex={0}\n >\n <AccountSignInPanel\n onEnrol={cloudTab.onEnrol}\n note={cloudTab.note}\n walletUrl={cloudTab.walletUrl}\n customWallet={cloudTab.customWallet}\n theme={theme}\n />\n </div>\n ) : (\n renderNodeBody()\n )}\n </div>\n </div>\n </>\n );\n\n return createPortal(modalContent, document.body);\n}\n\nexport default LoginModal;\n","/**\n * ConnectButton - A button component for connecting to Calimero\n *\n * Shows connection status and provides login/logout functionality.\n * Includes built-in LoginModal with two tabs: **Node** (node discovery + URL,\n * the default) and **Cloud** (sign in with a Calimero account by enrolling at\n * the wallet — see `useAccountEnrolment`). `cloud={false}` removes the Cloud\n * tab and leaves the node dialog exactly as it was.\n */\n\nimport React, { useState, useEffect, useRef, useMemo } from 'react';\nimport { useMero } from '../context';\nimport { LoginModal } from './LoginModal';\nimport { isDesktopWindow } from '../utils/desktop';\nimport { useAccountEnrolment } from '../delegated/useAccountEnrolment';\nimport { readDelegatedSession } from '@calimero-network/mero-js';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport type { ConnectionType, CustomConnectionConfig } from '../types';\nimport { ConnectionType as ConnectionTypeEnum } from '../types';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\nexport interface ConnectButtonProps {\n /**\n * Connection behaviour. `Custom` (object form) connects straight to the\n * given URL, skipping the modal; every other value opens the LoginModal,\n * which always shows node discovery + manual URL entry.\n */\n connectionType?: ConnectionType | CustomConnectionConfig;\n /** Custom class name */\n className?: string;\n /** Custom styles */\n style?: React.CSSProperties;\n /** Theme overrides — accepts any subset of `MeroTheme` tokens */\n theme?: MeroTheme;\n /**\n * Render only the Calimero logo, no text. Produces a square 40×40 icon\n * button. The label is still announced to screen readers via `aria-label`.\n * Default: false.\n */\n logoOnly?: boolean;\n /**\n * Override the default labels per state. A bare string is shorthand for\n * `{ connect: '<string>' }`. The connected and reconnecting states keep\n * their defaults unless explicitly overridden.\n */\n label?:\n | string\n | { connect?: string; connected?: string; reconnecting?: string };\n /**\n * Offer the **Cloud** tab — sign in with a Calimero account — next to the\n * node dialog. Default true in a browser, false inside a Calimero Desktop\n * window (already bound to the desktop's node; see `isDesktopWindow`). With\n * false the modal has no tabs, and this button reads no enrolment callback,\n * leaving it to whichever component does.\n */\n cloud?: boolean;\n /**\n * Overrides for the account path, for local development only.\n */\n accountDefaults?: {\n /**\n * Point enrolment at a wallet other than the hosted one — for working ON\n * the wallet, e.g. one served from `localhost:8090`.\n */\n walletUrl?: string;\n };\n}\n\n/** `abcdef…123456` — enough of a 64-hex account id to recognise it. */\nfunction shortAccount(account: string): string {\n return account.length > 14 ? `${account.slice(0, 6)}…${account.slice(-6)}` : account;\n}\n\n/**\n * ConnectButton - Displays connection status and handles login/logout\n */\nexport function ConnectButton({\n connectionType = ConnectionTypeEnum.Remote,\n className,\n style,\n theme,\n logoOnly = false,\n label,\n cloud: cloudProp,\n accountDefaults,\n}: ConnectButtonProps) {\n const cloud = cloudProp ?? !isDesktopWindow();\n const { isAuthenticated, connectToNode, logout, nodeUrl, isOnline, isDelegated } = useMero();\n const enrolment = useAccountEnrolment({\n walletUrl: accountDefaults?.walletUrl,\n enabled: cloud,\n });\n // A tab coming back from the wallet opens straight onto the Cloud tab, so\n // whatever the completion has to say is where the person is looking. Once\n // `connectWithAccount` lands, the connected state below replaces it.\n const [isModalOpen, setIsModalOpen] = useState(() => cloud && enrolment.returning);\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n // The account an account session belongs to, for the dropdown. Read from the\n // stored session (the context exposes `isDelegated`, not the account).\n const account = useMemo(\n () => (isAuthenticated && isDelegated ? readDelegatedSession()?.account ?? null : null),\n [isAuthenticated, isDelegated],\n );\n\n // Resolve once. Inline CSS variables are only emitted when a theme prop is\n // provided — otherwise we leave the cascade alone so global `:root { --mero-* }`\n // overrides take effect.\n const resolvedTheme = useMemo(\n () => (theme ? resolveMeroTheme(theme) : null),\n [theme],\n );\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n // Close dropdown when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (\n dropdownRef.current &&\n !dropdownRef.current.contains(event.target as Node)\n ) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', handleClickOutside);\n return () => document.removeEventListener('mousedown', handleClickOutside);\n }, []);\n\n const dashboardUrl = useMemo(() => {\n if (!isAuthenticated || !nodeUrl || isDelegated) return '#';\n return new URL('admin-dashboard/', nodeUrl).toString();\n }, [isAuthenticated, nodeUrl]);\n\n const labels = useMemo(() => {\n const overrides = typeof label === 'string' ? { connect: label } : label;\n return {\n connect: overrides?.connect ?? 'Connect',\n connected: overrides?.connected ?? 'Connected',\n reconnecting: overrides?.reconnecting ?? 'Reconnecting...',\n };\n }, [label]);\n\n const buttonClassName = logoOnly ? 'mero-logo-only' : '';\n\n const handleConnect = () => {\n // If Custom type with URL, connect directly\n if (\n typeof connectionType === 'object' &&\n connectionType.type === ConnectionTypeEnum.Custom\n ) {\n connectToNode(connectionType.url);\n return;\n }\n\n // Otherwise, open modal\n setIsModalOpen(true);\n };\n\n const handleModalConnect = (url: string) => {\n setIsModalOpen(false);\n connectToNode(url);\n };\n\n // Reconnecting state\n if (isAuthenticated && !isOnline) {\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-reconnecting', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label={labels.reconnecting}\n title={logoOnly ? labels.reconnecting : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.reconnecting}\n </button>\n </div>\n );\n }\n\n // Connected state\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((prev) => !prev)}\n aria-label={labels.connected}\n title={logoOnly ? labels.connected : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connected}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n {isDelegated && account && (\n <div className=\"mero-dropdown-info\" title={account} data-testid=\"connected-account\">\n Account {shortAccount(account)}\n </div>\n )}\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {/* A delegated account with no relay is signed in and has no node\n to name. Saying so beats an empty row that reads as a bug. */}\n {nodeUrl ?? (isDelegated ? 'no relay yet' : null)}\n </div>\n {isDelegated && enrolment.note && (\n <div className=\"mero-dropdown-info\" data-testid=\"connected-note\">\n {enrolment.note}\n </div>\n )}\n {/* No dashboard link on the delegated path: the admin dashboard is\n a node-operator surface, and a keyholder has no credential for\n it. Offering a link that 401s would be worse than omitting it. */}\n {!isDelegated && (\n <a\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n )}\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n // Disconnected state\n return (\n <div\n className=\"mero-connect-container\"\n style={{ ...themeVars, display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', buttonClassName, className].filter(Boolean).join(' ')}\n style={style}\n onClick={handleConnect}\n aria-label={labels.connect}\n title={logoOnly ? labels.connect : undefined}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {!logoOnly && labels.connect}\n </button>\n <LoginModal\n isOpen={isModalOpen}\n onConnect={handleModalConnect}\n onClose={() => setIsModalOpen(false)}\n theme={resolvedTheme ?? theme}\n cloud={\n cloud\n ? {\n onEnrol: () => {\n void enrolment.goToWallet();\n },\n note: enrolment.note,\n walletUrl: enrolment.walletUrl,\n customWallet: enrolment.customWallet,\n }\n : false\n }\n initialTab={cloud && enrolment.returning ? 'cloud' : 'node'}\n />\n </div>\n );\n}\n\nexport default ConnectButton;\n","/**\n * ConnectButtonAccount — ConnectButton, plus a second way in.\n *\n * A copy of {@link ConnectButton} rather than a change to it, deliberately:\n * the node-login path is load-bearing for every shipped app, and this is an\n * experiment. `ConnectButton` and `LoginModal` are untouched.\n *\n * Two ways to connect, and the difference is who runs the node:\n *\n * - **I run a node** — exactly today's behaviour. `LoginModal` discovers nodes\n * or takes a URL, and `connectToNode` redirects into the node's auth flow.\n * - **I have an account** — no node. A wallet on another origin certifies this\n * tab's device key, and a relay writes on the account's behalf under warrants\n * signed here.\n *\n * ## One credential, two signatures over it\n *\n * The certificate the wallet mints is the whole of what this holds. The device\n * key it certifies signs two different things, and neither needs anything more:\n *\n * - a **warrant**, per intent, is what `rpc.execute` sends — an app's own logic,\n * including a generated ABI client, runs on this alone;\n * - a **request proof** (`X-Calimero-Proof`), per request, authenticates the\n * caller-scoped reads and the event stream. The node verifies the signature\n * against the certificate with no store read and no prior relationship, so\n * `getContexts` and `listNamespaces` answer this account's own and `/sse`\n * delivers this account's contexts.\n *\n * ## The pane asks for nothing\n *\n * It used to have three fields, and not one of them was a question an end user\n * could answer. All three are gone:\n *\n * - the **relay** is discovered. The same certificate proves the cloud's\n * account→relay lookup (`CloudClient.getAccountRelays`): the device signs an\n * account-bound nonce and the cloud names the relays. No cloud session, no\n * Google sign-in, no account root.\n * - the **wallet** is a platform constant, defaulted here, overridable only for\n * working on the wallet itself.\n * - the **context** is chosen after connecting, not before. `MeroContext` learns\n * this tab's `applicationId` from the registry by the app's `packageName`\n * (the account's contexts, caller-scoped by the request proof, name it only\n * when the app passes none), so an app's own context picker has what it needs\n * and the person picks from a list instead of pasting a 64-hex id.\n *\n * So the account path is one button.\n *\n * This pane used to ask for the relay node's signing key as well, to mint an\n * `account_proof` session with `login()`. Nothing needs it: the proof path was\n * measured serving the same reads and the same events without it, against a node\n * built from core `aecba573b`. A session remains the right shape where the device\n * key sits behind a boundary worth crossing once — a hardware key — which is not\n * this.\n */\n\nimport React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { useMero } from '../context';\nimport { useAccountEnrolment } from '../delegated/useAccountEnrolment';\nimport { LoginModal } from './LoginModal';\nimport { isDesktopWindow } from '../utils/desktop';\nimport { CalimeroLogo } from './CalimeroLogo';\nimport { resolveMeroTheme, themeToCssVars, type MeroTheme } from '../theme';\n\nexport interface ConnectButtonAccountProps {\n className?: string;\n style?: React.CSSProperties;\n theme?: MeroTheme;\n /**\n * Overrides for local development. An app in production passes none of this,\n * and the pane asks the person for nothing at all.\n *\n * Nothing here is a value an end user could know, which is precisely why none\n * of it is a form field any more:\n *\n * - the **relay** is discovered — the certificate the enrolment returns proves\n * the cloud's account→relay lookup, so there is nothing to type and a prefill\n * would only be a staler second source of truth;\n * - the **context** is chosen after connecting, from the account's own contexts,\n * which `admin.getContexts()` answers caller-scoped through the request proof.\n */\n /**\n * Show the \"I have an account\" path. Default true in a browser, false inside\n * a Calimero Desktop window, which is already bound to the desktop's node\n * (see `isDesktopWindow`).\n */\n cloud?: boolean;\n defaults?: {\n /**\n * Point enrolment at a wallet other than the hosted one.\n *\n * Exists for working ON the wallet: a wallet served from `localhost:8090`\n * cannot be reached through the hosted URL, and without this the only way to\n * test a wallet change would be to deploy it.\n */\n walletUrl?: string;\n };\n}\n\nexport function ConnectButtonAccount({\n className,\n style,\n theme,\n defaults = {},\n cloud: cloudProp,\n}: ConnectButtonAccountProps) {\n const cloud = cloudProp ?? !isDesktopWindow();\n const { isAuthenticated, isOnline, nodeUrl, isDelegated, connectToNode, logout } = useMero();\n\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const [isNodeModalOpen, setIsNodeModalOpen] = useState(false);\n const [isAccountOpen, setIsAccountOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n const resolvedTheme = useMemo(() => (theme ? resolveMeroTheme(theme) : null), [theme]);\n const themeVars = useMemo(\n () => (resolvedTheme ? themeToCssVars(resolvedTheme) : undefined),\n [resolvedTheme],\n );\n\n useEffect(() => {\n const onOutside = (e: MouseEvent) => {\n if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {\n setIsDropdownOpen(false);\n }\n };\n document.addEventListener('mousedown', onOutside);\n return () => document.removeEventListener('mousedown', onOutside);\n }, []);\n\n const { goToWallet, note, walletUrl } = useAccountEnrolment({\n walletUrl: defaults.walletUrl,\n enabled: cloud,\n });\n\n if (isAuthenticated && !isOnline) {\n return (\n <div className=\"mero-connect-container\" style={{ ...themeVars, display: 'inline-block' }}>\n <button\n className={['mero-connect-button', 'mero-reconnecting', className].filter(Boolean).join(' ')}\n style={style}\n disabled\n aria-label=\"Reconnecting...\"\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n Reconnecting...\n </button>\n </div>\n );\n }\n\n if (isAuthenticated) {\n return (\n <div\n ref={dropdownRef}\n className=\"mero-connect-container\"\n style={{ ...themeVars, position: 'relative', display: 'inline-block' }}\n >\n <button\n className={['mero-connect-button', 'mero-connected', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsDropdownOpen((p) => !p)}\n aria-label=\"Connected\"\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n {isDelegated ? 'Connected (account)' : 'Connected'}\n </button>\n {isDropdownOpen && (\n <div className=\"mero-dropdown\">\n <div className=\"mero-dropdown-info\" title={nodeUrl || ''}>\n {/* A delegated account with no relay is signed in and has no node\n to name. Saying so beats an empty row that reads as a bug. */}\n {nodeUrl ?? (isDelegated ? 'no relay yet' : null)}\n </div>\n {/* No dashboard link on the delegated path: the admin dashboard is\n a node-operator surface, and a keyholder has no credential for\n it. Offering a link that 401s would be worse than omitting it. */}\n {!isDelegated && nodeUrl && (\n <a\n href={new URL('admin-dashboard/', nodeUrl).toString()}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"mero-dropdown-item\"\n >\n Dashboard\n </a>\n )}\n <button\n className=\"mero-dropdown-item\"\n onClick={() => {\n setIsDropdownOpen(false);\n logout();\n }}\n >\n Log out\n </button>\n </div>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"mero-connect-container\" style={{ ...themeVars, display: 'inline-block' }}>\n <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>\n <button\n className={['mero-connect-button', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsNodeModalOpen(true)}\n >\n <CalimeroLogo size={18} className=\"mero-logo\" />\n I run a node\n </button>\n {cloud && (\n <button\n className={['mero-connect-button', className].filter(Boolean).join(' ')}\n style={style}\n onClick={() => setIsAccountOpen((p) => !p)}\n >\n I have an account\n </button>\n )}\n </div>\n\n {cloud && isAccountOpen && (\n <div\n style={{\n marginTop: 12,\n padding: 14,\n border: '1px solid rgba(127,127,127,.35)',\n borderRadius: 8,\n display: 'grid',\n gap: 8,\n maxWidth: 520,\n textAlign: 'left',\n font: '13px system-ui, sans-serif',\n }}\n >\n {/* No form fields. Every one this pane used to have asked for\n something only an operator could know, and all three are now\n answered by the certificate: the wallet is the platform's, the relay\n is looked up, and the context is chosen afterwards from the\n account's own. What is left is a button and an explanation of what\n pressing it does. */}\n <button className=\"mero-connect-button\" onClick={goToWallet}>\n Enrol with your account\n </button>\n <p style={{ margin: 0, opacity: 0.75 }}>\n You will approve a device key on the wallet&apos;s own page, then come\n back here. The relay never sees your account root — only the\n certificate it signed.\n </p>\n <p style={{ margin: 0, opacity: 0.75 }}>\n That one certificate is all of it: finding the relay that serves your\n account, writing through it, reading your own contexts and namespaces,\n and live events. Nothing to paste in.\n </p>\n {defaults.walletUrl && (\n /* Shown only when an app overrode it, so a local rig can see at a\n glance that it is not enrolling against the hosted wallet. */\n <p style={{ margin: 0, opacity: 0.6 }}>\n Enrolling at <code>{walletUrl}</code>, not the hosted wallet.\n </p>\n )}\n </div>\n )}\n\n {note && (\n <p style={{ font: '13px system-ui, sans-serif', color: '#b3261e' }}>{note}</p>\n )}\n\n <LoginModal\n isOpen={isNodeModalOpen}\n onConnect={(url) => {\n setIsNodeModalOpen(false);\n connectToNode(url);\n }}\n onClose={() => setIsNodeModalOpen(false)}\n theme={resolvedTheme ?? theme}\n // This component runs the account path itself (the hook above); the node\n // dialog stays node-only so the single-use callback has one reader.\n cloud={false}\n />\n </div>\n );\n}\n\nexport default ConnectButtonAccount;\n","/**\n * Minimal Base58 (Bitcoin alphabet) decoder.\n *\n * Blob ids come back from the admin API Base58-encoded, while a namespace's\n * `appKey` is a hex string, so comparing \"what's installed\" to \"what the group\n * targets\" needs one side converted. Decoding Base58 to canonical lowercase hex\n * is the smaller, encoding-agnostic conversion.\n */\n\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Decode a Base58 string to a lowercase hex string (no `0x` prefix). Leading\n * `1` characters map to leading zero bytes, so the byte width is preserved.\n * Throws on any character outside the Base58 alphabet.\n */\nexport function base58ToHex(input: string): string {\n const bytes: number[] = [];\n for (const char of input) {\n let carry = ALPHABET.indexOf(char);\n if (carry === -1) throw new Error(`invalid base58 character: ${char}`);\n for (let i = 0; i < bytes.length; i++) {\n carry += bytes[i] * 58;\n bytes[i] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n for (let k = 0; k < input.length && input[k] === '1'; k++) bytes.push(0);\n return bytes\n .reverse()\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","import { useState, useCallback, useEffect, useMemo, useRef } from 'react';\nimport { classifyError, compareSemver, memberJoinedOpenOp, signerFromSecret } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { base58ToHex } from '../utils/base58';\nimport { listDelegatedContexts, listDelegatedNamespaces, readDelegatedSession } from '@calimero-network/mero-js';\nimport { governRoot } from '@calimero-network/mero-js';\nimport { createDelegatedContext, createDelegatedPrivateContext } from '@calimero-network/mero-js';\nimport type {\n Codec,\n EphemeralClient,\n Context,\n CreateContextRequest,\n CreateGroupInvitationRequest,\n CreateGroupInNamespaceRequest,\n CreateNamespaceInvitationRequest,\n CreateNamespaceInvitationResponseData,\n CreateNamespaceRequest,\n CreateRecursiveInvitationResponseData,\n GetBlobInfoResponseData,\n GroupContextEntry,\n GroupInfo,\n GroupUpgradeStatusResponseData,\n MetadataRecord,\n JoinGroupRequest,\n JoinNamespaceRequest,\n ListGroupMembersResponseData,\n Namespace,\n NodeIdentity,\n ReparentGroupRequest,\n AddGroupMembersRequest,\n RemoveGroupMembersRequest,\n SetDefaultCapabilitiesRequest,\n SetMetadataRequest,\n SetSubgroupVisibilityRequest,\n SetTeeAdmissionPolicyRequest,\n SubgroupEntry,\n SseEventData,\n UpdateMemberRoleRequest,\n UpgradeGroupRequest,\n UploadBlobRequest,\n ResyncContextRequest,\n MigrationStatus,\n MemberMigrationStatusEntry,\n MigrationStatusRollup,\n MigrateMyEntriesSummary,\n AppVersionChangedEvent,\n GroupMembershipEventData,\n GroupMigrationEventData,\n ClassifiedError,\n RedeemOutcome,\n} from '@calimero-network/mero-js';\nimport type {\n ApplicationContextRecord,\n ContextDiscoveryOptions,\n ContextDiscoveryState,\n} from '../types';\n\nexport { useMero } from '../context';\n\n/**\n * The presence types come straight from `mero-js` now — `Codec` and\n * `EphemeralEntry` are its own declarations, and `EphemeralClient` is the type\n * of the class behind `mero.ephemeral`, so a drift between what this hook\n * assumes and what the SDK does is a compile error rather than a runtime\n * surprise.\n *\n * Re-exported under the same names this package has always exported, so\n * consumers importing `Codec` / `EphemeralEntry` / `EphemeralClient` from\n * `@calimero-network/mero-react` keep compiling — they now simply get the\n * nominal `mero-js` types instead of structural copies of them.\n *\n * On `EphemeralEntry.ageMs`: it is ABSENT on a live delta and PRESENT on a\n * replayed seed entry, reporting how stale that entry already was (bounded by\n * the node's presence TTL). Absent and `0` are different — a `0` means \"the\n * node replayed this and it is brand new\", not \"no age information\". Read it\n * with `?? 0`, never with a truthiness check.\n */\nexport type { Codec, EphemeralEntry, EphemeralClient } from '@calimero-network/mero-js';\n\nexport interface UseEphemeralOptions<T> {\n /** Encoding for the presence slice. Defaults to JSON. */\n codec?: Codec<T>;\n /** Base value for the first `setPresence` merge. */\n initial?: T;\n /** Minimum ms between publishes. Trailing edge — the latest value wins. */\n throttleMs?: number;\n /** Include your own echoed presence in `peers`. Default false. */\n includeSelf?: boolean;\n}\n\n/** Shape returned by {@link useEphemeral}. */\nexport interface UseEphemeralResult<T> {\n peers: Map<string, T>;\n setPresence: (partial: Partial<T>) => void;\n ageOf: (author: string) => number | undefined;\n error: Error | null;\n}\n\n/**\n * Which asynchronous producer currently owns the latched error slot.\n *\n * Only genuinely ASYNCHRONOUS failures are latched — an event happened once,\n * in the past, and nothing about the current render can re-derive it. Anything\n * that is a standing property of the current props/client (notably \"this\n * client has no `mero.ephemeral` surface\") is NOT latched: it is recomputed\n * every render, so it can neither go stale nor be accidentally cleared.\n *\n * The slot is shared, so each producer only clears what it itself raised.\n */\ntype ErrorSource = 'identity' | 'publish';\n\n/**\n * The latched async error, tagged with its producer AND with the context it\n * belongs to.\n *\n * `contextKey` is what makes cross-context leaks structurally impossible\n * rather than a matter of remembering to clear: a write whose key is no longer\n * the current context is dropped on the way in (a publish that was in flight\n * across a context switch), and a latch whose key no longer matches is not\n * read on the way out. Neither path depends on some other effect having run a\n * clear first.\n */\ninterface LatchedEphemeralError {\n contextKey: string | null;\n source: ErrorSource;\n error: Error;\n}\n\nconst NO_EPHEMERAL_SURFACE_MESSAGE =\n 'useEphemeral: this client has no `mero.ephemeral` surface. Ephemeral ' +\n 'presence requires @calimero-network/mero-js >= 9.1.0; upgrade the ' +\n 'installed @calimero-network/mero-js (and any lockfile pin) to use it.';\n\nconst COULD_NOT_RESOLVE_IDENTITY_MESSAGE =\n 'useEphemeral: could not resolve a local context identity, so your own ' +\n 'presence cannot be filtered out. Pass includeSelf: true to accept this.';\n\n/**\n * How long after the last replayed entry (one carrying `ageMs`) the replay\n * window stays open before `peers` is reconciled down to what the replay\n * contained. Long enough to absorb a replay burst split across several SSE\n * frames/ticks, short enough that a swept peer does not linger.\n */\nconst REPLAY_RECONCILE_MS = 50;\n\n/**\n * Observe and publish ephemeral presence (cursors, typing, online) for a\n * context.\n *\n * ONE read path: the subscription. When a client subscribes, the node replays\n * that context's current presence to that connection as ordinary entries\n * before the live deltas start, so seeding and updating share a single shape\n * ({@link EphemeralEntry}) and a reconnect — `SseClient` auto-reconnects and\n * re-subscribes — re-seeds itself. There is no snapshot fetch and no\n * client-side reconciliation pass.\n *\n * Freshness is computed entirely from local clock deltas: a replayed entry is\n * current as of `Date.now() - ageMs`, a live delta as of `Date.now()`. No\n * cross-machine clock comparison is ever performed.\n *\n * No client-side TTL or heartbeat: the node sweeps at 7s and emits removals,\n * and re-publishes on your behalf every 2.5s. A replay is treated as\n * AUTHORITATIVE — see the replay-reconcile pass in the read effect — so a peer\n * swept while the SSE connection was down does not survive the reconnect.\n *\n * `error` is derived, not accumulated: standing conditions (no `ephemeral`\n * surface) are recomputed every render, one-shot async failures are latched\n * keyed by the context they happened in, and whether a latched failure is even\n * relevant (an unresolved identity when `includeSelf` is true) is decided at\n * read time. Nothing survives a context switch.\n */\nexport function useEphemeral<T>(\n contextId: string | null,\n options: UseEphemeralOptions<T> = {},\n): UseEphemeralResult<T> {\n const { includeSelf = false } = options;\n const { mero } = useMero();\n // Cast: the installed mero-js's `MeroJs` type predates `ephemeral` (see\n // `EphemeralClient` above), though it exists at runtime.\n const ephemeral = mero\n ? ((mero as unknown as { ephemeral?: EphemeralClient }).ephemeral ?? null)\n : null;\n\n const [peers, setPeers] = useState<Map<string, T>>(new Map());\n // The one latched async error (see `LatchedEphemeralError`). Not read\n // directly — `error` below derives what is actually reported from it.\n const [latchedError, setLatchedError] = useState<LatchedEphemeralError | null>(null);\n // The context the CURRENT render targets. Read by `setSourceError` so a\n // callback that resolves after a context switch can tell that its result is\n // no longer wanted without closing over anything but its own captured key.\n const contextKeyRef = useRef<string | null>(contextId);\n contextKeyRef.current = contextId;\n // `key` is the contextId captured when the failing operation was STARTED,\n // not when it settled. A late write from a context we have already left is\n // dropped here rather than being written and then hopefully cleared.\n const setSourceError = useCallback(\n (source: ErrorSource, err: Error, key: string | null) => {\n if (key !== contextKeyRef.current) return;\n setLatchedError({ contextKey: key, source, error: err });\n },\n [],\n );\n const clearSourceError = useCallback((source: ErrorSource, key: string | null) => {\n setLatchedError(prev =>\n prev && prev.source === source && prev.contextKey === key ? null : prev,\n );\n }, []);\n\n // DERIVED, never latched: \"this client has no `mero.ephemeral` surface\" is a\n // standing property of the current client, not an event. Recomputing it every\n // render is what makes it impossible to (a) leave it set after an upgraded\n // client arrives or (b) lose it to some other effect's clear — a context\n // switch, for instance, cannot hide a client that still has no surface.\n // Memoised only so the Error identity is stable while the condition holds.\n const surfaceError = useMemo(\n () => (mero && !ephemeral ? new Error(NO_EPHEMERAL_SURFACE_MESSAGE) : null),\n [mero, ephemeral],\n );\n\n // A latch is reported only if it belongs to the context being rendered, and\n // only if it is still MEANINGFUL: an unresolved local identity is an error\n // solely because self-filtering needs it, so opting into `includeSelf` makes\n // it a non-event — decided here, at read time, rather than by racing an\n // effect to clear it.\n const error =\n surfaceError ??\n (latchedError &&\n latchedError.contextKey === contextId &&\n !(latchedError.source === 'identity' && includeSelf)\n ? latchedError.error\n : null);\n // author -> local ms timestamp the entry is considered current as of.\n const receivedAtRef = useRef<Map<string, number>>(new Map());\n // `codec` and `initial` are held in refs, never in a dependency array:\n // `jsonCodec()` is a FACTORY, so `{ codec: jsonCodec() }` at the call site is\n // a fresh identity every render. As a dep it would tear down and re-create\n // the subscription on every render — and since every applied entry sets a\n // new Map (a new render), that is an unbounded resubscribe storm, each\n // resubscribe pulling a fresh presence replay. A codec swapped mid-flight is\n // not a real use case.\n const codecRef = useRef<Codec<T> | undefined>(options.codec);\n codecRef.current = options.codec;\n const initialRef = useRef<T | undefined>(options.initial);\n initialRef.current = options.initial;\n // This node's own context member key (device-level), resolved async. Never\n // compare this against an account id — that comparison silently never\n // matches, which is the classic self-echo bug.\n const selfRef = useRef<string | null>(null);\n const lastLocalRef = useRef<T | undefined>(options.initial);\n const pendingRef = useRef<T | undefined>(undefined);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n // Seeded to the mount time (not 0) so an isolated call shortly after mount\n // is correctly treated as part of the initial \"burst\" and trailing-edge\n // throttled, rather than bypassing the throttle because it looks like it's\n // arriving long after a (nonexistent) previous publish.\n const lastSentAtRef = useRef<number>(Date.now());\n // Open replay window: the authors seen since a replayed entry (one carrying\n // `ageMs`) last arrived. Null when no replay is in progress.\n const replaySeenRef = useRef<Set<string> | null>(null);\n const replayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const ageOf = useCallback((author: string): number | undefined => {\n const at = receivedAtRef.current.get(author);\n return at === undefined ? undefined : Date.now() - at;\n }, []);\n\n // Clear ALL per-context state synchronously the instant the target context\n // changes. Read state, so a previous context's peers don't keep rendering\n // until the new context's replay arrives — and write state, because a\n // queued publish would otherwise fire into the PREVIOUS context (its\n // `setTimeout` closure captured the old `publish`), and `lastLocalRef` would\n // shallow-merge the old context's fields into the first slice published in\n // the new one. Presence is app-defined data (cursor position, typing target),\n // so both are genuine cross-context writes, not cosmetic leaks.\n //\n // The latched error is dropped here as well, but purely as housekeeping (it\n // is what makes A -> B -> A not resurrect A's old failure). Correctness does\n // not rest on it: the latch carries its own `contextKey`, so an error from a\n // context we have left is neither written nor read regardless of whether this\n // effect ran. The standing surface condition is untouched — it is derived, so\n // it re-reports itself on the very next render if it is still true.\n useEffect(() => {\n setPeers(new Map());\n receivedAtRef.current = new Map();\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n pendingRef.current = undefined;\n lastLocalRef.current = initialRef.current;\n selfRef.current = null;\n setLatchedError(null);\n }, [contextId]);\n\n // Resolve THIS node's context member key — the same value the node stamps\n // as `author` on ephemeral entries.\n useEffect(() => {\n if (!mero || !contextId) return;\n // Captured at START. Everything this effect reports is tagged with it, so\n // a slow lookup that lands after a context switch cannot write into the\n // context we switched to.\n const key = contextId;\n let cancelled = false;\n // The RAW client's lookup, on purpose, unlike every other hook: \"self\" here\n // must be exactly the key the client behind `mero.ephemeral` stamps as\n // `author` on this node's entries, and that is what its own admin API\n // answers. The session `admin` answers for the session instead (an account\n // admin returns the account id), which names a different key and would\n // leave own echoes unfiltered.\n mero.admin\n .getContextIdentitiesOwned(contextId)\n .then(res => {\n if (cancelled) return;\n const self = res.identities?.[0] ?? null;\n selfRef.current = self;\n if (!self) {\n // Latched unconditionally — `includeSelf` is NOT consulted here.\n // Whether an unresolved identity matters is a question about the\n // CURRENT props, so it is answered where `error` is derived; asking\n // it here is what previously left the error stranded when\n // `includeSelf` flipped to true while resolution still failed.\n setSourceError('identity', new Error(COULD_NOT_RESOLVE_IDENTITY_MESSAGE), key);\n return;\n }\n // A later run of this effect (contextId change, includeSelf toggle)\n // resolved a self identity where an earlier run didn't — clear the\n // \"could not resolve\" error this effect itself raised.\n clearSourceError('identity', key);\n // Ordering race: the identity lookup and the subscription's presence\n // replay land independently, so a self entry can already be seeded in\n // `peers`. Retroactively drop it now that we know who \"self\" is.\n if (!includeSelf) {\n receivedAtRef.current.delete(self);\n setPeers(prev => {\n if (!prev.has(self)) return prev;\n const next = new Map(prev);\n next.delete(self);\n return next;\n });\n }\n })\n .catch((err: unknown) => {\n if (!cancelled) {\n setSourceError('identity', toError(err), key);\n }\n });\n return () => { cancelled = true; };\n // `mero` itself is a dep on purpose: a real MeroProvider memoizes its\n // context value, so `mero` only changes identity when the underlying\n // client is actually replaced (e.g. `allowedNodeUrls` changes) — and\n // that replacement is exactly when this effect must re-resolve the\n // local identity against the new client. Keying on presence alone\n // (`Boolean(mero)`) would silently keep resolving against a closed,\n // stale client instance.\n }, [mero, contextId, includeSelf, setSourceError, clearSourceError]);\n\n // The single read path. Subscribing makes the node replay this context's\n // current presence to this connection as ordinary entries, then stream live\n // deltas — so this one handler both seeds and updates, and an SSE reconnect\n // (which re-subscribes) re-seeds without any extra machinery.\n //\n // A REPLAY IS AUTHORITATIVE. The node replays exactly who is present right\n // now; anything we still hold that the replay does not mention is gone.\n // Without reconciling against it, a peer swept while the connection was down\n // is a permanent ghost: its removal event was delivered to nobody, and the\n // replay — which lists only survivors — will never mention it again. That\n // sweep happens inside `SseClient`'s auto-reconnect, so it does NOT re-run\n // this effect; reconciliation has to be driven by the entries themselves,\n // which is why it keys off `ageMs` (present only on replayed entries) rather\n // than off subscribe/unsubscribe. Clearing `peers` eagerly on subscribe would\n // also miss the reconnect case entirely — and would blank the UI on every\n // `includeSelf` toggle.\n //\n // The window closes `REPLAY_RECONCILE_MS` after the last replayed entry, and\n // live entries arriving while it is open count as present too, so a peer that\n // publishes mid-replay is never swept. A replayed entry that somehow arrives\n // after the window closed re-adds its author immediately — the failure mode\n // is a flicker, never a resurrected ghost or a permanent loss.\n useEffect(() => {\n if (!ephemeral || !contextId) return;\n\n const closeReplayWindow = () => {\n replayTimerRef.current = null;\n const seen = replaySeenRef.current;\n replaySeenRef.current = null;\n if (!seen) return;\n setPeers(prev => {\n let next: Map<string, T> | null = null;\n for (const author of prev.keys()) {\n if (seen.has(author)) continue;\n if (!next) next = new Map(prev);\n next.delete(author);\n receivedAtRef.current.delete(author);\n }\n return next ?? prev;\n });\n };\n\n const unsubscribe = ephemeral.subscribe<T>(\n contextId,\n entry => {\n const { author, state } = entry;\n if (entry.ageMs !== undefined) {\n // A replayed entry: (re)open the reconcile window and debounce its\n // close, so a replay burst split across frames counts as one replay.\n if (!replaySeenRef.current) replaySeenRef.current = new Set();\n if (replayTimerRef.current) clearTimeout(replayTimerRef.current);\n replayTimerRef.current = setTimeout(closeReplayWindow, REPLAY_RECONCILE_MS);\n }\n if (entry.removed || state === undefined) {\n replaySeenRef.current?.delete(author);\n receivedAtRef.current.delete(author);\n setPeers(prev => {\n if (!prev.has(author)) return prev;\n const next = new Map(prev);\n next.delete(author);\n return next;\n });\n return;\n }\n if (!includeSelf && author === selfRef.current) return;\n replaySeenRef.current?.add(author);\n // `ageMs` is absent on a live delta (current as of now) and present on\n // a replayed entry (current as of `now - ageMs`). `?? 0` — never a\n // truthiness test: an `ageMs` of 0 is a real, meaningful value.\n receivedAtRef.current.set(author, Date.now() - (entry.ageMs ?? 0));\n setPeers(prev => new Map(prev).set(author, state));\n },\n codecRef.current,\n );\n\n return () => {\n if (replayTimerRef.current) {\n clearTimeout(replayTimerRef.current);\n replayTimerRef.current = null;\n }\n replaySeenRef.current = null;\n unsubscribe();\n };\n // `ephemeral` itself is a dep on purpose — see the identity-resolution\n // effect above. A replaced client must re-subscribe against the new\n // client, not keep reading/writing through the old (possibly closed)\n // one. `codec` is deliberately NOT a dep — see `codecRef`.\n }, [ephemeral, contextId, includeSelf]);\n\n const publish = useCallback((value: T) => {\n if (!ephemeral || !contextId) return;\n // Captured at START, like the identity lookup's `key`: `ephemeral.set` is\n // not cancellable, so a rejection can land long after a context switch.\n // Tagging the write with the context it was issued for is what keeps that\n // failure out of the new context's error slot.\n const key = contextId;\n lastSentAtRef.current = Date.now();\n void ephemeral.set<T>(key, value, codecRef.current).then(\n () => clearSourceError('publish', key),\n (err: unknown) => setSourceError('publish', toError(err), key),\n );\n }, [ephemeral, contextId, setSourceError, clearSourceError]);\n\n /**\n * Publish your own presence.\n *\n * SHALLOW merge over the last locally-set value (starting from `initial`):\n * presence is one slot per author, so fields are not independent channels\n * and a bare replace would silently drop whatever you did not mention.\n * Nested objects are replaced wholesale, not deep-merged —\n * `setPresence({ cursor: { x: 1 } })` DROPS `cursor.y` if it was set\n * separately.\n *\n * Throttled on the trailing edge: rapid calls collapse into one publish\n * carrying the newest value, never the oldest queued one.\n */\n const setPresence = useCallback((partial: Partial<T>) => {\n const next = { ...(lastLocalRef.current ?? ({} as T)), ...partial } as T;\n lastLocalRef.current = next;\n\n const throttleMs = options.throttleMs ?? 30;\n if (throttleMs <= 0) {\n publish(next);\n return;\n }\n\n pendingRef.current = next;\n if (timerRef.current) return;\n const elapsed = Date.now() - lastSentAtRef.current;\n const delay = Math.max(throttleMs - elapsed, 0);\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n const queued = pendingRef.current;\n pendingRef.current = undefined;\n if (queued !== undefined) publish(queued);\n }, delay);\n }, [publish, options.throttleMs]);\n\n // Cancel a queued publish on unmount.\n useEffect(() => () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n }, []);\n\n return { peers, setPresence, ageOf, error };\n}\n\n/**\n * Shape accepted by the metadata-setter hooks — re-exported from mero-js so\n * callers have one canonical type. A `set*Metadata` call **replaces the whole\n * record**: `data` defaults to `{}` and wholly replaces the stored map; omit\n * `name` to keep the current name.\n */\nexport type SetMetadataInput = SetMetadataRequest;\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction mapApplicationContexts(contexts: Context[]): ApplicationContextRecord[] {\n return contexts.map((context) => ({\n contextId: context.id,\n applicationId: context.applicationId,\n }));\n}\n\nfunction useMountedRef() {\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n return mountedRef;\n}\n\n/** Options a mutation hook that can fail meaningfully accepts. */\nexport interface MutationOptions {\n /**\n * Rethrow a failed request from the action, after recording it in `error`\n * and `failure`.\n *\n * By default an action resolves `null` on failure, which a caller awaiting it\n * cannot tell apart from \"not connected\" — and a `catch` around it never\n * runs, so a refused join reads as a successful one. Set this when the\n * caller branches on the outcome.\n */\n throwOnError?: boolean;\n}\n\nfunction useAsyncMutation({ throwOnError = false }: MutationOptions = {}) {\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [failure, setFailure] = useState<ClassifiedError | null>(null);\n\n const run = useCallback(\n async <T,>(action: () => Promise<T>): Promise<T | null> => {\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n setFailure(null);\n }\n\n try {\n return await action();\n } catch (err) {\n if (mountedRef.current) {\n setError(toError(err));\n setFailure(classifyError(err));\n }\n // The original error, not the wrapped one: it carries the status.\n if (throwOnError) throw err;\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [mountedRef, throwOnError],\n );\n\n return { loading, error, failure, run, setError };\n}\n\n/**\n * Generic read resource: fetch + loading/error/data with a latest-request-wins\n * guard. `fetcher` is null when the read is disabled (missing args) — the\n * resource resets to `initialValue` and nothing is fetched. `deps` drive both\n * the refetch and a synchronous reset when they change, so a slow earlier\n * request can never overwrite a newer one. This is the staleness guard the read\n * hooks used to hand-roll (and mostly lacked), now in one place.\n */\nfunction useAsyncResource<T>(\n fetcher: (() => Promise<T>) | null,\n initialValue: T,\n deps: readonly unknown[],\n): { data: T; loading: boolean; error: Error | null; refetch: () => Promise<void> } {\n const mountedRef = useMountedRef();\n const [data, setData] = useState<T>(initialValue);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const reqRef = useRef(0);\n\n // fetcherRef is refreshed every render so refetch() always calls the latest\n // closure; initialRef captures the (per-hook constant) initial value once.\n // Neither is a dependency — adding them would break latest-request-wins.\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n const initialRef = useRef(initialValue);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n const fn = fetcherRef.current;\n if (!fn) {\n if (mountedRef.current && seq === reqRef.current) {\n setData(initialRef.current);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await fn();\n if (mountedRef.current && seq === reqRef.current) setData(result);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, deps);\n\n // Invalidate any in-flight request and drop the previous key's data DURING\n // RENDER, not in an effect. An effect leaves one render where `data` still\n // answers for the old inputs, and a consumer that persists what it sees\n // (a \"this member already has a name\" marker, say) makes that transient\n // staleness permanent.\n const prevDeps = useRef(deps);\n if (\n deps.length !== prevDeps.current.length ||\n deps.some((d, i) => !Object.is(d, prevDeps.current[i]))\n ) {\n prevDeps.current = deps;\n reqRef.current += 1;\n setData(initialRef.current);\n setError(null);\n }\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nfunction extractAliasContextId(value: unknown): string | null {\n if (typeof value === 'string') {\n return value;\n }\n\n if (!value || typeof value !== 'object') {\n return null;\n }\n\n if ('value' in value && typeof value.value === 'string') {\n return value.value;\n }\n\n if ('contextId' in value && typeof value.contextId === 'string') {\n return value.contextId;\n }\n\n return null;\n}\n\n/**\n * Execute RPC methods against a context.\n * Tracks loading/error state. Unmount-safe.\n */\nexport function useExecute(contextId: string | null, executorId: string | null) {\n const { mero, isDelegated } = useMero();\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useRef(true);\n\n useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const execute = useCallback(\n async <T = unknown>(method: string, params?: Record<string, unknown>): Promise<T | null> => {\n if (!mero || !contextId || !executorId) {\n // A delegated session with no client is one specific, ordinary state —\n // an account that has not been invited anywhere yet, so the cloud names\n // no relay for it — and it must not report as \"Not connected\", because\n // the account IS connected and re-authenticating cures nothing. The cure\n // is an invitation, so the message says so.\n if (mountedRef.current) {\n setError(\n new Error(\n !mero && isDelegated\n ? 'No relay for this account yet, so there is nowhere to send this write. ' +\n 'Redeeming an invitation admits the account to a namespace and gives it a ' +\n 'relay; reads and events resume with it.'\n : 'Not connected',\n ),\n );\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await mero.rpc.execute<T>({\n contextId,\n method,\n argsJson: params,\n executorPublicKey: executorId,\n });\n return result;\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err));\n if (mountedRef.current) setError(e);\n return null;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [mero, contextId, executorId, isDelegated],\n );\n\n return { execute, loading, error };\n}\n\n/** Event payload delivered to a `useSubscription` callback. */\nexport type SubscriptionEventData =\n | SseEventData\n | GroupMembershipEventData\n | GroupMigrationEventData;\n\n/** Ids to subscribe to. Either can be omitted, but not both. */\nexport interface SubscriptionInput {\n contextIds?: string[];\n groupIds?: string[];\n}\n\n/**\n * Subscribe to SSE events for context and/or group IDs.\n * StrictMode-safe: tracks the SseClient instance in a ref to avoid\n * double-connect on mount/unmount/remount cycles.\n */\nexport function useSubscription(\n contextIds: string[],\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n): void;\nexport function useSubscription(\n input: string[] | SubscriptionInput,\n callback: (event: SubscriptionEventData) => void,\n) {\n const { mero } = useMero();\n const callbackRef = useRef(callback);\n callbackRef.current = callback;\n\n const { contextIds = [], groupIds = [] } = Array.isArray(input)\n ? { contextIds: input, groupIds: [] as string[] }\n : input;\n\n const contextIdsKey = JSON.stringify(contextIds);\n const groupIdsKey = JSON.stringify(groupIds);\n\n useEffect(() => {\n if (!mero || (contextIds.length === 0 && groupIds.length === 0)) return;\n\n const sse = mero.events;\n\n const handler = (event: SubscriptionEventData) => {\n callbackRef.current(event);\n };\n\n sse.on('event', handler);\n sse.connect().catch(() => {});\n sse.subscribe({ contextIds, groupIds }).catch(() => {});\n\n return () => {\n sse.off('event', handler);\n };\n }, [mero, contextIdsKey, groupIdsKey]);\n}\n\n/**\n * Fetch contexts for the current node, optionally filtered by application ID.\n */\nexport function useContexts(applicationId?: string | null) {\n const { admin, isDelegated } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ApplicationContextRecord[]>(\n admin\n ? async () => {\n // A delegated session may list only its own contexts: the\n // per-application listing is node-wide, so a relay refuses it (403).\n // The caller-scoped `getContexts` carries each context's application,\n // so filter here instead.\n if (isDelegated) {\n // Across every relay this account uses: its namespaces may each be\n // served by a different one, and each relay lists only its own.\n const session = readDelegatedSession();\n const listed = session ? await listDelegatedContexts(session) : [];\n const own = listed.filter(\n (c) => !applicationId || c.applicationId === applicationId,\n );\n return mapApplicationContexts(own);\n }\n const response = applicationId\n ? await admin.getContextsForApplication(applicationId)\n : await admin.getContexts();\n return mapApplicationContexts(response.contexts ?? []);\n }\n : null,\n [],\n [admin, applicationId, isDelegated],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useApplicationContexts(applicationId?: string | null) {\n return useContexts(applicationId);\n}\n\nexport function useGroupMembers(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<ListGroupMembersResponseData | null>(\n admin && groupId ? () => admin.listGroupMembers(groupId) : null,\n null,\n [admin, groupId],\n );\n // `members` is a guaranteed array on the wire; `?? []` guards mocks / drift.\n return {\n members: data?.members ?? [],\n loading,\n error,\n refetch,\n };\n}\n\nexport function useGroupContexts(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupContextEntry[]>(\n admin && groupId ? () => admin.listGroupContexts(groupId) : null,\n [],\n [admin, groupId],\n );\n return { contexts: data, loading, error, refetch };\n}\n\nexport function useGroupInvitations() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createInvitation = useCallback(\n async (groupId: string, request?: CreateGroupInvitationRequest) => {\n if (!admin) {\n return null;\n }\n return run(() => admin.createGroupInvitation(groupId, request));\n },\n [admin, run],\n );\n\n return { createInvitation, loading, error };\n}\n\nexport function useJoinGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinGroup = useCallback(\n async (request: JoinGroupRequest) => {\n if (!admin) {\n return null;\n }\n return run(() => admin.joinGroup(request));\n },\n [admin, run],\n );\n\n return { joinGroup, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useGroupCapabilities(groupId?: string | null, memberId?: string | null) {\n const { admin } = useMero();\n const [capabilities, setCapabilitiesState] = useState<number | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Read+write hybrid (setCapabilities shares this state), so it keeps the\n // inline latest-request-wins guard rather than useAsyncResource.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !groupId || !memberId) {\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(null);\n setError(null);\n setLoading(false);\n }\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const response = await admin.getMemberCapabilities(groupId, memberId);\n if (mountedRef.current && seq === reqRef.current) {\n setCapabilitiesState(response.capabilities);\n }\n return response.capabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, memberId, admin, mountedRef]);\n\n useEffect(() => {\n reqRef.current += 1;\n setCapabilitiesState(null);\n setError(null);\n }, [groupId, memberId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n const setCapabilities = useCallback(\n async (nextCapabilities: number) => {\n if (!admin || !groupId || !memberId) {\n return null;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n await admin.setMemberCapabilities(groupId, memberId, { capabilities: nextCapabilities });\n if (mountedRef.current) {\n setCapabilitiesState(nextCapabilities);\n }\n return nextCapabilities;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n },\n [groupId, memberId, admin, mountedRef],\n );\n\n return { capabilities, loading, error, refetch, setCapabilities };\n}\n\nexport function useContextDiscovery(options: ContextDiscoveryOptions): ContextDiscoveryState {\n const { admin } = useMero();\n const [context, setContext] = useState<ApplicationContextRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n\n const knownContextIdsKey = JSON.stringify(options.knownContextIds ?? []);\n\n const discover = useCallback(async () => {\n if (!admin) {\n const notConnectedError = new Error('Not connected');\n if (mountedRef.current) {\n setError(notConnectedError);\n }\n return null;\n }\n const knownContextIds = new Set(options.knownContextIds ?? []);\n const pollIntervalMs = options.pollIntervalMs ?? 1000;\n const timeoutMs = options.timeoutMs ?? 30000;\n const deadline = Date.now() + timeoutMs;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n while (Date.now() <= deadline) {\n if (options.targetAlias) {\n const aliasMatch = extractAliasContextId(\n await admin.lookupContextAlias(options.targetAlias),\n );\n\n if (aliasMatch && !knownContextIds.has(aliasMatch)) {\n const discoveredFromAlias = {\n contextId: aliasMatch,\n applicationId: options.applicationId,\n };\n\n if (mountedRef.current) {\n setContext(discoveredFromAlias);\n }\n\n return discoveredFromAlias;\n }\n }\n\n const response = await admin.getContextsForApplication(options.applicationId);\n const contexts = mapApplicationContexts(response.contexts ?? []);\n const discovered = contexts.find(\n (applicationContext) => !knownContextIds.has(applicationContext.contextId),\n );\n\n if (discovered) {\n if (mountedRef.current) {\n setContext(discovered);\n }\n return discovered;\n }\n\n if (Date.now() + pollIntervalMs > deadline) {\n break;\n }\n\n await sleep(pollIntervalMs);\n }\n\n const timeoutError = new Error(\n `Timed out discovering a context for application ${options.applicationId}`,\n );\n\n if (mountedRef.current) {\n setContext(null);\n setError(timeoutError);\n }\n\n return null;\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current) {\n setContext(null);\n setError(errorValue);\n }\n return null;\n } finally {\n if (mountedRef.current) {\n setLoading(false);\n }\n }\n }, [\n knownContextIdsKey,\n admin,\n mountedRef,\n options.applicationId,\n options.knownContextIds,\n options.pollIntervalMs,\n options.targetAlias,\n options.timeoutMs,\n ]);\n\n const reset = useCallback(() => {\n if (mountedRef.current) {\n setContext(null);\n setError(null);\n setLoading(false);\n }\n }, [mountedRef]);\n\n return { context, loading, error, discover, reset };\n}\n\n// ---- Context CRUD Hooks ----\n\nexport function useCreateContext() {\n const { admin, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createContext = useCallback(\n async (request: CreateContextRequest) => {\n if (isDelegated) {\n // An account creates a context through the relay serving the namespace,\n // under a creation warrant (mero-js createDelegatedContext).\n const session = readDelegatedSession();\n if (!session || !request.groupId) return null;\n return run(() =>\n createDelegatedContext(session, {\n namespaceId: request.groupId!,\n applicationId: request.applicationId,\n serviceName: request.serviceName,\n contextSeed: request.contextSeed,\n name: request.name,\n initializationParams: request.initializationParams as number[] | undefined,\n }),\n );\n }\n if (!admin) return null;\n return run(() => admin.createContext(request));\n },\n [admin, run, isDelegated],\n );\n\n return { createContext, loading, error };\n}\n\nexport interface CreatePrivateContextRequest {\n readonly namespaceId: string;\n readonly applicationId: string;\n /** The accounts that share it with you, and nobody else — e.g. the other person of a DM. */\n readonly members: readonly string[];\n readonly initializationParams?: number[];\n}\n\n/**\n * Create a context only you and `members` are in (a DM, a small room): its own\n * restricted group in the namespace, members added directly — they are in the\n * namespace already, so nobody is invited. Same call on either connection:\n *\n * - a node login makes the group, adds the members and creates the context\n * with its own admin calls (as mero-chat's DMs do);\n * - an account has the relay serving the namespace do the same three steps,\n * each under its own warrant (mero-js createDelegatedContext).\n */\nexport function useCreatePrivateContext() {\n const { admin, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createPrivateContext = useCallback(\n async (request: CreatePrivateContextRequest): Promise<{ contextId: string } | null> => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n return run(() => createDelegatedPrivateContext(session, request));\n }\n if (!admin) return null;\n return run(async () => {\n const { groupId } = await admin.createGroupInNamespace(request.namespaceId, {\n visibility: 'restricted',\n });\n // The creator is the new group's admin already; the others join it here.\n await admin.addGroupMembers(groupId, {\n members: request.members.map((identity) => ({ identity, role: 'Member' })),\n });\n const { contextId } = await admin.createContext({\n applicationId: request.applicationId,\n groupId,\n initializationParams: request.initializationParams,\n });\n return { contextId };\n });\n },\n [admin, run, isDelegated],\n );\n\n return { createPrivateContext, loading, error };\n}\n\nexport function useDeleteContext() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteContext = useCallback(\n async (contextId: string) => {\n if (!admin) return null;\n return run(() => admin.deleteContext(contextId));\n },\n [admin, run],\n );\n\n return { deleteContext, loading, error };\n}\n\n/**\n * Join a context. `failure` says what kind of refusal a failed join was, and\n * whether trying again later could work; pass `{ throwOnError: true }` to have\n * `joinContext` reject instead of resolving `null`.\n */\nexport function useJoinContext(options: MutationOptions = {}) {\n const { admin } = useMero();\n const { loading, error, failure, run } = useAsyncMutation(options);\n\n const joinContext = useCallback(\n async (contextId: string) => {\n if (!admin) return null;\n return run(() => admin.joinContext(contextId));\n },\n [admin, run],\n );\n\n return { joinContext, loading, error, failure };\n}\n\nexport function useJoinSubgroupInheritance() {\n const { admin, isDelegated } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const joinSubgroupInheritance = useCallback(\n async (groupId: string) => {\n if (isDelegated) {\n const session = readDelegatedSession();\n if (!session) return null;\n // Joining an open subgroup yourself: a root op carrying your own credential.\n return run(async () => {\n await governRoot(session, groupId, memberJoinedOpenOp({ member: session.account, groupId, credential: session.credential }));\n // An account's identity in the subgroup is its device key: what its ops are signed with.\n const { publicKey } = await signerFromSecret(session.deviceSecret);\n return { groupId, memberPublicKey: publicKey, wasInherited: false };\n });\n }\n if (!admin) return null;\n return run(() => admin.joinSubgroupInheritance(groupId));\n },\n [admin, run, isDelegated],\n );\n\n return { joinSubgroupInheritance, loading, error };\n}\n\nexport function useContextGroup(contextId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n admin && contextId ? () => admin.getContextGroup(contextId) : null,\n null,\n [admin, contextId],\n );\n return { groupId: data, loading, error, refetch };\n}\n\n// ---- Group Info / Management Hooks ----\n\nexport function useGroupInfo(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<GroupInfo | null>(\n admin && groupId ? () => admin.getGroupInfo(groupId) : null,\n null,\n [admin, groupId],\n );\n return { groupInfo: data, loading, error, refetch };\n}\n\nexport function useDeleteGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteGroup = useCallback(\n async (groupId: string) => {\n if (!admin) return null;\n return run(() => admin.deleteGroup(groupId));\n },\n [admin, run],\n );\n\n return { deleteGroup, loading, error };\n}\n\nexport function useSyncGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const syncGroup = useCallback(\n async (groupId: string) => {\n if (!admin) return null;\n return run(() => admin.syncGroup(groupId));\n },\n [admin, run],\n );\n\n return { syncGroup, loading, error };\n}\n\n/**\n * Takes the invitee's signing KEY (bs58) - the one call on this resource that\n * does, because someone being added may have no account here yet. Every other\n * member call, including `useRemoveGroupMembers`, takes the ACCOUNT, so a value\n * round-tripped from an add is the wrong one to remove with.\n */\nexport function useAddGroupMembers() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const addGroupMembers = useCallback(\n async (groupId: string, request: AddGroupMembersRequest) => {\n if (!admin) return null;\n return run(() => admin.addGroupMembers(groupId, request));\n },\n [admin, run],\n );\n\n return { addGroupMembers, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useRemoveGroupMembers() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const removeGroupMembers = useCallback(\n async (groupId: string, request: RemoveGroupMembersRequest) => {\n if (!admin) return null;\n return run(() => admin.removeGroupMembers(groupId, request));\n },\n [admin, run],\n );\n\n return { removeGroupMembers, loading, error };\n}\n\n// ---- Namespace Hooks ----\n\nexport function useNamespaces() {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n admin ? () => admin.listNamespaces() : null,\n [],\n [admin],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useNamespace(namespaceId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace | null>(\n admin && namespaceId ? () => admin.getNamespace(namespaceId) : null,\n null,\n [admin, namespaceId],\n );\n return { namespace: data, loading, error, refetch };\n}\n\n/**\n * Who this node is: `accountId` is what member-addressing takes and what\n * `useGroupMembers` rows are keyed by — `publicKey` is the signing key and\n * addresses nobody. Both are 32-byte strings, so a swap fails silently.\n */\nexport function useNodeIdentity() {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<NodeIdentity | null>(\n admin ? () => admin.getNodeIdentity() : null,\n null,\n [admin],\n );\n return { identity: data, loading, error, refetch };\n}\n\nexport function useNamespacesForApplication(applicationId?: string | null) {\n const { admin, isDelegated } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<Namespace[]>(\n admin && applicationId\n ? isDelegated\n ? async () => {\n // The per-application listing is node-wide, so a relay refuses it to\n // an account; list its own namespaces on every relay and filter.\n const session = readDelegatedSession();\n const listed = session ? await listDelegatedNamespaces(session) : [];\n return listed.filter((ns) => ns.targetApplicationId === applicationId);\n }\n : () => admin.listNamespacesForApplication(applicationId)\n : null,\n [],\n [admin, applicationId, isDelegated],\n );\n return { namespaces: data, loading, error, refetch };\n}\n\nexport function useCreateNamespace() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespace = useCallback(\n async (request: CreateNamespaceRequest) => {\n if (!admin) return null;\n return run(() => admin.createNamespace(request));\n },\n [admin, run],\n );\n\n return { createNamespace, loading, error };\n}\n\nexport function useDeleteNamespace() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const deleteNamespace = useCallback(\n async (namespaceId: string) => {\n if (!admin) return null;\n return run(() => admin.deleteNamespace(namespaceId));\n },\n [admin, run],\n );\n\n return { deleteNamespace, loading, error };\n}\n\nexport function useCreateNamespaceInvitation() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createNamespaceInvitation = useCallback(\n async (\n namespaceId: string,\n request?: CreateNamespaceInvitationRequest,\n ): Promise<CreateNamespaceInvitationResponseData | CreateRecursiveInvitationResponseData | null> => {\n if (!admin) return null;\n return run(() => admin.createNamespaceInvitation(namespaceId, request));\n },\n [admin, run],\n );\n\n return { createNamespaceInvitation, loading, error };\n}\n\n/**\n * Join a namespace by invitation. `failure` says what kind of refusal a failed\n * join was, and whether trying again later could work; pass\n * `{ throwOnError: true }` to have `joinNamespace` reject instead of resolving\n * `null`.\n *\n * To follow an invitation link, prefer {@link useRedeemInvitation}: it also\n * recognises a join that landed although its request failed.\n */\nexport function useJoinNamespace(options: MutationOptions = {}) {\n const { admin } = useMero();\n const { loading, error, failure, run } = useAsyncMutation(options);\n\n const joinNamespace = useCallback(\n async (namespaceId: string, request: JoinNamespaceRequest) => {\n if (!admin) return null;\n return run(() => admin.joinNamespace(namespaceId, request));\n },\n [admin, run],\n );\n\n return { joinNamespace, loading, error, failure };\n}\n\n/**\n * Follow an invitation: join its namespace once, then check membership, and\n * report what happened as a {@link RedeemOutcome}.\n *\n * Unlike {@link useJoinNamespace}, a request that failed but whose join landed\n * anyway — the desktop proxy aborts at 30s, a join with no member online takes\n * longer — is `already-member`, not a failure. `shouldRetain(outcome)` from\n * mero-js says whether to keep the invitation for another attempt.\n *\n * `redeem` resolves `null` only when there is no client to send it through.\n */\nexport function useRedeemInvitation() {\n const { admin } = useMero();\n const mountedRef = useMountedRef();\n const [loading, setLoading] = useState(false);\n const [outcome, setOutcome] = useState<RedeemOutcome | null>(null);\n\n const redeem = useCallback(\n async (\n namespaceId: string,\n invitation: JoinNamespaceRequest['invitation'],\n options: { groupName?: string; teamName?: string } = {},\n ): Promise<RedeemOutcome | null> => {\n if (!admin) return null;\n if (mountedRef.current) {\n setLoading(true);\n setOutcome(null);\n }\n try {\n const result = await admin.redeemInvitation(namespaceId, invitation, options);\n if (mountedRef.current) setOutcome(result);\n return result;\n } finally {\n if (mountedRef.current) setLoading(false);\n }\n },\n [admin, mountedRef],\n );\n\n return { redeem, outcome, loading };\n}\n\nexport function useCreateGroupInNamespace() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const createGroupInNamespace = useCallback(\n async (namespaceId: string, request?: CreateGroupInNamespaceRequest) => {\n if (!admin) return null;\n return run(() => admin.createGroupInNamespace(namespaceId, request));\n },\n [admin, run],\n );\n\n return { createGroupInNamespace, loading, error };\n}\n\nexport function useNamespaceGroups(namespaceId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n admin && namespaceId ? () => admin.listNamespaceGroups(namespaceId) : null,\n [],\n [admin, namespaceId],\n );\n return { groups: data, loading, error, refetch };\n}\n\n// ---- Group Settings & Role Management ----\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useUpdateMemberRole() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const updateMemberRole = useCallback(\n async (groupId: string, identity: string, request: UpdateMemberRoleRequest) => {\n if (!admin) return null;\n return run(() => admin.updateMemberRole(groupId, identity, request));\n },\n [admin, run],\n );\n\n return { updateMemberRole, loading, error };\n}\n\nexport function useSetDefaultCapabilities() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setDefaultCapabilities = useCallback(\n async (groupId: string, request: SetDefaultCapabilitiesRequest) => {\n if (!admin) return null;\n return run(() => admin.setDefaultCapabilities(groupId, request));\n },\n [admin, run],\n );\n\n return { setDefaultCapabilities, loading, error };\n}\n\nexport function useSetSubgroupVisibility() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setSubgroupVisibility = useCallback(\n async (groupId: string, request: SetSubgroupVisibilityRequest) => {\n if (!admin) return null;\n return run(() => admin.setSubgroupVisibility(groupId, request));\n },\n [admin, run],\n );\n\n return { setSubgroupVisibility, loading, error };\n}\n\nexport function useDefaultCapabilities(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<number | null>(\n admin && groupId ? () => admin.getDefaultCapabilities(groupId) : null,\n null,\n [admin, groupId],\n );\n return { defaultCapabilities: data, loading, error, refetch };\n}\n\nexport function useSubgroupVisibility(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<string | null>(\n admin && groupId ? () => admin.getSubgroupVisibility(groupId) : null,\n null,\n [admin, groupId],\n );\n return { subgroupVisibility: data, loading, error, refetch };\n}\n\nexport function useSetTeeAdmissionPolicy() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setTeeAdmissionPolicy = useCallback(\n async (groupId: string, request: SetTeeAdmissionPolicyRequest) => {\n if (!admin) return null;\n return run(() => admin.setTeeAdmissionPolicy(groupId, request));\n },\n [admin, run],\n );\n\n return { setTeeAdmissionPolicy, loading, error };\n}\n\n// ---- Metadata Hooks ----\n\nexport function useSetGroupMetadata() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setGroupMetadata = useCallback(\n async (groupId: string, request: SetMetadataInput) => {\n if (!admin) return null;\n return run(() => admin.setGroupMetadata(groupId, request));\n },\n [admin, run],\n );\n\n return { setGroupMetadata, loading, error };\n}\n\n/**\n * Takes the member's ACCOUNT (64 hex), as `useGroupMembers` rows are keyed by\n * and `useNodeIdentity().identity?.accountId` returns - NOT a signing key.\n * Both are 32-byte strings, so passing a key names nobody and raises nothing.\n */\nexport function useSetMemberMetadata() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setMemberMetadata = useCallback(\n async (groupId: string, identity: string, request: SetMetadataInput) => {\n if (!admin) return null;\n return run(() => admin.setMemberMetadata(groupId, identity, request));\n },\n [admin, run],\n );\n\n return { setMemberMetadata, loading, error };\n}\n\nexport function useSetContextMetadata() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const setContextMetadata = useCallback(\n async (groupId: string, contextId: string, request: SetMetadataInput) => {\n if (!admin) return null;\n return run(() => admin.setContextMetadata(groupId, contextId, request));\n },\n [admin, run],\n );\n\n return { setContextMetadata, loading, error };\n}\n\nexport function useGroupMetadata(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<MetadataRecord | null>(\n admin && groupId ? () => admin.getGroupMetadata(groupId) : null,\n null,\n [admin, groupId],\n );\n return { metadata: data, loading, error, refetch };\n}\n\nexport function useMemberMetadata(groupId?: string | null, identity?: string | null) {\n const { admin } = useMero();\n const [metadata, setMetadata] = useState<MetadataRecord | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Drop the previous (group, member)'s record DURING RENDER. Clearing in an\n // effect leaves one render where `metadata` answers for the pair that was\n // asked about last, and a consumer that persists what it sees turns that\n // transient staleness into a permanent wrong answer.\n const prevKey = useRef<string | null>(null);\n const key = `${groupId ?? ''}:${identity ?? ''}`;\n if (prevKey.current !== null && prevKey.current !== key) {\n setMetadata(null);\n setError(null);\n }\n prevKey.current = key;\n\n // Shared fetch logic for the auto-mount effect and the explicit\n // refetch callable. The per-invocation `signal.aborted` flag covers\n // the response-during-unmount race cleanly without the global\n // mountedRef gate that — under StrictMode-like fast unmount/remount\n // cycles — could leave the hook stuck on `metadata = null` when an\n // in-flight response landed during cleanup and the followup mount's\n // useCallback referential identity hadn't changed enough to re-fire\n // the effect.\n const run = useCallback(\n async (signal: { aborted: boolean }) => {\n if (!admin || !groupId || !identity) {\n if (!signal.aborted) {\n setMetadata(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n if (!signal.aborted) {\n setLoading(true);\n setError(null);\n }\n try {\n const result = await admin.getMemberMetadata(groupId, identity);\n if (!signal.aborted) setMetadata(result);\n } catch (err) {\n if (!signal.aborted) setError(toError(err));\n } finally {\n if (!signal.aborted) setLoading(false);\n }\n },\n [admin, groupId, identity],\n );\n\n useEffect(() => {\n const signal = { aborted: false };\n void run(signal);\n return () => {\n signal.aborted = true;\n };\n }, [run]);\n\n // Explicit refetch — the caller's `await refetch()` resolves only\n // after state has been written (preserves the prior API contract;\n // call sites like `useMemberDisplayName.setName` rely on the new\n // value being readable from state after the await).\n const refetch = useCallback(async () => {\n const signal = { aborted: false };\n await run(signal);\n }, [run]);\n\n return { metadata, loading, error, refetch };\n}\n\n// ---- Group Signing Key, Upgrades & Hierarchy ----\n\nexport function useUpgradeGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const upgradeGroup = useCallback(\n async (groupId: string, request: UpgradeGroupRequest) => {\n if (!admin) return null;\n return run(() => admin.upgradeGroup(groupId, request));\n },\n [admin, run],\n );\n\n return { upgradeGroup, loading, error };\n}\n\n/**\n * Install a registry package version onto the node — the discrete \"Download\"\n * step an Updates flow runs before an `upgradeGroup`. Resolves the installed\n * application id (`InstallApplicationResponseData`). Downloading does not by\n * itself change what any group runs; pair it with a subsequent upgrade.\n */\nexport function useInstallFromRegistry() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n /**\n * ⚠️ NO `registryUrl` ARGUMENT ANY MORE. Since core's registry-only\n * application distribution, a node installs by `package@version` and\n * resolves the artifact against the registry IT is configured with — a\n * client cannot name one. mero-js dropped `installFromRegistry` for\n * `installApplication({ package, version })` to match, so the old third\n * argument had nowhere to go.\n */\n const installFromRegistry = useCallback(\n async (packageName: string, version: string) => {\n if (!admin) return null;\n return run(() => admin.installApplication({ package: packageName, version }));\n },\n [admin, run],\n );\n\n return { installFromRegistry, loading, error };\n}\n\n/**\n * Kick off a full state re-pull for a context — operator recovery for a\n * context stranded mid-sync. `force` re-pulls even when the node does not\n * flag the context as stranded.\n */\nexport function useResyncContext() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const resyncContext = useCallback(\n async (contextId: string, request: ResyncContextRequest = {}) => {\n if (!admin) return null;\n return run(() => admin.resyncContext(contextId, request));\n },\n [admin, run],\n );\n\n return { resyncContext, loading, error };\n}\n\nexport function useGroupUpgradeStatus(groupId?: string | null) {\n const { admin } = useMero();\n const [upgradeStatus, setUpgradeStatus] = useState<GroupUpgradeStatusResponseData>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus) so overlapping refetches\n // can't land out of order and overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !groupId) {\n if (mountedRef.current) {\n setUpgradeStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await admin.getGroupUpgradeStatus(groupId);\n if (mountedRef.current && seq === reqRef.current) {\n setUpgradeStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, admin, mountedRef]);\n\n // Clear stale status synchronously when the target group changes (and\n // invalidate any in-flight refetch), mirroring useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setUpgradeStatus(null);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { upgradeStatus, loading, error, refetch };\n}\n\nexport function useRetryGroupUpgrade() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const retryGroupUpgrade = useCallback(\n async (groupId: string) => {\n if (!admin) return null;\n return run(() => admin.retryGroupUpgrade(groupId));\n },\n [admin, run],\n );\n\n return { retryGroupUpgrade, loading, error };\n}\n\n/** Move `childGroupId` under a new parent. */\nexport function useReparentGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const reparentGroup = useCallback(\n async (childGroupId: string, request: ReparentGroupRequest) => {\n if (!admin) return null;\n return run(() => admin.reparentGroup(childGroupId, request));\n },\n [admin, run],\n );\n\n return { reparentGroup, loading, error };\n}\n\nexport function useSubgroups(groupId?: string | null) {\n const { admin } = useMero();\n const { data, loading, error, refetch } = useAsyncResource<SubgroupEntry[]>(\n admin && groupId ? () => admin.listSubgroups(groupId) : null,\n [],\n [admin, groupId],\n );\n return { subgroups: data, loading, error, refetch };\n}\n\n// ---- Context-Group Relationship ----\n\nexport function useDetachContextFromGroup() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const detachContextFromGroup = useCallback(\n async (groupId: string, contextId: string) => {\n if (!admin) return null;\n return run(() => admin.detachContextFromGroup(groupId, contextId));\n },\n [admin, run],\n );\n\n return { detachContextFromGroup, loading, error };\n}\n\n/**\n * Subscribe to a namespace's `GroupMigration` events, invoking `onEvent` per\n * frame and unsubscribing on unmount.\n *\n * A non-admin subscriber never sees `CascadeProgress`; core delivers that to\n * namespace admins only, so a UI must not wait on it to decide progress.\n */\n/**\n * Fallback poll cadence for `useMigrationStatus` when the SSE stream is\n * unavailable (no token, a proxy that buffers, an older node) and the caller\n * named no interval of its own. Chosen to match the heartbeat cadence that\n * migration facts actually arrive on; an explicit `pollIntervalMs` overrides it.\n */\nexport const DEFAULT_MIGRATION_POLL_INTERVAL_MS = 5000;\n\nexport function useMigrationEvents(\n namespaceId: string | null | undefined,\n onEvent: (event: GroupMigrationEventData) => void,\n): boolean {\n const { mero } = useMero();\n const mountedRef = useMountedRef();\n // Whether the stream is actually carrying frames. Callers use it to decide\n // whether they still need a fallback poll, so it must reflect the subscribe\n // ACTUALLY succeeding - not merely that we asked.\n const [live, setLive] = useState(false);\n // Held in a ref so a caller passing an inline arrow does not resubscribe on\n // every render - the subscription's lifetime is the namespace's, not the\n // callback identity's.\n const handlerRef = useRef(onEvent);\n handlerRef.current = onEvent;\n\n useEffect(() => {\n if (!mero || !namespaceId) return;\n const sse = mero.events;\n const unsubscribe = sse.onMigrationEvent((event) => handlerRef.current(event));\n // Sequential, and the result is recorded: connecting but failing to\n // subscribe is still a dead stream, and both used to be swallowed, which\n // left a caller unable to tell a live stream from a silent one.\n let cancelled = false;\n void (async () => {\n try {\n await sse.connect();\n await sse.subscribe({ groupIds: [namespaceId] });\n if (!cancelled && mountedRef.current) setLive(true);\n } catch {\n if (!cancelled && mountedRef.current) setLive(false);\n }\n })();\n return () => {\n cancelled = true;\n if (mountedRef.current) setLive(false);\n unsubscribe();\n };\n }, [mero, namespaceId, mountedRef]);\n\n return live;\n}\n\n/**\n * Migration-status rollup for a namespace (skew #3).\n *\n * Live: subscribes to the `GroupMigration` event family and re-reads on each\n * frame. It re-READS rather than folding the event's counters in, because the\n * rollup is recomputed from raw member rows and is the authoritative answer.\n * `pollIntervalMs` stays as the fallback when SSE is unavailable, and when the\n * caller names none it defaults to `DEFAULT_MIGRATION_POLL_INTERVAL_MS` for\n * exactly as long as the stream is down - so the panel can never sit silently\n * frozen with neither transport.\n * Derived counters are null-safe before the first load.\n */\nexport function useMigrationStatus(\n namespaceId?: string | null,\n options?: { pollIntervalMs?: number },\n) {\n const { admin } = useMero();\n const [status, setStatus] = useState<MigrationStatus | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Monotonic request token: only the latest in-flight request applies its\n // result, so an overlapping poll or a fast namespace change can't let a\n // stale response overwrite fresher data.\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!admin || !namespaceId) {\n if (mountedRef.current) {\n setStatus(null);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await admin.getMigrationStatus(namespaceId);\n if (mountedRef.current && seq === reqRef.current) {\n setStatus(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [namespaceId, admin, mountedRef]);\n\n // Clear stale state the instant the namespace changes, so the panel shows a\n // loading state rather than the previous namespace's data during the refetch.\n useEffect(() => {\n setStatus(null);\n setError(null);\n }, [namespaceId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Live updates. The frame is a signal, not the answer: it says something\n // moved, and the re-read is what stays authoritative. This runs BEFORE the\n // poll below because whether the stream is genuinely live is what decides\n // if a caller who named no interval needs a fallback poll at all.\n const sseLive = useMigrationEvents(namespaceId, () => void refetch());\n\n // An explicit interval always wins - a caller that asked to poll keeps\n // polling. When none was named, poll only while the stream is NOT live:\n // migration facts arrive by heartbeat gossip with no push transport of their\n // own, so with neither SSE nor an interval the panel loads once and then\n // silently never updates again, with no error to show for it.\n const pollIntervalMs =\n options?.pollIntervalMs ??\n (sseLive ? undefined : DEFAULT_MIGRATION_POLL_INTERVAL_MS);\n useEffect(() => {\n if (!pollIntervalMs || !admin || !namespaceId) return;\n const handle = setInterval(() => void refetch(), pollIntervalMs);\n return () => clearInterval(handle);\n }, [pollIntervalMs, admin, namespaceId, refetch]);\n\n const rollup: MigrationStatusRollup | null = status?.rollup ?? null;\n const members: MemberMigrationStatusEntry[] = status?.members ?? [];\n\n return {\n status,\n rollup,\n members,\n allMigrated: rollup?.allMigrated ?? false,\n /**\n * When this node watched the fleet converge, or `null`. Durable, unlike\n * `allMigrated`, which is recomputed from in-TTL heartbeats and lapses back\n * to false when a member simply goes quiet.\n */\n fleetCompletedAt: status?.fleetCompletedAt ?? null,\n membersPendingSignature: rollup?.membersPendingSignature ?? 0,\n /** Members whose migrate aborted (migration-check failed or apply errored). */\n failed: rollup?.failed ?? 0,\n loading,\n error,\n refetch,\n };\n}\n\n/**\n * Bundle-version skew (#2): reads the context's installed `applicationVersion`\n * (semver) and compares it to the app-declared `expected` build constant. Any\n * mismatch (either direction) is `isStale` → \"reload to update\". Subscribes to\n * `AppVersionChanged` so a live flip updates `appVersion` without a refetch.\n */\nexport function useAppVersion(contextId?: string | null, expected?: string) {\n const { mero, admin } = useMero();\n const [appVersion, setAppVersion] = useState<string | undefined>(undefined);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!admin || !contextId) {\n if (mountedRef.current) {\n setAppVersion(undefined);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const context = await admin.getContext(contextId);\n if (mountedRef.current && seq === reqRef.current) {\n setAppVersion(context.applicationVersion);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [contextId, admin, mountedRef]);\n\n // Reset on context change so a stale version isn't shown during the refetch.\n useEffect(() => {\n setAppVersion(undefined);\n setError(null);\n }, [contextId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !contextId) return;\n const off = mero.events.onAppVersionChanged((event: AppVersionChangedEvent) => {\n if (event.contextId !== contextId) return;\n if (mountedRef.current && event.toVersion) {\n // Invalidate any in-flight refetch so its (older) result can't clobber\n // this live update.\n reqRef.current += 1;\n setAppVersion(event.toVersion);\n }\n });\n return off;\n }, [mero, contextId, mountedRef]);\n\n const isStale = appVersion != null && expected != null && appVersion !== expected;\n\n return { appVersion, expected, isStale, loading, error, refetch };\n}\n\n/**\n * \"Is a newer version available?\" for an Updates view. Reads a package's\n * published versions from the registry and compares the newest to the running\n * `currentVersion` (e.g. a context's `applicationVersion`). `updateAvailable`\n * is true only when the registry's newest is strictly greater. This is the\n * registry-side check the admin acts on; gate rendering on admin status at the\n * call site. Pure read — fetching nothing until both `registryUrl` and\n * `packageName` are provided.\n */\nexport function useLatestVersion(\n registryUrl?: string | null,\n packageName?: string | null,\n currentVersion?: string | null,\n) {\n const { admin } = useMero();\n const [versions, setVersions] = useState<string[]>([]);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n if (!admin || !registryUrl || !packageName) {\n // Invalidate any in-flight request so a late response can't repopulate\n // stale versions for the previous package after the inputs were cleared.\n reqRef.current += 1;\n if (mountedRef.current) {\n setVersions([]);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n const seq = ++reqRef.current;\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n const result = await admin.getRegistryVersions(registryUrl, packageName);\n if (mountedRef.current && seq === reqRef.current) {\n setVersions(result);\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [admin, registryUrl, packageName, mountedRef]);\n\n // Clear stale versions the instant the package/registry changes.\n useEffect(() => {\n setVersions([]);\n setError(null);\n }, [registryUrl, packageName]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // getRegistryVersions returns newest-first, so [0] is the latest published.\n const latestVersion = versions[0] ?? null;\n const updateAvailable =\n latestVersion != null &&\n currentVersion != null &&\n compareSemver(latestVersion, currentVersion) > 0;\n\n return { versions, latestVersion, currentVersion, updateAvailable, loading, error, refetch };\n}\n\ninterface GroupAppVersion {\n /** Semver of the application the group currently targets (`null` until loaded). */\n version: string | null;\n /** The group's `targetApplicationId`. */\n applicationId: string | null;\n /** The installed blob differs from the one the group targets (see hook doc). */\n pendingApply: boolean;\n /** Only populated via the group-info path; `null` in the namespace path. */\n activeUpgrade: GroupUpgradeStatusResponseData;\n}\n\nconst EMPTY_GROUP_APP_VERSION: GroupAppVersion = {\n version: null,\n applicationId: null,\n pendingApply: false,\n activeUpgrade: null,\n};\n\n/** An appKey carries no \"pending\" signal when it is absent or all-zero. */\nfunction isZeroAppKey(appKey?: string): boolean {\n return !appKey || /^0+$/.test(appKey);\n}\n\n/**\n * What app version does this group run, and is there a downloaded-but-not-yet-\n * applied update? Replaces the appKey-vs-installed-blob comparison apps\n * otherwise hand-roll: `pendingApply` is true when the group's `appKey` (the\n * blob it targets) is present, non-zero, and differs from the blob actually\n * installed for its `targetApplicationId`. Deciding whether to render or gate on\n * that status (admin-only actions, etc.) is the call site's job.\n *\n * Resolution stays cheap: the group's record comes from `listNamespaces()` when\n * the id is a namespace, else from `getGroupInfo()`; `getApplication()` then\n * reads the installed version and blob. `activeUpgrade` is returned only when it\n * arrives for free on the group-info path (it is not fetched separately).\n * Subscribes to `AppVersionChanged` and refetches, since any version flip in the\n * workspace can make the rollup stale.\n */\nexport function useGroupAppVersion(groupId?: string) {\n const { mero, admin } = useMero();\n const [data, setData] = useState<GroupAppVersion>(EMPTY_GROUP_APP_VERSION);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const mountedRef = useMountedRef();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !groupId) {\n if (mountedRef.current) {\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n setLoading(false);\n }\n return;\n }\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n\n try {\n // Namespace-first resolution: a top-level group is a namespace; only\n // subgroups need the getGroupInfo fallback (which also carries\n // activeUpgrade, so we surface it without a third call).\n const namespaces = await admin.listNamespaces();\n const namespace = namespaces.find((entry) => entry.namespaceId === groupId);\n\n let appKey: string | undefined;\n let applicationId: string | null;\n let activeUpgrade: GroupUpgradeStatusResponseData = null;\n\n if (namespace) {\n appKey = namespace.appKey;\n applicationId = namespace.targetApplicationId;\n } else {\n const info = await admin.getGroupInfo(groupId);\n appKey = info.appKey;\n applicationId = info.targetApplicationId;\n activeUpgrade = info.activeUpgrade ?? null;\n }\n\n let version: string | null = null;\n let pendingApply = false;\n if (applicationId) {\n const { application } = await admin.getApplication(applicationId);\n version = application?.version ?? null;\n if (application && !isZeroAppKey(appKey)) {\n const installedHex = base58ToHex(application.blob.bytecode).toLowerCase();\n pendingApply = appKey!.toLowerCase() !== installedHex;\n }\n }\n\n if (mountedRef.current && seq === reqRef.current) {\n setData({ version, applicationId, pendingApply, activeUpgrade });\n }\n } catch (err) {\n const errorValue = toError(err);\n if (mountedRef.current && seq === reqRef.current) {\n setError(errorValue);\n }\n } finally {\n if (mountedRef.current && seq === reqRef.current) {\n setLoading(false);\n }\n }\n }, [groupId, admin, mountedRef]);\n\n // Clear stale state synchronously when the target group changes (and\n // invalidate any in-flight refetch). Mirrors useGroupUpgradeStatus.\n useEffect(() => {\n reqRef.current += 1;\n setData(EMPTY_GROUP_APP_VERSION);\n setError(null);\n }, [groupId]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n useEffect(() => {\n if (!mero?.events || !groupId) return;\n const off = mero.events.onAppVersionChanged(() => {\n if (mountedRef.current) void refetch();\n });\n return off;\n }, [mero, groupId, refetch, mountedRef]);\n\n return { ...data, loading, error, refetch };\n}\n\n/**\n * The caller's own identity-gated entries pending re-signature (skew #1).\n * `pending` is `pendingCount > 0` (from `count_my_pending`); `authorize()` runs\n * the one-tap `migrate_my_entries` convert and folds the resulting `remaining`\n * back into the count.\n */\nexport function useMyAuthoredMigration(contextId?: string | null) {\n const { mero } = useMero();\n const [summary, setSummary] = useState<MigrateMyEntriesSummary | null>(null);\n const [pendingCount, setPendingCount] = useState(0);\n const mountedRef = useMountedRef();\n const { loading, error, run } = useAsyncMutation();\n // Latest-request-wins token (see useMigrationStatus).\n const reqRef = useRef(0);\n\n const refresh = useCallback(async () => {\n if (!mero || !contextId) {\n if (mountedRef.current) setPendingCount(0);\n return;\n }\n const seq = ++reqRef.current;\n try {\n const count = await mero.rpc.countMyPending(contextId);\n if (mountedRef.current && seq === reqRef.current) setPendingCount(count);\n } catch {\n // best-effort count; leave the previous value on a transient failure\n }\n }, [mero, contextId, mountedRef]);\n\n // Clear stale per-context state synchronously when the target changes (and\n // invalidate any in-flight refresh), so the banner doesn't flash the previous\n // context's count until the new count resolves. Mirrors useMigrationStatus.\n useEffect(() => {\n reqRef.current += 1;\n setPendingCount(0);\n setSummary(null);\n }, [contextId]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const authorize = useCallback(async () => {\n if (!mero || !contextId) return null;\n const result = await run(() => mero.rpc.migrateMyEntries(contextId));\n if (result && mountedRef.current) {\n // Invalidate any in-flight refresh so a stale count can't overwrite the\n // authoritative post-convert remaining.\n reqRef.current += 1;\n setSummary(result);\n setPendingCount(result.remaining);\n }\n return result;\n }, [mero, contextId, run, mountedRef]);\n\n return {\n summary,\n pendingCount,\n pending: pendingCount > 0,\n authorize,\n loading,\n error,\n refresh,\n };\n}\n\n// ---- Blob Hooks ----\n\n/**\n * Options for the blob READ hooks.\n *\n * `contextId` is what picks the mode, and the two modes have wildly different\n * costs:\n *\n * - **omitted** — local-only read. The node answers from its own blob store\n * and returns immediately, or 404s.\n * - **supplied** — network discovery. The node probes that context's peers\n * (availability nodes first) for a holder. Core bounds the search by a ~30s\n * deadline, and for {@link useBlobUrl} the byte transfer is on top of that.\n *\n * So `loading` is load-bearing UI state on these hooks, not decoration: a\n * discovery read can plausibly spin for half a minute before it resolves\n * either way. Render a spinner (or a cancel affordance) accordingly.\n */\nexport interface BlobHookOptions {\n /** Context whose peers to probe. Omit for a local-only read. */\n contextId?: string;\n}\n\n/** Options for {@link useBlobUrl}. */\nexport interface UseBlobUrlOptions extends BlobHookOptions {\n /**\n * MIME type stamped on the `Blob` the object URL points at. The blob read\n * itself carries no type, and a peer-sourced answer has no `mimeType` at\n * all, so pass it when the consumer needs one (`<img>` sniffs; a download\n * `<a>` and an `<iframe>` do not).\n */\n type?: string;\n}\n\n/**\n * True when the failure is the node saying \"nobody has this blob\" (HTTP 404)\n * rather than a transport/auth failure.\n *\n * Duck-typed on `status` rather than `instanceof HTTPError`: a consumer app can\n * easily end up with two copies of mero-js (bundled + peer), and an\n * `instanceof` across that boundary silently reports false.\n */\nfunction isBlobNotFound(error: Error | null): boolean {\n return !!error && (error as { status?: unknown }).status === 404;\n}\n\n/**\n * A blob's presence and size, WITHOUT downloading it — the cheap half of the\n * blob surface, and the one to ask before pulling something large.\n *\n * `blobId` follows the same `string | null` convention as the other read\n * hooks: null/undefined means \"no read\", not \"read nothing\" — nothing is\n * fetched and `info` stays null.\n *\n * `hash` and `mimeType` on the result are genuinely optional: a peer probe\n * answers with presence and size only, so a discovery-sourced hit carries\n * neither. `info.source` (`'local' | 'peer'`, undefined on nodes that predate\n * the header) tells the two apart — do not treat a missing `mimeType` as a\n * malformed response.\n *\n * `notFound` distinguishes the legitimate \"no holder\" outcome (the node\n * answered 404) from a transport failure. `error` is set in BOTH cases — this\n * hook does not swallow the 404, it only labels it.\n *\n * Latency: immediate without `contextId`, up to core's ~30s discovery deadline\n * with one. See {@link BlobHookOptions}.\n */\nexport function useBlobInfo(blobId?: string | null, options?: BlobHookOptions) {\n const { admin } = useMero();\n const contextId = options?.contextId;\n const { data, loading, error, refetch } = useAsyncResource<GetBlobInfoResponseData | null>(\n admin && blobId\n ? () => admin.getBlobInfo(blobId, contextId ? { contextId } : undefined)\n : null,\n null,\n [admin, blobId, contextId],\n );\n\n return { info: data, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * A blob's bytes as an object URL, ready for `<img src>`, an `<a href>`\n * download, or an `<iframe>`.\n *\n * Lifecycle is handled here so the consumer never has to revoke: the URL is\n * revoked on unmount, and whenever `blobId`/`contextId`/`type` change. `url`\n * goes back to null synchronously on such a change, so a revoked URL is never\n * handed out as the current one — render off `url` and it is always live.\n *\n * A response for a superseded `blobId` is dropped before an object URL is even\n * created, so an out-of-order arrival can neither overwrite the newer result\n * nor leak.\n *\n * Latency: this is the expensive hook. Without `contextId` it is a local read;\n * with one it is discovery (core's ~30s deadline) PLUS the transfer of the\n * bytes. Prefer {@link useBlobInfo} to decide whether the download is worth\n * starting, and always render `loading`.\n *\n * `notFound` marks the node's 404 (\"no peer holds this\") apart from a\n * transport failure; `error` is set for both.\n */\nexport function useBlobUrl(blobId?: string | null, options?: UseBlobUrlOptions) {\n const { admin } = useMero();\n const contextId = options?.contextId;\n const type = options?.type;\n const mountedRef = useMountedRef();\n const [url, setUrl] = useState<string | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n // Latest-request-wins token, same shape as useAsyncResource's.\n const reqRef = useRef(0);\n // The URL currently handed out, held in a ref so revocation never depends on\n // a render having happened.\n const urlRef = useRef<string | null>(null);\n\n const revoke = useCallback(() => {\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n }, []);\n\n const refetch = useCallback(async () => {\n const seq = ++reqRef.current;\n if (!admin || !blobId) return;\n\n if (mountedRef.current) {\n setLoading(true);\n setError(null);\n }\n try {\n const bytes = await admin.getBlob(blobId, contextId ? { contextId } : undefined);\n // Check BEFORE creating the object URL: a loser allocates nothing, so\n // there is nothing to leak and nothing to overwrite the winner with.\n if (!mountedRef.current || seq !== reqRef.current) return;\n revoke();\n const objectUrl = URL.createObjectURL(new Blob([bytes], type ? { type } : undefined));\n urlRef.current = objectUrl;\n setUrl(objectUrl);\n } catch (err) {\n if (mountedRef.current && seq === reqRef.current) setError(toError(err));\n } finally {\n if (mountedRef.current && seq === reqRef.current) setLoading(false);\n }\n }, [admin, blobId, contextId, type, revoke, mountedRef]);\n\n // Invalidate the in-flight request and drop the current URL synchronously\n // when the inputs change, so the consumer never sees the previous blob's URL\n // (revoked or not) attributed to the new id.\n useEffect(() => {\n reqRef.current += 1;\n revoke();\n setUrl(null);\n setError(null);\n setLoading(false);\n }, [admin, blobId, contextId, type, revoke]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n // Final revoke on unmount. Separate from the input-change effect above so it\n // runs exactly once, on teardown, whatever the deps did.\n useEffect(() => revoke, [revoke]);\n\n return { url, notFound: isBlobNotFound(error), loading, error, refetch };\n}\n\n/**\n * Upload bytes to the node's blob store. Mutation-shaped, like the other\n * write hooks: `uploadBlob` resolves to `{ blobId, size }`, or null when the\n * client is absent or the call failed (read `error` for which).\n *\n * Pass `contextId` to announce the blob to that context, which is what lets\n * the context's other members later discover it with {@link useBlobUrl} /\n * {@link useBlobInfo}. Without it the blob is only readable on this node.\n */\nexport function useUploadBlob() {\n const { admin } = useMero();\n const { loading, error, run } = useAsyncMutation();\n\n const uploadBlob = useCallback(\n async (request: UploadBlobRequest) => {\n if (!admin) return null;\n return run(() => admin.uploadBlob(request));\n },\n [admin, run],\n );\n\n return { uploadBlob, loading, error };\n}\n","import type { ReactNode } from 'react';\nimport { useMyAuthoredMigration } from '../hooks';\n\nexport interface MigrationPendingBannerProps {\n /** Context whose authored entries to check / convert. */\n contextId: string;\n className?: string;\n /** Override the default prompt text. */\n children?: ReactNode;\n /** Fired once a convert leaves nothing pending (`remaining === 0`). */\n onMigrated?: () => void;\n}\n\n/**\n * Shows only when the current identity has entries below the target schema\n * (skew #1). A single button runs the one-tap `migrate_my_entries` convert and\n * the banner clears itself once nothing is pending.\n */\nexport function MigrationPendingBanner({\n contextId,\n className,\n children,\n onMigrated,\n}: MigrationPendingBannerProps) {\n const { pending, pendingCount, authorize, loading } = useMyAuthoredMigration(contextId);\n\n if (!pending) return null;\n\n const handleClick = async () => {\n const result = await authorize();\n if (result && result.remaining === 0) {\n onMigrated?.();\n }\n };\n\n const message =\n children ??\n `You have ${pendingCount} ${pendingCount === 1 ? 'entry' : 'entries'} to re-sign after a recent upgrade.`;\n\n return (\n <div className={className} data-testid=\"migration-pending-banner\" role=\"status\">\n <span>{message}</span>\n <button type=\"button\" onClick={handleClick} disabled={loading}>\n {loading ? 'Migrating…' : 'Migrate my data'}\n </button>\n </div>\n );\n}\n","import { useMigrationStatus } from '../hooks';\n\nexport interface MigrationAdminPanelProps {\n /** Namespace whose migration rollup to display. */\n namespaceId: string;\n /** Re-fetch interval; migration facts arrive via heartbeat gossip. */\n pollIntervalMs?: number;\n className?: string;\n}\n\n/**\n * Operator view of a namespace's migration rollup (skew #3): the cohort\n * counters, `membersPendingSignature`, and a per-member table. Read-only —\n * pair with the upgrade-trigger hooks to drive a migration.\n */\nexport function MigrationAdminPanel({ namespaceId, pollIntervalMs, className }: MigrationAdminPanelProps) {\n const { status, rollup, members, membersPendingSignature, failed, error } = useMigrationStatus(\n namespaceId,\n { pollIntervalMs },\n );\n\n // Surface a real failure rather than the misleading \"no status\" message.\n if (error && !status) {\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n Failed to load migration status: {error.message}\n </div>\n );\n }\n\n // Before the first successful fetch (initial paint or in-flight), show\n // loading — a successful read always yields a rollup, so a null status here\n // means \"not loaded yet\", never \"empty\".\n if (!status || !rollup) {\n return <div className={className} data-testid=\"migration-admin-panel\">Loading migration status…</div>;\n }\n\n return (\n <div className={className} data-testid=\"migration-admin-panel\">\n {error && (\n // A poll failed after data was already loaded — keep showing the last\n // good rollup but flag that it may be stale.\n <div data-testid=\"migration-status-error\" role=\"alert\">\n Could not refresh migration status: {error.message}\n </div>\n )}\n <dl>\n <div><dt>Target version</dt><dd>{status.targetVersion}</dd></div>\n <div><dt>Migrated</dt><dd>{rollup.migrated}</dd></div>\n <div><dt>In progress</dt><dd>{rollup.inProgress}</dd></div>\n <div><dt>Unknown</dt><dd>{rollup.unknown}</dd></div>\n <div><dt>Failed</dt><dd data-testid=\"migration-failed-count\">{failed}</dd></div>\n <div><dt>Total</dt><dd>{rollup.total}</dd></div>\n <div><dt>All migrated</dt><dd>{rollup.allMigrated ? 'yes' : 'no'}</dd></div>\n <div>\n <dt>Members pending signature</dt>\n <dd data-testid=\"members-pending-signature\">{membersPendingSignature}</dd>\n </div>\n </dl>\n <table>\n <thead>\n <tr><th>Peer</th><th>State</th><th>Schema</th><th>Pending</th><th>Reason</th></tr>\n </thead>\n <tbody>\n {members.map((m) => (\n <tr key={m.peer} data-testid=\"migration-member-row\">\n <td>{m.peer}</td>\n <td>{m.state}</td>\n <td>{m.report?.schemaVersion ?? '—'}</td>\n <td>{m.report?.authoredRemaining ?? '—'}</td>\n <td>{m.report?.migrationFailed ?? '—'}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n","/**\n * The delegated connect path, entered from an invitation instead of an account.\n *\n * `ConnectButtonAccount` enrols the device and then asks the cloud which relays\n * serve the ACCOUNT. For a first-time account that answer is `[]` and there is\n * nothing to connect to — correctly, since nothing yet serves an account that is\n * a member of nothing. This hook is the other door into the same connection: it\n * takes an invitation, resolves a relay from the NAMESPACE, presents the signed\n * join, and then connects through the node that carried it.\n *\n * It is `MeroContext`'s own `connectWithAccount` at the end, not a second\n * connection mechanism — the only difference is how the relay was found.\n */\n\nimport { useCallback, useState, useMemo } from 'react';\nimport type { SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport {\n bootstrapFromInvitation,\n type BootstrapResult,\n} from '@calimero-network/mero-js';\nimport {\n carryExecutorAccount,\n readDelegatedCredential,\n readDelegatedSession,\n rememberRelay,\n type DelegatedCredential,\n} from '@calimero-network/mero-js';\n\nexport interface UseDelegatedBootstrapOptions {\n /** Point at a cloud other than the hosted manager. For local rigs. */\n readonly cloudBaseUrl?: string;\n}\n\nexport interface UseDelegatedBootstrapResult {\n /** The enrolled account and its certificate, or `null` if none was ever held. */\n readonly credential: DelegatedCredential | null;\n /**\n * Whether this account is signed in with nowhere to write.\n *\n * True means: an enrolled credential is held and no relay is known for it, so\n * the account→relay lookup has nothing and an invitation is what changes that.\n * Being signed in is NOT the missing part — that is the whole point, since you\n * have to be signed in to be invited.\n *\n * False covers \"already has a relay\" and \"never enrolled\", which need the two\n * other entry points rather than this one.\n */\n readonly needsBootstrap: boolean;\n readonly running: boolean;\n /** The last attempt's outcome, kept so a UI can name the failing step. */\n readonly result: BootstrapResult | null;\n /**\n * Admit this account to the invitation's namespace and connect through the\n * admitting node.\n *\n * Resolves rather than throws for every expected refusal: the step names are\n * the point, because an empty intersection, an unreachable admitter and a\n * namespace with no fleet assignment need three different actions.\n */\n readonly bootstrap: (input: {\n readonly namespaceId: string;\n readonly invitation: SignedGroupOpenInvitation;\n /**\n * A node to present the join to, skipping the cloud lookup — an operator's,\n * a local rig's, or one a future invitation carries.\n */\n readonly nodeUrl?: string;\n /** The context the invitation is for, so its relay is known before any listing. */\n readonly contextId?: string;\n }) => Promise<BootstrapResult>;\n}\n\nexport function useDelegatedBootstrap(\n options: UseDelegatedBootstrapOptions = {},\n): UseDelegatedBootstrapResult {\n const { connectWithAccount, cloudBaseUrl: providerCloud } = useMero();\n const [running, setRunning] = useState(false);\n const [result, setResult] = useState<BootstrapResult | null>(null);\n\n // Read at render rather than held in state: the record is written by the\n // enrolment return in `ConnectButtonAccount`, in the same tab but outside\n // React's knowledge, so a cached copy would be stale exactly once — on the\n // load where it matters.\n //\n // Read every render, but the same object while its contents are the same:\n // a fresh parse each time made every callback below new on every render, and\n // an app with any of them in an effect's dependencies looped (\"Maximum update\n // depth exceeded\").\n const read = readDelegatedCredential();\n const credential = useMemo(\n () => read,\n // Keyed on the contents, not the parsed object.\n [read?.account, read?.credential, read?.deviceSecret],\n );\n // The stored record rather than the context's `nodeUrl`: that one is seeded\n // from `getNodeUrl()`, which can still hold a node URL from an earlier\n // node-login on this origin, and a stale value there would hide the very state\n // this reports.\n const relayUrl = readDelegatedSession()?.relayUrl ?? null;\n\n const cloudBaseUrl = options.cloudBaseUrl ?? providerCloud;\n const bootstrap = useCallback(\n async (input: {\n namespaceId: string;\n invitation: SignedGroupOpenInvitation;\n nodeUrl?: string;\n contextId?: string;\n }): Promise<BootstrapResult> => {\n const held = readDelegatedCredential();\n if (!held) {\n const failure: BootstrapResult = {\n ok: false,\n step: 'no-credential',\n reason:\n 'This tab holds no enrolled account, so there is no identity to admit. Enrol with ' +\n 'your account first — the invitation is then what gives it its first membership.',\n };\n setResult(failure);\n return failure;\n }\n setRunning(true);\n try {\n const outcome = await bootstrapFromInvitation({\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n credential: held,\n nodeUrl: input.nodeUrl,\n cloudBaseUrl,\n });\n setResult(outcome);\n // Connected only on a node that actually took the join. A session\n // installed after a refusal would look connected and refuse every write,\n // which is the failure this whole path exists to avoid.\n if (outcome.ok) {\n // Added to the account's relay map, never replacing it: the relays\n // that serve its other namespaces stay reachable.\n if (outcome.session.relayUrl) {\n rememberRelay(held.account, outcome.session.relayUrl, {\n namespaceId: input.namespaceId,\n contextId: input.contextId,\n });\n }\n connectWithAccount(carryExecutorAccount(readDelegatedSession(), outcome.session));\n }\n return outcome;\n } finally {\n setRunning(false);\n }\n },\n [cloudBaseUrl, connectWithAccount],\n );\n\n return {\n credential,\n needsBootstrap: credential !== null && relayUrl === null,\n running,\n result,\n bootstrap,\n };\n}\n","/**\n * The injected bridge, or `null` outside a capable launcher (SSR, plain tab,\n * PWA, or a launcher too old to inject it).\n */\nexport function getBridge() {\n if (typeof window === \"undefined\")\n return null;\n const b = window.__calimero_platform__;\n if (!b || typeof b !== \"object\")\n return null;\n const bridge = b;\n if (typeof bridge.version !== \"number\" ||\n !Array.isArray(bridge.capabilities) ||\n typeof bridge.invoke !== \"function\" ||\n typeof bridge.on !== \"function\") {\n return null;\n }\n return bridge;\n}\n/** Whether the current launcher advertises a given capability. */\nexport function hasCapability(name) {\n const bridge = getBridge();\n return bridge !== null && bridge.capabilities.includes(name);\n}\n","/**\n * Shareable deep-link generation.\n *\n * Links are ALWAYS HTTPS (`https://links.calimero.network/<slug>/<action>?…`),\n * never `calimero://` — the custom scheme is a device-local transport only. An\n * HTTPS link works everywhere: it opens the web/PWA app directly, and on a\n * device with the desktop installed + associated it hands off to the launcher.\n */\nconst DEFAULT_HOST = \"https://links.calimero.network\";\n/**\n * Build a canonical shareable link.\n *\n * @param slug the app slug (its manifest `handlers.slug`, e.g. `mero-chat`)\n * @param action the intent verb, e.g. `join`\n * @param params query params (values are URL-encoded)\n * @param host override the default host (no trailing slash needed)\n */\nexport function createLink(slug, action, params = {}, host = DEFAULT_HOST) {\n const base = host.replace(/\\/+$/, \"\");\n const path = `${encodeURIComponent(slug)}/${encodeURIComponent(action)}`;\n const url = new URL(`${base}/${path}`);\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, value);\n }\n return url.toString();\n}\n","/**\n * Durable pending-intent store.\n *\n * A deep-link intent (e.g. an invitation) must survive the app's own churn —\n * reload, auth redirect, even install→reopen — until the app explicitly acks\n * it. We persist captured intents to a single storage key (localStorage in the\n * browser; an injected Storage in tests), dedup by a content nonce so the same\n * link arriving from two sources (initial URL + a warm bridge event) is stored\n * once, and drop an intent only on `ack`.\n */\nconst STORAGE_KEY = \"calimero.platform.pendingIntents\";\n/** FNV-1a 32-bit — stable, dependency-free content hash for the dedup nonce. */\nfunction hashNonce(raw) {\n let h = 0x811c9dc5;\n for (let i = 0; i < raw.length; i++) {\n h ^= raw.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\nexport class PendingIntentStore {\n constructor(storage, now = () => Date.now()) {\n this.storage = storage;\n this.now = now;\n }\n read() {\n try {\n const raw = this.storage.getItem(STORAGE_KEY);\n if (!raw)\n return [];\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : [];\n }\n catch {\n return [];\n }\n }\n write(list) {\n try {\n this.storage.setItem(STORAGE_KEY, JSON.stringify(list));\n }\n catch {\n /* storage full / unavailable — the intent is best-effort */\n }\n }\n /** Capture an intent; idempotent by content nonce. Returns the stored entry. */\n capture(raw) {\n const nonce = hashNonce(raw);\n const list = this.read();\n const existing = list.find((i) => i.nonce === nonce);\n if (existing)\n return existing;\n const intent = { nonce, raw, capturedAt: this.now() };\n this.write([...list, intent]);\n return intent;\n }\n /** The oldest unacked intent, or null. */\n peek() {\n return this.read()[0] ?? null;\n }\n /** All unacked intents, oldest first. */\n all() {\n return this.read();\n }\n /** Drop an intent once the app has handled it. */\n ack(nonce) {\n this.write(this.read().filter((i) => i.nonce !== nonce));\n }\n}\n","/**\n * The deep-link controller: one place an app learns \"someone opened me with an\n * intent,\" no matter how it arrived.\n *\n * Sources it merges:\n * - the initial page URL (`location.href` — web/PWA cold open, or the launcher\n * appending `?invitation=…` to the app's frontend URL),\n * - the launcher bridge `deep-link` event (warm: app already open, a new link\n * routed to it),\n * - the PWA `launchQueue` (`targetURL`).\n *\n * All three funnel through the durable {@link PendingIntentStore}, so an intent\n * survives reload/auth/install and is deduped by content nonce (the same link\n * from URL + bridge fires a handler once). A handler registered LATE still\n * receives buffered intents. Each delivered intent carries `resolve()` — the\n * app calls it once handled, which acks the store so it never replays.\n */\n/**\n * Parse a captured raw string into `{ slug, action, params }`.\n *\n * `calimero://<slug>/<action>?…` is split by hand (NOT via `new URL().hostname`)\n * because non-special-scheme host parsing mangles dotted slugs like\n * `com.calimero.curb`. HTTPS/relative URLs use the URL parser; an app's own\n * root URL (`/?invitation=X`) yields null slug/action and just the params.\n */\nexport function parseIntent(raw) {\n const params = {};\n let slug = null;\n let action = null;\n try {\n if (/^calimero:\\/\\//i.test(raw)) {\n const rest = raw.slice(\"calimero://\".length);\n const qIdx = rest.indexOf(\"?\");\n const pathPart = qIdx >= 0 ? rest.slice(0, qIdx) : rest;\n const queryPart = qIdx >= 0 ? rest.slice(qIdx + 1) : \"\";\n const segs = pathPart.split(\"/\").filter(Boolean);\n slug = segs[0] ?? null;\n action = segs[1] ?? null;\n new URLSearchParams(queryPart).forEach((v, k) => (params[k] = v));\n }\n else {\n const url = new URL(raw, \"https://x.invalid/\");\n const segs = url.pathname.replace(/^\\/+|\\/+$/g, \"\").split(\"/\").filter(Boolean);\n slug = segs[0] ?? null;\n action = segs[1] ?? null;\n url.searchParams.forEach((v, k) => (params[k] = v));\n }\n }\n catch {\n /* unparseable — leave nulls / empty params */\n }\n return { slug, action, params };\n}\n/** Does a URL carry a deep-link signal (query or non-root path) worth capturing? */\nfunction hasIntentSignal(href) {\n try {\n const url = new URL(href, \"https://x.invalid/\");\n const segs = url.pathname.replace(/^\\/+|\\/+$/g, \"\").split(\"/\").filter(Boolean);\n return url.search.length > 1 || segs.length > 0;\n }\n catch {\n return false;\n }\n}\nexport class DeepLinkController {\n constructor(store, sources = {}) {\n this.store = store;\n this.handlers = new Set();\n this.delivered = new Set();\n this.unsubscribers = [];\n if (sources.location?.href && hasIntentSignal(sources.location.href)) {\n this.capture(sources.location.href);\n }\n if (sources.bridge) {\n const off = sources.bridge.on(\"deep-link\", (payload) => {\n const raw = extractRaw(payload);\n if (raw)\n this.capture(raw);\n });\n this.unsubscribers.push(off);\n }\n if (sources.launchQueue) {\n sources.launchQueue.setConsumer((p) => {\n if (p?.targetURL && hasIntentSignal(p.targetURL))\n this.capture(p.targetURL);\n });\n }\n }\n /** Register an intent handler; immediately replays buffered (unacked,\n * not-yet-delivered) intents. Returns an unsubscribe fn. */\n on(handler) {\n this.handlers.add(handler);\n for (const stored of this.store.all()) {\n if (!this.delivered.has(stored.nonce)) {\n this.delivered.add(stored.nonce);\n handler(this.toIntent(stored));\n }\n }\n return () => this.handlers.delete(handler);\n }\n /** Tear down source subscriptions + handlers. */\n dispose() {\n for (const off of this.unsubscribers.splice(0))\n off();\n this.handlers.clear();\n }\n capture(raw) {\n const stored = this.store.capture(raw);\n if (this.delivered.has(stored.nonce) || this.handlers.size === 0)\n return;\n this.delivered.add(stored.nonce);\n const intent = this.toIntent(stored);\n for (const handler of this.handlers)\n handler(intent);\n }\n toIntent(stored) {\n return {\n raw: stored.raw,\n ...parseIntent(stored.raw),\n resolve: () => this.store.ack(stored.nonce),\n };\n }\n}\n/** Pull a raw intent string out of a bridge `deep-link` payload (string or\n * `{raw}`/`{url}` object). */\nfunction extractRaw(payload) {\n if (typeof payload === \"string\")\n return payload;\n if (payload && typeof payload === \"object\") {\n const o = payload;\n if (typeof o.raw === \"string\")\n return o.raw;\n if (typeof o.url === \"string\")\n return o.url;\n }\n return null;\n}\n","// ── Capturing an invitation, however it arrived ───────────────────────────────\n//\n// Eleven Calimero apps once carried a near-identical copy of this file; this is\n// the one copy now.\n//\n// Three sources funnel into one controller:\n//\n// * the cold-open URL (web/PWA, or the desktop launcher appending\n// `?invitation=…` to this app's frontend URL),\n// * the launcher's warm `deep-link` bridge event (the app is already open),\n// * the PWA `launchQueue`.\n//\n// The SDK dedups them by content nonce, persists to localStorage so an intent\n// survives a reload and the auth redirect, replays to a handler that registers\n// late, and drops an intent only when the app acks it via `resolve()`.\n//\n// Two consequences worth stating, because hand-rolled versions got both wrong:\n//\n// 1. The landing route does not matter. A handler mounted anywhere sees the\n// intent, so an invitation cannot land on a page that cannot redeem it.\n// 2. Arriving before the session is ready is fine. The intent is buffered\n// until something asks for it, so there is no race with login.\n//\n// Storage note: `localStorage` can throw outright (Safari private mode, a\n// browser set to block site data). The store is built behind a probe so an\n// invitation still works in that session — it just does not survive a reload,\n// which is strictly better than failing to boot.\n\nimport {\n DeepLinkController,\n PendingIntentStore,\n createLink,\n getBridge,\n} from \"@calimero-network/mero-platform\";\n\n/** The action an invite link carries: `calimero://<package>/join?invitation=…`. */\nexport const JOIN_ACTION = \"join\";\n/** The query parameter every app's invite builder emits. */\nexport const INVITATION_PARAM = \"invitation\";\n\n/**\n * The link an inviter shares, for every app: `https://links.calimero.network/<slug>/join?invitation=…`.\n *\n * One shape, so one path gets it into the app. The links page opens the app's\n * frontend with the query appended (web, PWA, a cold desktop start), and a\n * desktop that is already running hands it over as a `deep-link` bridge event;\n * `primeInvitationCapture` listens to both. Nobody pastes it anywhere.\n *\n * `slug` is the app's deep-link handler, which for a Calimero app is its package id.\n * `extra` rides along beside the token, for an app whose link carries more\n * than the token (a display name, a target id).\n */\nexport function buildInviteLink(\n slug: string,\n token: string,\n extra: Record<string, string | undefined> = {},\n): string {\n const params: Record<string, string> = { [INVITATION_PARAM]: token };\n for (const [key, value] of Object.entries(extra)) {\n if (value !== undefined && value !== \"\") params[key] = value;\n }\n return createLink(slug, JOIN_ACTION, params);\n}\n\n/** One captured invitation, with the ack the app owes the store. */\nexport interface CapturedInvitation {\n /** The raw invitation token, ready to parse. */\n token: string;\n /** Every query parameter the link carried, the token included. */\n params: Record<string, string>;\n /** Ack it so the store stops replaying it. Call once handled OR declined. */\n resolve: () => void;\n /**\n * Whether to attempt the join without being asked.\n *\n * False once this invitation has spent its automatic attempts. The token is\n * still handed over — so a field can be prefilled and one click retries it —\n * but a link that can never join stops re-firing on every load.\n */\n autoJoin: boolean;\n}\n\ntype Listener = (invitation: CapturedInvitation) => void;\n\n/** Told whenever `peekInvitation()` would answer differently. */\nconst watchers = new Set<() => void>();\nfunction notifyWatchers(): void {\n for (const watcher of watchers) watcher();\n}\n\n/**\n * How many loads may auto-join one invitation before it needs a human.\n *\n * An unacked intent is replayed on every load by design, so that a transient\n * failure (node still starting, no member online yet) is retried rather than\n * lost. Without a ceiling a *permanent* failure is retried just as eagerly and\n * forever — which is what made every restart of the node re-fire a link that\n * had already been used.\n */\nexport const MAX_AUTO_JOIN_ATTEMPTS = 3;\n\nconst listeners = new Set<Listener>();\n/** Captured but not yet taken by a listener. Replayed to a late subscriber. */\nlet buffered: CapturedInvitation | null = null;\n/**\n * The captured invitation, held for the life of the session rather than\n * consumed on delivery — so code that is not a subscriber can still ask. Used\n * by bootstrap paths that need to know an invitation is inbound before they\n * decide where to send the user.\n */\nlet current: CapturedInvitation | null = null;\nlet controller: DeepLinkController | null = null;\n/** Namespaced per app so two apps on one origin cannot spend each other's budget. */\nlet attemptsKey = \"calimero:invitation-attempts\";\n/** The deep-link slugs that name this app; a `join` for any other slug is not ours. */\nlet ownSlugs: ReadonlySet<string> = new Set();\n\n/**\n * An in-memory Storage, for when the real one throws.\n *\n * Not a no-op: dedup within the session still works, so the same link arriving\n * from the URL and the bridge is handled once. Only cross-reload durability is\n * lost.\n */\nfunction memoryStorage(): Storage {\n const map = new Map<string, string>();\n return {\n get length() {\n return map.size;\n },\n clear: () => map.clear(),\n getItem: (k) => map.get(k) ?? null,\n key: (i) => [...map.keys()][i] ?? null,\n removeItem: (k) => void map.delete(k),\n setItem: (k, v) => void map.set(k, v),\n } as Storage;\n}\n\nfunction storage(): Storage {\n try {\n // Touched, not just referenced: some browsers expose `localStorage` and\n // throw only on access.\n const probe = \"__calimero_invite_probe__\";\n window.localStorage.setItem(probe, \"1\");\n window.localStorage.removeItem(probe);\n return window.localStorage;\n } catch {\n return memoryStorage();\n }\n}\n\nfunction readAttempts(): Record<string, number> {\n try {\n const parsed: unknown = JSON.parse(storage().getItem(attemptsKey) ?? \"{}\");\n return parsed && typeof parsed === \"object\"\n ? (parsed as Record<string, number>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction writeAttempts(attempts: Record<string, number>): void {\n try {\n storage().setItem(attemptsKey, JSON.stringify(attempts));\n } catch {\n /* unwritable storage — the cap degrades to per-session, never to a throw */\n }\n}\n\n/** Counts this load's attempt and reports whether it is still within the cap. */\nfunction spendAttempt(token: string): boolean {\n const attempts = readAttempts();\n const spent = attempts[token] ?? 0;\n if (spent >= MAX_AUTO_JOIN_ATTEMPTS) return false;\n attempts[token] = spent + 1;\n writeAttempts(attempts);\n return true;\n}\n\n/** Drops the ledger entry so an acked token cannot leak into it forever. */\nfunction forgetAttempts(token: string): void {\n const attempts = readAttempts();\n if (!(token in attempts)) return;\n delete attempts[token];\n writeAttempts(attempts);\n}\n\n/** The token in a raw deep-link payload, or `null` if it carries none. */\nexport function invitationFromRaw(raw: string): string | null {\n const direct = raw.trim();\n if (!direct) return null;\n // A bare token, or a URL/query carrying one.\n try {\n const params = new URLSearchParams(\n direct.includes(\"?\") ? direct.slice(direct.indexOf(\"?\") + 1) : direct,\n );\n const found = params.get(INVITATION_PARAM);\n if (found && found.trim()) return found.trim();\n } catch {\n /* not a query string — fall through to the bare-token reading */\n }\n if (direct.includes(\"=\") || direct.includes(\"?\")) return null;\n if (direct.startsWith(\"/\") || /^[a-z][a-z0-9+.-]*:/i.test(direct)) return null;\n return direct;\n}\n\n/** The current URL with the invitation parameter removed. */\nexport function urlWithoutInvitation(href: string): string {\n try {\n const url = new URL(href);\n if (!url.searchParams.has(INVITATION_PARAM)) return href;\n url.searchParams.delete(INVITATION_PARAM);\n return url.toString();\n } catch {\n return href;\n }\n}\n\nfunction deliver(invitation: CapturedInvitation): void {\n current = invitation;\n notifyWatchers();\n if (listeners.size === 0) {\n buffered = invitation;\n return;\n }\n for (const listener of listeners) listener(invitation);\n}\n\nfunction ensureController(): void {\n if (controller) return;\n controller = new DeepLinkController(new PendingIntentStore(storage()), {\n location: typeof window !== \"undefined\" ? window.location : null,\n bridge: getBridge(),\n launchQueue:\n typeof window !== \"undefined\"\n ? (window as unknown as { launchQueue?: never }).launchQueue ?? null\n : null,\n });\n\n controller.on((intent) => {\n // `join`, or no action at all — the launcher can append `?invitation=…` to\n // this app's own frontend URL, which parses to a null action with the\n // params intact. Anything else is somebody else's intent.\n //\n // An app page opened with an invitation on it (`/teams/t?invitation=…`)\n // parses as slug `teams`, action `t`: not a deep link at all, but still the\n // app's own URL carrying an invitation, so the parameter decides, not the path.\n if (\n intent.action !== null &&\n intent.action !== JOIN_ACTION &&\n !intent.params[INVITATION_PARAM]\n ) {\n return;\n }\n\n // A join addressed to another app. The launcher routes by slug, so this\n // takes a misrouted event or a link for app A opened inside app B — and\n // joining it would put this app's node into a namespace of an app it\n // cannot run. Acked so it does not replay; never offered.\n if (\n intent.action === JOIN_ACTION &&\n intent.slug !== null &&\n ownSlugs.size > 0 &&\n !ownSlugs.has(intent.slug)\n ) {\n intent.resolve();\n return;\n }\n\n const token = invitationFromRaw(intent.raw);\n if (!token) {\n // Nothing for us in it, but it is still ours to ack or it replays forever.\n intent.resolve();\n return;\n }\n\n // Hygiene, not bookkeeping — the store already remembers this. Done AFTER\n // capture, or the parameter would be gone before the controller read it.\n try {\n const cleaned = urlWithoutInvitation(window.location.href);\n if (cleaned !== window.location.href) {\n window.history.replaceState(null, \"\", cleaned);\n }\n } catch {\n /* no history API (or a non-browser test env) — the intent still stands */\n }\n\n deliver({\n token,\n params: { ...intent.params, [INVITATION_PARAM]: token },\n resolve: () => {\n forgetAttempts(token);\n // Acked before any listener took it (declined on the logged-out\n // invitation screen): it must not be replayed to the redemption\n // hook that subscribes once the person logs in.\n if (buffered?.token === token) buffered = null;\n intent.resolve();\n if (current?.token === token) {\n current = null;\n notifyWatchers();\n }\n },\n autoJoin: spendAttempt(token),\n });\n });\n}\n\n/**\n * Start listening for inbound invitation links.\n *\n * Call once before React mounts: the launcher appends `?invitation=…` to the\n * app's own URL, and a router would otherwise replace the URL before any\n * component could read it.\n *\n * `appKey` namespaces the attempt ledger. Two apps served from one origin (the\n * dev server, a preview deployment) would otherwise share it.\n *\n * `slug` is this app's deep-link slug (its package id). Given it, a `join` link\n * addressed to a different app is dropped instead of being offered here.\n */\nexport function primeInvitationCapture(\n appKey?: string,\n options: { slug?: string | readonly string[] } = {},\n): void {\n if (appKey) attemptsKey = `${appKey}:invitation-attempts`;\n const { slug } = options;\n if (slug) ownSlugs = new Set(typeof slug === \"string\" ? [slug] : slug);\n ensureController();\n}\n\n/**\n * Subscribe to invitations. Replays one already captured, so a component that\n * mounts after the link was opened still sees it.\n */\nexport function onInvitation(listener: Listener): () => void {\n ensureController();\n listeners.add(listener);\n if (buffered) {\n const pending = buffered;\n buffered = null;\n listener(pending);\n }\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * The captured invitation right now, without subscribing.\n *\n * Unlike `onInvitation`, this does not consume it and does not register a\n * listener — it answers \"is an invitation inbound?\" for code that only needs\n * to know, such as a bootstrap deciding where to land the user.\n */\nexport function peekInvitation(): CapturedInvitation | null {\n ensureController();\n return current;\n}\n\n/**\n * Be told when the captured invitation changes: one arrives, or it is acked.\n *\n * Unlike `onInvitation` this takes nothing: the invitation stays buffered for\n * whoever redeems it. It is for UI that only needs to know one is pending — the\n * logged-out invitation screen — and pairs with `peekInvitation` as a\n * `useSyncExternalStore` source.\n */\nexport function subscribeInvitation(watcher: () => void): () => void {\n ensureController();\n watchers.add(watcher);\n return () => {\n watchers.delete(watcher);\n };\n}\n\n/** Test seam: drop the controller and any buffered intent. */\nexport function resetInvitationCaptureForTests(): void {\n controller?.dispose();\n controller = null;\n listeners.clear();\n buffered = null;\n current = null;\n attemptsKey = \"calimero:invitation-attempts\";\n ownSlugs = new Set();\n // Watchers outlive a reset (a mounted component keeps its subscription);\n // they hear that the answer changed.\n notifyWatchers();\n}\n","import type { InviteFailureReason } from '@calimero-network/mero-js';\n\n/**\n * What to tell a person about a failed join, or `null` to show the node's own\n * message (an `unknown` failure has nothing better to offer).\n *\n * `noun` is what the app calls the thing being joined: \"team\", \"space\", \"vault\".\n * The reason is mero-js's (`redeemInvitation`), read off the node's status.\n */\nexport function describeInviteFailure(\n reason: InviteFailureReason,\n noun = 'team',\n): string | null {\n switch (reason) {\n case 'expired':\n return 'This invitation has expired. Ask for a new link.';\n case 'invalid':\n return \"This invitation link isn't valid. Ask for a new one.\";\n case 'refused':\n return `You can't join this ${noun} with this invitation. Ask an admin to invite you again.`;\n case 'signed-out':\n return 'Your session with your node has ended. Sign in again to finish joining.';\n case 'no-one-online':\n return `No one in this ${noun} is online to let you in yet. It will try again the next time you open the app.`;\n case 'node-unreachable':\n return \"Couldn't reach your node. Check that it is running, then try again.\";\n case 'unknown':\n return null;\n }\n}\n","/**\n * The set of namespaces this browser session has just joined and is still\n * waiting on.\n *\n * `sessionStorage`, not `localStorage`: the flag exists to cover the window\n * between a join returning and that namespace's state arriving. Surviving a\n * browser restart would mean gating a workspace that settled days ago.\n *\n * One key, shared by every app on the origin, and deliberately so. The value is\n * a namespace id — globally unique — so \"you just joined namespace X\" is true\n * for any app that can see X, not just the one that accepted the invite. The\n * watchdog in `useJoinSync` bounds how long a stale entry can matter, so an app\n * that sets the flag and navigates away cannot strand another one.\n */\nconst KEY = \"calimero:justJoinedNamespaces\";\n\n/** Reading storage can throw outright — Safari private mode, blocked site data. */\nfunction read(): Set<string> {\n try {\n if (typeof sessionStorage === \"undefined\") return new Set();\n const raw = sessionStorage.getItem(KEY);\n if (!raw) return new Set();\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed)\n ? new Set(parsed.filter((v): v is string => typeof v === \"string\"))\n : new Set();\n } catch {\n return new Set();\n }\n}\n\n/** In-page listeners: the invitation dialog waits on a namespace's flag clearing. */\nconst listeners = new Set<() => void>();\n\nfunction notify(): void {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n // One listener's failure must not keep the others from hearing it.\n }\n }\n}\n\n/**\n * Hear every mark and clear in this page. The flag is set by redemption (at\n * the app root) and cleared by whichever page reads the namespace's data\n * (`useJoinSync`), so this is how the one learns about the other without the\n * app threading page state up to its root.\n */\nexport function subscribeJustJoined(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\nfunction write(set: Set<string>): void {\n try {\n if (typeof sessionStorage === \"undefined\") return;\n sessionStorage.setItem(KEY, JSON.stringify([...set]));\n } catch {\n // Storage is a convenience here. A session that cannot persist the flag\n // simply does not get the gate; it must never break the join itself.\n }\n}\n\n/**\n * Call this the moment a join succeeds, before navigating. The app that reads\n * the flag is usually a different route from the one that accepted the invite.\n */\nexport function markNamespaceJustJoined(namespaceId: string): void {\n if (!namespaceId) return;\n const set = read();\n if (set.has(namespaceId)) return;\n set.add(namespaceId);\n write(set);\n notify();\n}\n\nexport function clearNamespaceJustJoined(namespaceId: string): void {\n const set = read();\n if (!set.delete(namespaceId)) return;\n write(set);\n notify();\n}\n\nexport function isNamespaceJustJoined(namespaceId: string | null): boolean {\n if (!namespaceId) return false;\n return read().has(namespaceId);\n}\n\n/** Test seam. Not part of the app-facing API. */\nexport function __readJustJoinedSet(): Set<string> {\n return read();\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { markNamespaceJustJoined } from \"./justJoined\";\n\nimport { onInvitation, type CapturedInvitation } from \"./capture\";\nimport {\n redeemInvitation,\n shouldRetain,\n type InviteFailureReason,\n type InviteRedeemer,\n type RedeemOutcome,\n} from \"@calimero-network/mero-js\";\n\n/** What the token carries, once the app's codec has read it. */\nexport interface ParsedInvitation {\n namespaceId: string;\n /** The invitation struct the node's join body expects. */\n invitation: unknown;\n /** The human name the inviter embedded, if any. */\n teamName?: string;\n}\n\n/**\n * Where redemption has got to, for rendering.\n *\n * `joining` is the state the apps used to lack: following an invite\n * link put the app on a page with no sign anything was happening, for as long\n * as the join took — up to 95s when no member of the namespace was online.\n */\nexport type InviteState =\n | { stage: \"idle\" }\n | { stage: \"awaiting-confirmation\"; teamName?: string }\n | { stage: \"joining\"; teamName?: string }\n | { stage: \"joined\"; namespaceId: string; teamName?: string }\n | { stage: \"already-member\"; namespaceId: string; teamName?: string }\n | {\n stage: \"failed\";\n /** The node's own words, or this package's for an unreadable link. */\n message: string;\n /** Why; `describeInviteFailure` turns it into something to show. */\n reason: InviteFailureReason;\n retryable: boolean;\n };\n\nexport interface UseInviteRedemptionOptions<P extends ParsedInvitation = ParsedInvitation> {\n /**\n * Read a raw token into its parts. Return `null` (or throw) if it is not a\n * usable invitation — the app owns this because the codecs differ slightly.\n * Extra fields the app returns (a vault name, a context id) come back as\n * `parsed` and are handed to `redeem`.\n */\n parse: (token: string, params: Record<string, string>) => P | null;\n /**\n * The two calls that differ between apps, for the standard join: join the\n * namespace, then check membership (mero-js `redeemInvitation`).\n */\n redeemer?: InviteRedeemer;\n /**\n * An app's own join flow, for one that does more than join the namespace\n * (enter a context, pick where to land). Takes precedence over `redeemer`.\n * Report a failure as a `failed` outcome rather than throwing; a throw is\n * read as an `unknown`, retryable failure.\n */\n redeem?: (parsed: P) => Promise<RedeemOutcome>;\n /**\n * Ask before joining, rather than joining on arrival.\n *\n * Not a stylistic choice, and deliberately per-app. Joining is a state\n * change: it puts you in someone else's namespace and gives them a peer that\n * syncs their data. For an app holding secrets — mero-pass is the clear case\n * — doing that on page load means a forwarded link, or a background tab that\n * refreshes, joins silently. Decoding is pure and local, so the scope can be\n * shown first and the join can need a click.\n *\n * With this set the state goes `awaiting-confirmation` and waits for\n * `accept()`; `decline()` acks the invitation so it stops coming back.\n *\n * On by default: an invitation reaches an app only by a link being opened,\n * and every app asks before it joins. Off only for a caller that has already\n * asked in its own words.\n */\n confirm?: boolean;\n /**\n * Called once, after a join has landed and before anything navigates. The\n * `already-member` case calls it too: the app still has to go and look at a\n * namespace it may never have opened.\n */\n onJoined?: (namespaceId: string, teamName?: string) => void;\n /**\n * Hold off until the app can actually join — a session, a resolved\n * application id. The invitation is buffered meanwhile, not dropped.\n */\n enabled?: boolean;\n}\n\nexport interface InviteRedemption<P extends ParsedInvitation = ParsedInvitation> {\n state: InviteState;\n /** The captured token, for prefilling a manual join field. */\n token: string | null;\n /** What the invitation names, available while confirming. */\n parsed: P | null;\n /** Go ahead with a join that is `awaiting-confirmation`. */\n accept: () => void;\n /** Decline it, and ack it so it does not come back. */\n decline: () => void;\n /** Retry the captured invitation by hand, past the automatic attempt cap. */\n retry: () => void;\n /** Take the result off the screen. */\n dismiss: () => void;\n}\n\n/**\n * Redeem an invitation that arrived by link, and report progress.\n *\n * Mount this once, high enough that it is not unmounted by routing. Capture is\n * process-wide and buffers, so mounting late is safe; being unmounted mid-join\n * only loses the on-screen state, never the invitation (it is acked on the\n * outcome, not on the render).\n */\nexport function useInviteRedemption<P extends ParsedInvitation = ParsedInvitation>({\n parse,\n redeemer,\n redeem,\n confirm = true,\n onJoined,\n enabled = true,\n}: UseInviteRedemptionOptions<P>): InviteRedemption<P> {\n const [state, setState] = useState<InviteState>({ stage: \"idle\" });\n const [token, setToken] = useState<string | null>(null);\n const [parsed, setParsed] = useState<P | null>(null);\n\n // Read through refs so a re-created `parse`/`redeemer`/`onJoined` — which is\n // every render, in most apps — does not resubscribe and re-fire the join.\n const parseRef = useRef(parse);\n parseRef.current = parse;\n const redeemerRef = useRef(redeemer);\n redeemerRef.current = redeemer;\n const redeemRef = useRef(redeem);\n redeemRef.current = redeem;\n const onJoinedRef = useRef(onJoined);\n onJoinedRef.current = onJoined;\n const confirmRef = useRef(confirm);\n confirmRef.current = confirm;\n\n /** Tokens already attempted this session, so nothing loops within one load. */\n const attempted = useRef<Set<string>>(new Set());\n /** The pending ack for the captured invitation, held for confirm/retry. */\n const pending = useRef<CapturedInvitation | null>(null);\n const parsedRef = useRef<P | null>(null);\n const alive = useRef(true);\n useEffect(() => {\n alive.current = true;\n return () => {\n alive.current = false;\n };\n }, []);\n\n /** Do the join and report the outcome. */\n const perform = useCallback(\n async (captured: CapturedInvitation, invitation: P) => {\n if (alive.current)\n setState({ stage: \"joining\", teamName: invitation.teamName });\n\n const outcome = await runRedeem(\n invitation,\n redeemRef.current,\n redeemerRef.current,\n );\n\n if (!shouldRetain(outcome)) captured.resolve();\n\n if (outcome.status === \"joined\" || outcome.status === \"already-member\") {\n // Before any navigation, so the gate is already set wherever the app\n // sends the user next.\n markNamespaceJustJoined(outcome.namespaceId);\n onJoinedRef.current?.(outcome.namespaceId, outcome.teamName);\n }\n\n if (!alive.current) return;\n setState(\n outcome.status === \"failed\"\n ? {\n stage: \"failed\",\n message: outcome.message,\n reason: outcome.reason,\n retryable: outcome.retryable,\n }\n : {\n stage: outcome.status,\n namespaceId: outcome.namespaceId,\n teamName: outcome.teamName,\n },\n );\n },\n [],\n );\n\n /** Parse, then either ask or go. */\n const begin = useCallback(\n (captured: CapturedInvitation) => {\n let invitation: P | null = null;\n try {\n invitation = parseRef.current(captured.token, captured.params);\n } catch {\n invitation = null;\n }\n if (!invitation?.namespaceId) {\n // Unreadable: retrying cannot help, so ack it rather than leave it to\n // replay forever.\n captured.resolve();\n if (alive.current) {\n setState({\n stage: \"failed\",\n message: \"That invitation could not be read.\",\n reason: \"invalid\",\n retryable: false,\n });\n }\n return;\n }\n\n parsedRef.current = invitation;\n if (alive.current) setParsed(invitation);\n\n if (confirmRef.current) {\n if (alive.current) {\n setState({\n stage: \"awaiting-confirmation\",\n teamName: invitation.teamName,\n });\n }\n return;\n }\n void perform(captured, invitation);\n },\n [perform],\n );\n\n useEffect(() => {\n if (!enabled) return;\n return onInvitation((captured) => {\n pending.current = captured;\n setToken(captured.token);\n if (attempted.current.has(captured.token)) return;\n // The attempt cap stops a link that cannot join from re-firing a join on\n // every load. Asking is not joining: a prompt is still owed, because a\n // link is the only way an invitation reaches the app.\n if (!captured.autoJoin && !confirmRef.current) return;\n attempted.current.add(captured.token);\n begin(captured);\n });\n }, [enabled, begin]);\n\n const accept = useCallback(() => {\n const captured = pending.current;\n const invitation = parsedRef.current;\n if (!captured || !invitation) return;\n void perform(captured, invitation);\n }, [perform]);\n\n const decline = useCallback(() => {\n // \"Not now\" IS handled. Without the ack the same prompt returns on every\n // load, which reads as the app nagging rather than as durability.\n pending.current?.resolve();\n setState({ stage: \"idle\" });\n }, []);\n\n const retry = useCallback(() => {\n const captured = pending.current;\n if (!captured) return;\n attempted.current.add(captured.token);\n // The person already said yes to this invitation: \"Try again\" joins, it\n // does not ask a second time. Only an invitation never read is begun anew.\n const invitation = parsedRef.current;\n if (invitation) void perform(captured, invitation);\n else begin(captured);\n }, [begin, perform]);\n\n const dismiss = useCallback(() => setState({ stage: \"idle\" }), []);\n\n return { state, token, parsed, accept, decline, retry, dismiss };\n}\n\n/** The app's own flow, or the standard join; a throw is an unknown failure. */\nasync function runRedeem<P extends ParsedInvitation>(\n invitation: P,\n redeem: ((parsed: P) => Promise<RedeemOutcome>) | undefined,\n redeemer: InviteRedeemer | undefined,\n): Promise<RedeemOutcome> {\n try {\n if (redeem) return await redeem(invitation);\n if (redeemer) return await redeemInvitation(invitation, redeemer);\n return {\n status: \"failed\",\n namespaceId: invitation.namespaceId,\n message: \"This app cannot redeem invitations: no redeemer is configured.\",\n reason: \"unknown\",\n retryable: false,\n };\n } catch (err) {\n return {\n status: \"failed\",\n namespaceId: invitation.namespaceId,\n message: err instanceof Error ? err.message : String(err),\n reason: \"unknown\",\n retryable: true,\n };\n }\n}\n","import { useEffect, useReducer, useRef } from \"react\";\nimport {\n clearNamespaceJustJoined,\n isNamespaceJustJoined,\n subscribeJustJoined,\n} from \"./justJoined\";\n\n/**\n * Base window for the gate. A governance op plus the namespace's own state\n * typically land in under a second on a healthy mesh; past this we give up\n * ONLY if nothing is actively in flight.\n */\nexport const JOIN_SYNC_WATCHDOG_MS = 30_000;\n/**\n * Hard ceiling. Bounds a genuinely stuck sync so the gate can never pin the UI\n * forever, even while something keeps reporting activity.\n */\nexport const JOIN_SYNC_MAX_MS = 120_000;\n/** How often the watchdog re-checks activity past the base window. */\nexport const JOIN_SYNC_POLL_MS = 2_000;\n\nexport interface JoinSyncOptions {\n /** The namespace being shown. `null` while nothing is selected. */\n namespaceId: string | null;\n /**\n * The app's own answer to \"has this namespace's data actually arrived?\" —\n * the one thing that cannot be shared, because every app reads a different\n * collection. Pass `true` once a real read has come back, INCLUDING an empty\n * one: \"no documents yet\" is a settled answer, and waiting for a non-empty\n * result would gate an genuinely empty workspace forever.\n */\n settled: boolean;\n /**\n * Optional: a sync is making forward progress. Holds the gate open past the\n * base window, up to the hard ceiling. Leave undefined if the app has no\n * such signal — the gate then simply expires at the base window.\n *\n * A stuck or backing-off sync must report `false`, not `true`: the point of\n * the base window is to stop waiting on something that is not coming.\n */\n active?: boolean;\n}\n\nexport interface JoinSyncState {\n /**\n * Show the \"syncing from peers\" affordance. True only for a namespace this\n * session just joined, whose data has not arrived, within the watchdog.\n */\n isSyncing: boolean;\n /** Drop the gate now — for a \"show me anyway\" control. */\n dismiss: () => void;\n}\n\n/**\n * Gate the window between \"you joined\" and \"your data is here\".\n *\n * Without it a just-joined namespace renders its ordinary empty state, and the\n * user cannot tell an empty workspace from one that is still arriving. That\n * ambiguity is the whole reason this exists: the two look identical, and the\n * honest one is the less alarming of the two.\n */\nexport function useJoinSync({\n namespaceId,\n settled,\n active,\n}: JoinSyncOptions): JoinSyncState {\n // The flag, read on every render, with a render on every mark or clear in the\n // page: a join can mark the namespace this page already shows (an invitation\n // to a workspace this node joined before), and a read keyed only on\n // `namespaceId` would never see that mark. Every change, not just a flip of\n // this namespace's flag: a clear and a re-mark in one batch leave the flag\n // where it was, and the clear below still has to run again.\n const [, storeChanged] = useReducer((n: number) => n + 1, 0);\n useEffect(() => {\n const unsubscribe = subscribeJustJoined(storeChanged);\n // A change between the first render and this subscription.\n storeChanged();\n return unsubscribe;\n }, []);\n const flagged = isNamespaceJustJoined(namespaceId);\n // When this namespace was first seen flagged, for the watchdog. Dropped once\n // the flag clears, so a later join of the same namespace gets a full window.\n const firstSeen = useRef<Map<string, number>>(new Map());\n if (namespaceId && flagged && !firstSeen.current.has(namespaceId)) {\n firstSeen.current.set(namespaceId, Date.now());\n } else if (namespaceId && !flagged) {\n firstSeen.current.delete(namespaceId);\n }\n // Read from a ref inside the watchdog so a change in activity does not\n // restart the timer — which would let a chatty sync postpone the deadline\n // indefinitely.\n const activeRef = useRef(active);\n activeRef.current = active;\n\n // Settled is the happy path: the data arrived, so stop gating and forget the\n // namespace. Runs before the watchdog ever fires in the normal case.\n //\n // After every render, reading the store itself: a mark that lands in the\n // same batch as this clear (an app's own mark, then the redemption's) leaves\n // `flagged` true throughout, so an effect keyed on it would not run again and\n // the flag would stay set. The clear notifies, which renders again, so this\n // stops once the flag is gone.\n useEffect(() => {\n if (!namespaceId || !settled || !isNamespaceJustJoined(namespaceId)) return;\n clearNamespaceJustJoined(namespaceId);\n });\n\n useEffect(() => {\n if (!namespaceId || !flagged || settled) return;\n const since = firstSeen.current.get(namespaceId) ?? Date.now();\n let timer: ReturnType<typeof setTimeout>;\n const check = () => {\n const elapsed = Date.now() - since;\n const giveUp =\n elapsed >= JOIN_SYNC_MAX_MS ||\n (elapsed >= JOIN_SYNC_WATCHDOG_MS && !activeRef.current);\n if (giveUp) {\n clearNamespaceJustJoined(namespaceId);\n return;\n }\n timer = setTimeout(check, JOIN_SYNC_POLL_MS);\n };\n timer = setTimeout(check, JOIN_SYNC_WATCHDOG_MS);\n return () => clearTimeout(timer);\n }, [namespaceId, flagged, settled]);\n\n return {\n isSyncing: flagged && !settled,\n dismiss: () => {\n if (!namespaceId) return;\n clearNamespaceJustJoined(namespaceId);\n },\n };\n}\n","/**\n * The one invitation prompt: ask, join, wait for the data, done.\n *\n * Mount it once at the app root with the app's `useInviteRedemption()`. It\n * renders nothing until an invitation link has been opened, then walks the\n * person through every stage in one place:\n *\n * awaiting-confirmation \"Join “Design team”?\" Join / Not now\n * joining \"Joining “Design team”…\" (cannot be closed)\n * syncing \"Syncing “Design team”…\" (cannot be closed; once\n * slow: Continue in background)\n * ready \"You're in “Design team”\" closes by itself\n * already-member \"You're already in …\" Done\n * failed the reason, in plain words Try again / Close\n *\n * `syncing` is the stage the apps used to skip: a join returns before the\n * namespace's data has arrived, and an empty page then looks exactly like an\n * empty workspace. It lasts while the namespace's just-joined flag is set\n * (`markNamespaceJustJoined`, set by redemption) and ends when the page that\n * reads the data clears it (`useJoinSync` with `settled`), when the app says so\n * here (`synced`), or at the watchdog's hard ceiling. So the app root needs no\n * page state threaded up to it: the page that knows says so through the flag.\n *\n * Joining and syncing are not closed by a stray click or Escape: leaving\n * mid-sync lands on a page whose data has not arrived. While the dialog is up\n * the rest of the page is `inert`, so nothing behind it takes a click or focus.\n * A sync slow enough to trip the watchdog offers \"Continue in background\"; the\n * dialog then keeps the flag's ceiling running, so a page that never mounts\n * cannot leave the namespace flagged.\n *\n * Test ids are the contract the apps' two-node journeys drive: `invite-prompt`\n * (with `data-stage`), `invite-accept`, `invite-decline`, `invite-retry`,\n * `invite-continue`, `invite-error`.\n */\nimport {\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n useSyncExternalStore,\n type KeyboardEvent as ReactKeyboardEvent,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { describeInviteFailure } from './describeInviteFailure';\nimport {\n clearNamespaceJustJoined,\n isNamespaceJustJoined,\n subscribeJustJoined,\n} from './justJoined';\nimport type { InviteRedemption } from './useInviteRedemption';\nimport { JOIN_SYNC_MAX_MS, JOIN_SYNC_WATCHDOG_MS } from './useJoinSync';\n\n/** How long \"You're in\" stays up before the dialog closes by itself. */\nexport const INVITATION_READY_MS = 1_200;\n\nexport interface InvitationDialogProps {\n /** The app's `useInviteRedemption(...)`. */\n redemption: InviteRedemption;\n /** What the app calls the thing being joined: \"team\", \"workspace\", \"vault\". */\n noun?: string;\n /** Shown above the title, so a person knows which app is asking. */\n appName?: string;\n /**\n * Optional: the joined namespace's data has been read, empty or not. For an\n * app whose root already knows; others leave this out and let the page that\n * reads the data clear the flag with `useJoinSync({ settled })`.\n */\n synced?: boolean;\n /**\n * Optional: the app's own words under the question, for an invitation whose\n * grant needs spelling out (\"Joining gives you this vault and the rest of\n * the team it belongs to.\").\n */\n detail?: string;\n /** Optional: which step a slow join is on, shown while joining. */\n status?: string | null;\n}\n\n/** The stage the dialog shows: redemption's, plus the wait for the data. */\nexport type InvitationDialogStage =\n | 'awaiting-confirmation'\n | 'joining'\n | 'syncing'\n | 'ready'\n | 'already-member'\n | 'failed';\n\nfunction useJustJoined(namespaceId: string | null): boolean {\n return useSyncExternalStore(\n subscribeJustJoined,\n () => isNamespaceJustJoined(namespaceId),\n () => false,\n );\n}\n\nexport function InvitationDialog({\n redemption,\n noun = 'team',\n appName,\n synced,\n detail,\n status,\n}: InvitationDialogProps) {\n const { state, accept, decline, retry, dismiss } = redemption;\n const joinedId = state.stage === 'joined' ? state.namespaceId : null;\n // The namespace still being waited on, kept after \"Continue in background\"\n // takes the redemption back to idle: the wait goes on without the dialog.\n const [backgroundId, setBackgroundId] = useState<string | null>(null);\n useEffect(() => {\n if (joinedId) setBackgroundId(joinedId);\n }, [joinedId]);\n const waitingId = joinedId ?? backgroundId;\n const flagged = useJustJoined(waitingId);\n const stillSyncing = joinedId !== null && flagged;\n useEffect(() => {\n if (!joinedId && backgroundId && !flagged) setBackgroundId(null);\n }, [joinedId, backgroundId, flagged]);\n\n // The app's own word that the data is here ends the wait just as the page's\n // `useJoinSync` would.\n useEffect(() => {\n if (waitingId && flagged && synced) clearNamespaceJustJoined(waitingId);\n }, [waitingId, flagged, synced]);\n\n // A sync that never settles must not pin the dialog: past the watchdog it\n // says so, and at the hard ceiling it lets go (the flag too, so the page's\n // own banner does not outlive it).\n const [slow, setSlow] = useState(false);\n // Keyed on the namespace, not on whether the dialog shows it, so sending it\n // to the background neither restarts nor drops the ceiling.\n useEffect(() => {\n setSlow(false);\n if (!waitingId || !flagged) return;\n const slowTimer = setTimeout(() => setSlow(true), JOIN_SYNC_WATCHDOG_MS);\n const ceiling = setTimeout(\n () => clearNamespaceJustJoined(waitingId),\n JOIN_SYNC_MAX_MS,\n );\n return () => {\n clearTimeout(slowTimer);\n clearTimeout(ceiling);\n };\n }, [waitingId, flagged]);\n\n const stage: InvitationDialogStage | null =\n state.stage === 'idle'\n ? null\n : state.stage === 'joined'\n ? stillSyncing\n ? 'syncing'\n : 'ready'\n : state.stage;\n\n // \"You're in\" closes by itself; everything else waits for the person.\n useEffect(() => {\n if (stage !== 'ready') return;\n const t = setTimeout(dismiss, INVITATION_READY_MS);\n return () => clearTimeout(t);\n }, [stage, dismiss]);\n\n const titleId = useId();\n const bodyId = useId();\n const overlayRef = useRef<HTMLDivElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n const primaryRef = useRef<HTMLButtonElement>(null);\n\n // Modal for real: the page behind takes no click, focus or screen-reader\n // visit while the dialog is up, including what the app mounts meanwhile.\n const open = stage !== null;\n useEffect(() => {\n const overlay = overlayRef.current;\n if (!open || !overlay || typeof MutationObserver === 'undefined') return;\n const made = new Set<Element>();\n const shut = (el: Element) => {\n if (el === overlay || el.hasAttribute('inert')) return;\n if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE') return;\n el.setAttribute('inert', '');\n made.add(el);\n };\n Array.from(document.body.children).forEach(shut);\n const observer = new MutationObserver((records) => {\n for (const record of records) record.addedNodes.forEach((n) => n instanceof Element && shut(n));\n });\n observer.observe(document.body, { childList: true });\n return () => {\n observer.disconnect();\n made.forEach((el) => el.removeAttribute('inert'));\n };\n }, [open]);\n\n // Focus follows the stage, so a keyboard user lands on what to do next.\n useEffect(() => {\n if (!stage) return;\n (primaryRef.current ?? dialogRef.current)?.focus();\n }, [stage]);\n\n /**\n * Closing means what the stage says it means. Mid-join and mid-sync it means\n * nothing: a stray click must not drop the person on a page whose data has\n * not arrived. A slow sync has its own, deliberate, button.\n */\n const close = useCallback(() => {\n if (stage === 'awaiting-confirmation') decline();\n else if (stage && stage !== 'joining' && stage !== 'syncing') dismiss();\n }, [stage, decline, dismiss]);\n\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.key === 'Escape') {\n event.stopPropagation();\n close();\n return;\n }\n if (event.key !== 'Tab' || !dialogRef.current) return;\n // Keep focus inside while the dialog is up.\n const focusable = dialogRef.current.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), [href], [tabindex]:not([tabindex=\"-1\"])',\n );\n if (focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n if (!stage || typeof document === 'undefined') return null;\n\n const teamName = 'teamName' in state ? state.teamName : undefined;\n const named = teamName ? `“${teamName}”` : `this ${noun}`;\n const busy = stage === 'joining' || stage === 'syncing';\n\n let icon: 'spinner' | 'invite' | 'done' | 'error' = 'invite';\n let title = '';\n let body: string | null = null;\n if (stage === 'awaiting-confirmation') {\n title = teamName ? `Join “${teamName}”?` : `Join this ${noun}?`;\n body =\n detail ??\n `You have been invited. Joining makes this device a member, and the ${noun}'s data syncs to it from the other members.`;\n } else if (stage === 'joining') {\n icon = 'spinner';\n title = `Joining ${named}…`;\n body =\n status ||\n 'Asking a member to let you in. With few members online this can take up to a minute.';\n } else if (stage === 'syncing') {\n icon = 'spinner';\n title = `Syncing ${named}…`;\n body = slow\n ? `Still waiting on the other members. You can carry on; the ${noun} fills in as its data arrives.`\n : `You're in. Getting the ${noun}'s data from the other members.`;\n } else if (stage === 'ready') {\n icon = 'done';\n title = `You're in ${named}`;\n } else if (stage === 'already-member') {\n icon = 'done';\n title = `You're already in ${named}`;\n } else {\n icon = 'error';\n title = \"Couldn't join\";\n body =\n state.stage === 'failed'\n ? (describeInviteFailure(state.reason, noun) ?? state.message)\n : null;\n }\n\n const retryable = state.stage === 'failed' && state.retryable;\n\n return createPortal(\n <div\n ref={overlayRef}\n className=\"mero-invite-overlay\"\n onMouseDown={(event) => {\n if (event.target !== event.currentTarget) return;\n // Keep focus in the dialog: a press on the backdrop would otherwise\n // move it to <body>, and Tab from there walks the page behind.\n event.preventDefault();\n close();\n }}\n >\n <div\n ref={dialogRef}\n className=\"mero-invite-dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={titleId}\n aria-describedby={body ? bodyId : undefined}\n aria-busy={busy}\n tabIndex={-1}\n data-testid=\"invite-prompt\"\n data-stage={stage}\n onKeyDown={onKeyDown}\n >\n {appName ? <p className=\"mero-invite-app\">{appName}</p> : null}\n <div className=\"mero-invite-head\">\n <InviteIcon kind={icon} />\n <h2 id={titleId} className=\"mero-invite-title\">\n {title}\n </h2>\n </div>\n {body ? (\n <p\n id={bodyId}\n className={\n stage === 'failed'\n ? 'mero-invite-body mero-invite-body-error'\n : 'mero-invite-body'\n }\n role={stage === 'failed' ? 'alert' : undefined}\n data-testid={stage === 'failed' ? 'invite-error' : undefined}\n >\n {body}\n </p>\n ) : null}\n {stage === 'syncing' || stage === 'joining' ? (\n <div className=\"mero-invite-progress\" aria-hidden=\"true\">\n <span className=\"mero-invite-progress-bar\" />\n </div>\n ) : null}\n\n <div className=\"mero-invite-actions\">\n {stage === 'awaiting-confirmation' ? (\n <>\n <button\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={decline}\n data-testid=\"invite-decline\"\n >\n Not now\n </button>\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={accept}\n data-testid=\"invite-accept\"\n >\n Join\n </button>\n </>\n ) : null}\n {stage === 'syncing' && slow ? (\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={dismiss}\n data-testid=\"invite-continue\"\n >\n Continue in background\n </button>\n ) : null}\n {stage === 'ready' || stage === 'already-member' ? (\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={dismiss}\n data-testid=\"invite-done\"\n >\n Done\n </button>\n ) : null}\n {stage === 'failed' ? (\n <>\n <button\n ref={retryable ? undefined : primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={dismiss}\n data-testid=\"invite-decline\"\n >\n Close\n </button>\n {retryable ? (\n <button\n ref={primaryRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={retry}\n data-testid=\"invite-retry\"\n >\n Try again\n </button>\n ) : null}\n </>\n ) : null}\n </div>\n </div>\n </div>,\n document.body,\n );\n}\n\nfunction InviteIcon({ kind }: { kind: 'spinner' | 'invite' | 'done' | 'error' }) {\n if (kind === 'spinner') {\n return <span className=\"mero-invite-icon mero-invite-spinner\" aria-hidden=\"true\" />;\n }\n const path =\n kind === 'done'\n ? 'M5 12.5l4.5 4.5L19 7.5'\n : kind === 'error'\n ? 'M12 7v6m0 4h.01'\n : 'M4 7l8 6 8-6M5 6h14a1 1 0 011 1v10a1 1 0 01-1 1H5a1 1 0 01-1-1V7a1 1 0 011-1z';\n return (\n <span className={`mero-invite-icon mero-invite-icon-${kind}`} aria-hidden=\"true\">\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d={path} />\n </svg>\n </span>\n );\n}\n","import type { CSSProperties, ReactNode } from \"react\";\n\nexport interface JoinSyncBannerProps {\n /** Usually `useJoinSync(...).isSyncing`. Renders nothing when false. */\n show: boolean;\n /** What is arriving, in the app's own words: \"documents\", \"vaults\", \"sheets\". */\n what?: string;\n /** Wire to `useJoinSync(...).dismiss` for a \"show me anyway\" escape. */\n onDismiss?: () => void;\n /** Escape hatches for apps with their own design system. */\n className?: string;\n style?: CSSProperties;\n children?: ReactNode;\n}\n\n/**\n * Deliberately inline-styled rather than using a stylesheet or utility classes.\n *\n * The apps in this monorepo do not share a CSS stack — Tailwind, CSS modules\n * and plain stylesheets are all represented — so anything class-based would\n * render unstyled in most of them. Inline styles are the only thing that looks\n * the same everywhere, and `className`/`style` are there for apps that want to\n * take it over. Colours come from CSS custom properties with literal\n * fallbacks, so an app that defines them gets its own palette for free and one\n * that does not still gets something legible in both themes.\n */\nexport function JoinSyncBanner({\n show,\n what = \"data\",\n onDismiss,\n className,\n style,\n children,\n}: JoinSyncBannerProps) {\n if (!show) return null;\n\n return (\n <div\n role=\"status\"\n aria-live=\"polite\"\n className={className}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"0.625rem\",\n padding: \"0.625rem 0.875rem\",\n borderRadius: \"0.5rem\",\n border: \"1px solid var(--join-sync-border, rgba(127,127,127,0.28))\",\n background: \"var(--join-sync-bg, rgba(127,127,127,0.08))\",\n color: \"var(--join-sync-fg, inherit)\",\n font: \"inherit\",\n fontSize: \"0.875rem\",\n lineHeight: 1.4,\n ...style,\n }}\n >\n <Spinner />\n <span style={{ flex: 1 }}>\n {children ?? (\n <>\n Joined. Syncing {what} from peers&hellip;{\" \"}\n <span style={{ opacity: 0.75 }}>\n This can take a moment on a cold connection.\n </span>\n </>\n )}\n </span>\n {onDismiss && (\n <button\n type=\"button\"\n onClick={onDismiss}\n style={{\n font: \"inherit\",\n fontSize: \"0.8125rem\",\n background: \"none\",\n border: \"none\",\n padding: 0,\n color: \"inherit\",\n opacity: 0.75,\n textDecoration: \"underline\",\n cursor: \"pointer\",\n }}\n >\n Show anyway\n </button>\n )}\n </div>\n );\n}\n\n/**\n * An inline SVG rather than a CSS-class spinner, for the same reason as above —\n * and `<animateTransform>` rather than a keyframe, because injecting a\n * `@keyframes` rule from a shared component would collide across apps.\n */\nfunction Spinner() {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 16 16\"\n aria-hidden=\"true\"\n style={{ flexShrink: 0, opacity: 0.85 }}\n >\n <circle\n cx=\"8\"\n cy=\"8\"\n r=\"6.5\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeOpacity=\"0.25\"\n strokeWidth=\"2\"\n />\n <path\n d=\"M8 1.5A6.5 6.5 0 0 1 14.5 8\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n >\n <animateTransform\n attributeName=\"transform\"\n type=\"rotate\"\n from=\"0 8 8\"\n to=\"360 8 8\"\n dur=\"0.8s\"\n repeatCount=\"indefinite\"\n />\n </path>\n </svg>\n );\n}\n","/**\n * The page an invite link lands on when you are not logged in.\n *\n * Before this, a logged-out person who opened an invite link saw the app's\n * ordinary logged-out page, usually its marketing landing, with nothing saying\n * they had been invited: the invitation sat captured in storage, and the\n * `InvitationDialog` only appeared once they had worked out on their own that\n * they should log in. This screen is the missing step:\n *\n * session restoring a blank page with a spinner (no landing-page flash)\n * logged out \"You're invited to join “Design team”\"\n * Not now / Log in to join (the app's usual login)\n * unreadable link \"This invitation can't be read\" Continue\n * logged in nothing: `InvitationDialog` asks, joins and syncs\n *\n * It reads the captured invitation without taking it (`subscribeInvitation`,\n * `peekInvitation`), so the app's `useInviteRedemption` still receives it after\n * login. \"Not now\" acks it, exactly as the dialog's does.\n *\n * Two ways to mount it, both inside `MeroProvider` (outside one it shows\n * nothing, since there is no session to ask about):\n *\n * - beside the app's `InvitationDialog`, with no children: the screen covers\n * whatever page is underneath (a full-page layer, opaque). One line in the\n * component that already owns the dialog.\n * - around the app, `<InvitationGate …>{app}</InvitationGate>`: the screen is\n * rendered instead of the children, so the landing page does not mount.\n *\n * Test ids: `invite-landing` (with `data-state`: `checking`, `invited`,\n * `invalid`), `invite-landing-login`, `invite-landing-decline`.\n */\nimport {\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useSyncExternalStore,\n type KeyboardEvent as ReactKeyboardEvent,\n type ReactNode,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { ConnectButton, type ConnectButtonProps } from '../components/ConnectButton';\nimport { MeroContext } from '../context';\nimport { peekInvitation, subscribeInvitation, type CapturedInvitation } from './capture';\nimport type { ParsedInvitation } from './useInviteRedemption';\n\nexport interface InvitationGateProps {\n /**\n * The app, shown as usual unless an invitation is waiting on a login. Leave\n * out to mount the gate beside the app instead, as a full-page layer.\n */\n children?: ReactNode;\n /**\n * The app's invitation codec, the same `parse` it gives `useInviteRedemption`.\n * Decoding needs no session, so the screen can name what is being joined.\n * Without it the screen falls back to the noun.\n */\n parse?: (token: string, params: Record<string, string>) => ParsedInvitation | null;\n /** What the app calls the thing being joined: \"team\", \"workspace\", \"vault\". */\n noun?: string;\n /** The app's name, so a person knows where the invitation is taking them. */\n appName?: string;\n /** Optional: the app's own words about what joining gives you. */\n detail?: string;\n /** Passed to the login button (theme, `cloud`, `connectionType`). */\n connectButtonProps?: Omit<ConnectButtonProps, 'label'>;\n}\n\ntype GateState = 'checking' | 'invited' | 'invalid';\n\n/** The captured invitation, re-rendering when one arrives or is acked. */\nexport function usePendingInvitation(): CapturedInvitation | null {\n return useSyncExternalStore(subscribeInvitation, peekInvitation, () => null);\n}\n\nexport function InvitationGate({\n children,\n parse,\n noun = 'team',\n appName,\n detail,\n connectButtonProps,\n}: InvitationGateProps) {\n // Read directly rather than through `useMero`, which throws: with no\n // provider there is no session to ask about, so the gate stays out of the\n // way (as it does in an app's unit tests that stub `useMero` itself).\n const session = useContext(MeroContext);\n const pending = usePendingInvitation();\n\n // `undefined`: not readable at all. `null`: no codec given, so no name.\n const parsed = useMemo((): ParsedInvitation | null | undefined => {\n if (!pending || !parse) return null;\n try {\n const result = parse(pending.token, pending.params);\n return result?.namespaceId ? result : undefined;\n } catch {\n return undefined;\n }\n }, [pending, parse]);\n\n const state: GateState | null =\n !pending || !session || session.isAuthenticated\n ? null\n : session.isLoading\n ? 'checking'\n : parsed === undefined\n ? 'invalid'\n : 'invited';\n\n if (!state) return children === undefined ? null : <>{children}</>;\n\n const page = (\n <InvitationScreen\n state={state}\n teamName={parsed?.teamName}\n noun={noun}\n appName={appName}\n detail={detail}\n connectButtonProps={connectButtonProps}\n onDecline={() => pending?.resolve()}\n />\n );\n if (children !== undefined || typeof document === 'undefined') return page;\n return createPortal(page, document.body);\n}\n\ninterface InvitationScreenProps {\n state: GateState;\n teamName?: string;\n noun: string;\n appName?: string;\n detail?: string;\n connectButtonProps?: Omit<ConnectButtonProps, 'label'>;\n onDecline: () => void;\n}\n\nfunction InvitationScreen({\n state,\n teamName,\n noun,\n appName,\n detail,\n connectButtonProps,\n onDecline,\n}: InvitationScreenProps) {\n const titleId = useId();\n const bodyId = useId();\n const cardRef = useRef<HTMLDivElement>(null);\n const loginRef = useRef<HTMLDivElement>(null);\n const continueRef = useRef<HTMLButtonElement>(null);\n\n // Focus lands on what to do next: the login, or Continue past a bad link.\n useEffect(() => {\n if (state === 'checking') return;\n const target =\n state === 'invited'\n ? loginRef.current?.querySelector<HTMLElement>('button')\n : continueRef.current;\n (target ?? cardRef.current)?.focus();\n }, [state]);\n\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n // No Escape: on a full page it would decline by accident. Keep Tab inside.\n if (event.key !== 'Tab' || !cardRef.current) return;\n const focusable = cardRef.current.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), [href], [tabindex]:not([tabindex=\"-1\"])',\n );\n if (focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n if (state === 'checking') {\n // Deliberately wordless: a restored session goes straight to the dialog,\n // and a card that says \"invited\" for a blink before it would be noise.\n return (\n <div\n className=\"mero-invite-landing\"\n role=\"status\"\n aria-busy=\"true\"\n aria-label=\"Checking your session\"\n data-testid=\"invite-landing\"\n data-state=\"checking\"\n >\n <span className=\"mero-invite-icon mero-invite-spinner\" aria-hidden=\"true\" />\n </div>\n );\n }\n\n const invalid = state === 'invalid';\n const title = invalid\n ? \"This invitation can't be read\"\n : teamName\n ? `You're invited to join “${teamName}”`\n : `You're invited to join a ${noun}`;\n const where = appName ? ` in ${appName}` : '';\n const body = invalid\n ? 'The link may have been cut short when it was shared. Ask whoever sent it for a new one.'\n : `Someone sent you a link to join this ${noun}${where}. Log in to accept it; you'll be asked to confirm before you join.`;\n\n return (\n <div className=\"mero-invite-landing\">\n <div\n ref={cardRef}\n className=\"mero-invite-dialog mero-invite-landing-card\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={titleId}\n aria-describedby={bodyId}\n tabIndex={-1}\n data-testid=\"invite-landing\"\n data-state={state}\n onKeyDown={onKeyDown}\n >\n {appName ? <p className=\"mero-invite-app\">{appName}</p> : null}\n <div className=\"mero-invite-head\">\n <InviteIcon error={invalid} />\n <h1 id={titleId} className=\"mero-invite-title\">\n {title}\n </h1>\n </div>\n <p id={bodyId} className=\"mero-invite-body\">\n {body}\n </p>\n {detail && !invalid ? <p className=\"mero-invite-body\">{detail}</p> : null}\n\n <div className=\"mero-invite-actions\">\n {invalid ? (\n <button\n ref={continueRef}\n type=\"button\"\n className=\"mero-invite-button mero-invite-primary\"\n onClick={onDecline}\n data-testid=\"invite-landing-decline\"\n >\n Continue\n </button>\n ) : (\n <>\n <button\n type=\"button\"\n className=\"mero-invite-button mero-invite-secondary\"\n onClick={onDecline}\n data-testid=\"invite-landing-decline\"\n >\n Not now\n </button>\n <div\n ref={loginRef}\n className=\"mero-invite-landing-login\"\n data-testid=\"invite-landing-login\"\n >\n <ConnectButton {...connectButtonProps} label=\"Log in to join\" />\n </div>\n </>\n )}\n </div>\n </div>\n </div>\n );\n}\n\nfunction InviteIcon({ error }: { error: boolean }) {\n const path = error\n ? 'M12 7v6m0 4h.01'\n : 'M4 7l8 6 8-6M5 6h14a1 1 0 011 1v10a1 1 0 01-1 1H5a1 1 0 01-1-1V7a1 1 0 011-1z';\n return (\n <span\n className={error ? 'mero-invite-icon mero-invite-icon-error' : 'mero-invite-icon'}\n aria-hidden=\"true\"\n >\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d={path} />\n </svg>\n </span>\n );\n}\n","/**\n * Join a namespace and one of its contexts from an invitation — the same call\n * whatever the connection is.\n *\n * - A node login publishes its own membership op (`joinNamespace`) and joins\n * the context (`joinContext`) on that node.\n * - An account (no node) signs the join with its device key and hands it to\n * an admitter the invitation names (`useDelegatedBootstrap`); from then on it\n * reaches the namespace through that relay.\n *\n * The app gets one result shape back either way, including whether the failure\n * is FINAL — worth discarding the invitation for — or worth retrying.\n */\nimport { useCallback, useState } from 'react';\nimport type { InviteRedeemer, SignedGroupOpenInvitation } from '@calimero-network/mero-js';\nimport { useMero } from '../context';\nimport { useDelegatedBootstrap } from '../delegated/useDelegatedBootstrap';\nimport type { BootstrapFailure } from '@calimero-network/mero-js';\nimport { listDelegatedNamespaces, readDelegatedSession } from '@calimero-network/mero-js';\n\n/** The HTTP status an error carries, read the way mero-js's classifier reads it. */\nfunction statusOf(err: unknown): number | undefined {\n if (!err || typeof err !== 'object') return undefined;\n const e = err as { status?: unknown; statusCode?: unknown; response?: { status?: unknown } };\n for (const c of [e.status, e.response?.status, e.statusCode]) {\n if (typeof c === 'number' && Number.isFinite(c)) return c;\n }\n return undefined;\n}\n\nexport interface JoinInvitationInput {\n readonly namespaceId: string;\n /** The context the invitation was for, when it names one; a workspace invitation names none. */\n readonly contextId?: string;\n readonly invitation: SignedGroupOpenInvitation;\n}\n\nexport type JoinInvitationStep = BootstrapFailure['step'] | 'node-join';\n\nexport type JoinInvitationResult =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly step: JoinInvitationStep;\n /** What went wrong, in words a person can act on. */\n readonly reason: string;\n /** True when no retry can succeed: a fresh invitation is the only cure. */\n readonly final: boolean;\n /** The HTTP status of the refusal, when there was one. */\n readonly status?: number;\n };\n\n/** Which step failed, in the words a person can act on. */\nconst STEP_LABEL: Record<BootstrapFailure['step'], string> = {\n 'no-credential': 'No enrolled account',\n 'admitters-lookup': 'Admitters lookup failed',\n 'no-nodes': 'No hosted node serves this namespace',\n 'not-invited': 'This invitation names none of the serving nodes',\n 'invited-unreachable': 'The invited admitter cannot take a join right now',\n 'no-relay-url': 'The invited admitter has no address yet',\n sign: 'The join could not be signed',\n admit: 'The admitter refused the join',\n};\n\n/**\n * Whether an account's join failure is final. Per step: an admitter's 400/403\n * judged the op or the invitation; `not-invited` and `sign` fail identically\n * next time. Everything else (a lookup, an unreachable admitter, no fleet\n * assignment yet, a 409) is kept for a retry.\n */\nfunction accountJoinIsFinal(failure: BootstrapFailure): boolean {\n if (failure.step === 'admit') return failure.status === 400 || failure.status === 403;\n return failure.step === 'not-invited' || failure.step === 'sign';\n}\n\n/**\n * Whether a node's join failure means the invitation itself will never work.\n *\n * Errs toward false: a dropped invitation is unrecoverable for the user, a\n * retried one costs a round trip, so a timeout or anything unfamiliar keeps\n * it. Phrases, not bare words — `\"invalid\"` alone would also match an\n * \"invalid response\" from a proxy, a transient failure.\n */\nexport function isFinalInvitationError(message: string | undefined | null): boolean {\n if (!message) return false;\n const m = message.toLowerCase();\n return [\n 'invitation expired',\n 'expired invitation',\n 'invalid invitation',\n 'invitation is invalid',\n 'malformed invitation',\n 'malformed payload',\n 'invalid signature',\n 'signature verification failed',\n 'not admin',\n 'revoked',\n 'already a member',\n ].some((t) => m.includes(t));\n}\n\nexport function useJoinInvitation(): {\n joinInvitation: (input: JoinInvitationInput) => Promise<JoinInvitationResult>;\n joining: boolean;\n /** The namespaces this connection is a member of: a node's own, or an account's across its relays. */\n memberships: () => Promise<string[]>;\n /**\n * The `{ join, memberships }` pair mero-js's `redeemInvitation` drives, for\n * whichever connection this is, so an app redeems an invitation (join once,\n * then check membership) with no transport of its own. `join` throws on a\n * refusal, carrying its HTTP status for the outcome's reason.\n */\n invitationRedeemer: (input: JoinInvitationInput) => InviteRedeemer;\n} {\n const { mero, isDelegated } = useMero();\n const { credential, bootstrap } = useDelegatedBootstrap();\n const [joining, setJoining] = useState(false);\n\n const joinInvitation = useCallback(\n async (input: JoinInvitationInput): Promise<JoinInvitationResult> => {\n setJoining(true);\n try {\n // An account joins through an admitter: when the connection is one, or\n // when an account is enrolled and no node session exists. A node login\n // joins on its own node even if a credential lingers in this tab.\n const asAccount = isDelegated || (credential !== null && mero === null);\n if (asAccount) {\n const outcome = await bootstrap({\n namespaceId: input.namespaceId,\n invitation: input.invitation,\n contextId: input.contextId,\n });\n if (outcome.ok) return { ok: true };\n return {\n ok: false,\n step: outcome.step,\n reason: `${STEP_LABEL[outcome.step]}. ${outcome.reason}`,\n final: accountJoinIsFinal(outcome),\n ...(outcome.status !== undefined ? { status: outcome.status } : {}),\n };\n }\n\n if (!mero) {\n return { ok: false, step: 'node-join', reason: 'Not connected to a node.', final: false };\n }\n // The admin client directly, not the join hooks: those swallow errors\n // (they resolve to null), which would report a failed join as joined.\n await mero.admin.joinNamespace(input.namespaceId, { invitation: input.invitation });\n if (input.contextId) await mero.admin.joinContext(input.contextId);\n return { ok: true };\n } catch (e) {\n const reason = e instanceof Error ? e.message : String(e);\n const status = statusOf(e);\n return {\n ok: false,\n step: 'node-join',\n reason,\n final: isFinalInvitationError(reason),\n ...(status !== undefined ? { status } : {}),\n };\n } finally {\n setJoining(false);\n }\n },\n [mero, isDelegated, credential, bootstrap],\n );\n\n const memberships = useCallback(async (): Promise<string[]> => {\n const asAccount = isDelegated || (credential !== null && mero === null);\n const ids = (list: ReadonlyArray<{ namespaceId?: string; groupId?: string; id?: string }>) =>\n list.map((n) => n.namespaceId ?? n.groupId ?? n.id ?? '').filter(Boolean);\n if (asAccount) {\n const session = readDelegatedSession();\n return session ? ids(await listDelegatedNamespaces(session)) : [];\n }\n if (!mero) return [];\n return ids((await mero.admin.listNamespaces()) as Array<{ namespaceId?: string; groupId?: string; id?: string }>);\n }, [mero, isDelegated, credential]);\n\n const invitationRedeemer = useCallback(\n (input: JoinInvitationInput): InviteRedeemer => ({\n join: async () => {\n const outcome = await joinInvitation(input);\n if (!outcome.ok) {\n throw Object.assign(new Error(outcome.reason), outcome.status !== undefined ? { status: outcome.status } : {});\n }\n },\n memberships,\n }),\n [joinInvitation, memberships],\n );\n\n return { joinInvitation, joining, memberships, invitationRedeemer };\n}\n"]}