@kehto/shell 0.21.3 → 0.23.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.
- package/README.md +71 -24
- package/dist/index.d.ts +109 -1
- package/dist/index.js +359 -42
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shell-bridge.ts","../src/hooks-adapter.ts","../src/origin-registry.ts","../src/session-registry.ts","../src/acl-store.ts","../src/manifest-cache.ts","../src/audio-manager.ts","../src/shell-init.ts","../src/shell-ready.ts","../src/napplet-namespace.ts","../src/index.ts","../src/topics.ts","../src/identity-proxy.ts","../src/theme-proxy.ts","../src/keys-proxy.ts","../src/media-proxy.ts","../src/notify-proxy.ts"],"sourcesContent":["\nimport { createRuntime, type ConsentRequest, type Runtime } from '@kehto/runtime';\nimport { adaptHooks } from './hooks-adapter.js';\nimport { originRegistry } from './origin-registry.js';\nimport { nappKeyRegistry } from './session-registry.js';\nimport { aclStore } from './acl-store.js';\nimport { manifestCache } from './manifest-cache.js';\nimport { audioManager } from './audio-manager.js';\nimport type { ShellAdapter, UnroutedMessageInfo } from './types.js';\nimport type { NappletMessage } from '@napplet/core';\nimport type { Theme } from '@napplet/nap/theme/types';\nimport { createShellReadyState, handleShellReady } from './shell-ready.js';\n\n/**\n * Shell-side message bridge that handles NIP-5D communication with napplet iframes.\n *\n * The bridge acts as a browser adapter: it receives raw MessageEvents from\n * window.addEventListener('message', ...), extracts the source Window, resolves\n * it to a windowId via originRegistry, and delegates NIP-5D envelope messages\n * to the runtime engine. The shell.ready/shell.init capability handshake is\n * handled locally within the bridge and never forwarded to the runtime.\n *\n * @example\n * ```ts\n * import { createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * window.addEventListener('message', bridge.handleMessage);\n * ```\n */\nexport interface ShellBridge {\n /**\n * Handle an incoming postMessage from a napplet iframe.\n *\n * Only NIP-5D envelope objects (plain objects with a `.type` string) are\n * accepted. NIP-01 arrays and all other message shapes are silently dropped\n * (clean break — no legacy array fallback).\n *\n * shell.ready messages are handled locally: the bridge responds with shell.init\n * containing the capability set and registered service list. All other envelopes\n * are delegated to the runtime's NAP domain dispatch.\n *\n * @param event - The raw MessageEvent from window.addEventListener('message', ...)\n * @example\n * ```ts\n * window.addEventListener('message', bridge.handleMessage);\n * ```\n */\n handleMessage(event: MessageEvent): void;\n\n /**\n * Inject a shell-originated event into subscription delivery. Under NIP-5D,\n * shell-originated events are forwarded to napplets as inc.event envelope\n * messages. The runtime's injectEvent() handles the per-session routing.\n *\n * v1.10 hard-removed the v1.8 soft-rename compatibility branch for the\n * old `auth:identity-changed` topic. Use the canonical `identity:changed`\n * topic for identity-change pushes.\n *\n * @param topic - The event topic tag value. Forwarded exactly once.\n * @param payload - The event content\n * @example\n * ```ts\n * bridge.injectEvent('identity:changed', { pubkey: userPubkey });\n * ```\n */\n injectEvent(topic: string, payload: unknown): void;\n\n /**\n * Destroy the bridge instance, cleaning up all internal state.\n * Persists manifest cache and clears all subscriptions, buffers, and registries.\n * Call when the shell is shutting down or the bridge is no longer needed.\n *\n * @example\n * ```ts\n * bridge.destroy();\n * ```\n */\n destroy(): void;\n\n /**\n * Register a handler for consent requests on destructive signing kinds.\n * Called when a napplet requests signing for kinds 0, 3, 5, or 10002.\n *\n * @param handler - Callback receiving the consent request with a resolve function\n * @example\n * ```ts\n * bridge.registerConsentHandler((request) => {\n * const allowed = confirm(`Allow signing kind ${request.event.kind}?`);\n * request.resolve(allowed);\n * });\n * ```\n */\n registerConsentHandler(handler: (request: ConsentRequest) => void): void;\n\n /**\n * Publish a theme update to each eligible napplet.\n *\n * Posts a `theme.changed` envelope (shell → napplet push) to every\n * live authenticated session whose frozen environment grants `theme` and\n * whose current ACL grants `theme:read`. Stale or ineligible sessions are\n * skipped before origin-registry delivery; recipient code is not trusted\n * to enforce host authorization.\n *\n * @param theme - The new theme payload to broadcast.\n * @example\n * ```ts\n * bridge.publishTheme({\n * colors: { background: '#0a0a0a', text: '#e0e0e0', primary: '#7aa2f7' },\n * title: 'Dark',\n * });\n * ```\n */\n publishTheme(theme: Theme): void;\n\n /**\n * Publish the current shell-user identity to every loaded napplet.\n *\n * Posts an `identity.changed` envelope (shell → napplet push) with the\n * current user pubkey. An empty pubkey means no signer/user identity is\n * currently connected. This is distinct from NIP-5D napplet session identity,\n * which remains source-bound at iframe creation.\n *\n * @param pubkey - Current user's hex pubkey, or empty string when signed out.\n */\n publishIdentityChanged(pubkey: string): void;\n\n /**\n * Access the underlying runtime instance for advanced use cases.\n * Provides direct access to the runtime's sessionRegistry, aclState,\n * and manifestCache.\n */\n readonly runtime: Runtime;\n\n}\n\n/**\n * Create a ShellBridge instance with dependency injection via hooks.\n *\n * Internally creates a Runtime from @kehto/runtime and adapts the\n * browser-oriented ShellAdapter into environment-agnostic RuntimeAdapter.\n *\n * @param hooks - Host application provides relay pool, auth, config, etc.\n * @returns A ShellBridge instance ready to handle napplet messages\n * @example\n * ```ts\n * import { createShellBridge, type ShellAdapter } from '@kehto/shell';\n *\n * const hooks: ShellAdapter = {\n * relayPool: myRelayPoolHooks,\n * relayConfig: myRelayConfigHooks,\n * windowManager: myWindowManagerHooks,\n * auth: myAuthHooks,\n * config: myConfigHooks,\n * hotkeys: myHotkeyHooks,\n * workerRelay: myWorkerRelayHooks,\n * crypto: myCryptoHooks,\n * };\n * const bridge = createShellBridge(hooks);\n * ```\n */\n/**\n * Fire the optional {@link ShellAdapter.onUnroutedMessage} diagnostic hook for a\n * message the bridge is about to drop. Extracts the envelope `type` defensively\n * (the message-shape guard hasn't run yet at the drop points) and never throws —\n * a misbehaving host hook must not break message handling.\n */\nfunction reportUnrouted(\n hooks: ShellAdapter,\n event: MessageEvent,\n reason: UnroutedMessageInfo['reason'],\n): void {\n if (!hooks.onUnroutedMessage) return;\n const data = event.data as { type?: unknown } | null | undefined;\n const type = typeof data === 'object' && data !== null && typeof data.type === 'string'\n ? data.type\n : undefined;\n try {\n hooks.onUnroutedMessage({ type, origin: event.origin, reason });\n } catch {\n // Observability must never break routing — swallow host hook errors.\n }\n}\n\nexport function createShellBridge(hooks: ShellAdapter): ShellBridge {\n const shellReadyState = createShellReadyState();\n const runtimeHooks = adaptHooks(hooks, {\n originRegistry,\n manifestCache,\n aclStore,\n audioManager,\n nappKeyRegistry,\n });\n\n const runtime: Runtime = createRuntime({\n ...runtimeHooks,\n isDomainAllowed: shellReadyState.isDomainAllowed,\n });\n\n function publishToEligibleNapplets(\n envelope: NappletMessage,\n domain: 'identity' | 'theme',\n capability: 'identity:read' | 'theme:read',\n ): void {\n // A session exists only after shell.ready. Iterate entries, not a pubkey\n // lookup, because different live windows may legitimately share pubkey ''.\n for (const entry of runtime.sessionRegistry.getAllEntries()) {\n const environment = shellReadyState.environments.get(entry.windowId);\n if (!environment?.capabilities.domains.includes(domain)) continue;\n if (!runtime.aclState.check(entry.pubkey, entry.dTag, entry.aggregateHash, capability)) continue;\n\n const win = originRegistry.getIframeWindow(entry.windowId);\n if (!win) continue;\n win.postMessage(envelope, '*');\n }\n }\n\n return {\n handleMessage(event: MessageEvent): void {\n const sourceWindow = event.source as Window | null;\n if (!sourceWindow) {\n reportUnrouted(hooks, event, 'no-source-window');\n return;\n }\n const windowId = originRegistry.getWindowId(sourceWindow);\n if (!windowId) {\n reportUnrouted(hooks, event, 'unregistered-window');\n return;\n }\n const msg = event.data;\n\n // NIP-5D envelope-only guard (clean break — no legacy array support)\n if (typeof msg !== 'object' || msg === null || typeof msg.type !== 'string') return;\n\n // Handle shell.ready handshake locally (not forwarded to runtime)\n if (msg.type === 'shell.ready') {\n handleShellReady({\n hooks,\n origin: event.origin,\n runtime,\n state: shellReadyState,\n sourceRegistrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0,\n sourceWindow,\n windowId,\n });\n return;\n }\n\n // Delegate to runtime — runtime handles NAP domain dispatch\n runtime.handleMessage(windowId, msg);\n },\n\n injectEvent(topic: string, payload: unknown): void {\n runtime.injectEvent(topic, payload);\n },\n\n destroy(): void {\n runtime.destroy();\n shellReadyState.clear();\n },\n\n registerConsentHandler(handler: (request: ConsentRequest) => void): void {\n runtime.registerConsentHandler(handler);\n },\n\n publishTheme(theme: Theme): void {\n const envelope: NappletMessage = { type: 'theme.changed', theme } as NappletMessage;\n publishToEligibleNapplets(envelope, 'theme', 'theme:read');\n },\n\n publishIdentityChanged(pubkey: string): void {\n const envelope: NappletMessage = { type: 'identity.changed', pubkey } as NappletMessage;\n publishToEligibleNapplets(envelope, 'identity', 'identity:read');\n },\n\n get runtime() {\n return runtime;\n },\n };\n}\n","/**\n * hooks-adapter.ts — Converts ShellAdapter (browser-facing) to RuntimeAdapter (environment-agnostic).\n *\n * The adapter bridges the gap between the shell's browser-oriented ShellAdapter interfaces\n * (Window references, localStorage, postMessage) and the runtime's abstract RuntimeAdapter\n * (windowId strings, persistence interfaces, sendToNapplet callbacks).\n */\n\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type {\n RuntimeAdapter,\n RelayPoolAdapter,\n CacheAdapter,\n AuthAdapter,\n Signer,\n ConfigAdapter,\n HotkeyAdapter,\n AclPersistence,\n ManifestPersistence,\n StatePersistence,\n CryptoAdapter,\n WindowManagerAdapter,\n RelayConfigAdapter,\n DmAdapter,\n SendToNapplet,\n RelaySubscriptionHandle,\n ShellSecretPersistence,\n GuidPersistence,\n} from '@kehto/runtime';\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);\n }\n return bytes;\n}\nimport type { ShellAdapter } from './types.js';\nimport type { originRegistry as OriginRegistryType } from './origin-registry.js';\nimport type { manifestCache as ManifestCacheType } from './manifest-cache.js';\nimport type { aclStore as AclStoreType } from './acl-store.js';\nimport type { audioManager as AudioManagerType } from './audio-manager.js';\nimport type { sessionRegistry as SessionRegistryType } from './session-registry.js';\n\n/**\n * Browser-specific singletons that the adapter bridges to the runtime.\n * These use browser APIs (Window, localStorage, postMessage, CustomEvent)\n * that the runtime cannot access directly.\n */\nexport interface BrowserDeps {\n originRegistry: typeof OriginRegistryType;\n manifestCache: typeof ManifestCacheType;\n aclStore: typeof AclStoreType;\n audioManager: typeof AudioManagerType;\n nappKeyRegistry: typeof SessionRegistryType;\n}\n\nfunction createSendToNapplet(originRegistry: BrowserDeps['originRegistry']): SendToNapplet {\n return (windowId, msg) => {\n const win = originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(msg, '*');\n };\n}\n\nfunction createRelayPoolAdapter(\n shellHooks: ShellAdapter,\n originRegistry: BrowserDeps['originRegistry'],\n): RelayPoolAdapter {\n return {\n subscribe(\n filters: NostrFilter[],\n callback: (item: NostrEvent | 'EOSE') => void,\n relayUrls?: string[],\n ): RelaySubscriptionHandle {\n const pool = shellHooks.relayPool.getRelayPool();\n if (!pool) return { unsubscribe() { /* no-op */ } };\n\n const urls = relayUrls ?? shellHooks.relayPool.selectRelayTier(filters);\n const sub = pool.subscription(urls, filters).subscribe((item) => {\n if (item === 'EOSE') callback('EOSE');\n else callback(item as NostrEvent);\n });\n return { unsubscribe: () => sub.unsubscribe() };\n },\n\n publish(event: NostrEvent): void | Promise<void> {\n const pool = shellHooks.relayPool.getRelayPool();\n if (!pool) return;\n const relayUrls = shellHooks.relayPool.selectRelayTier([]);\n return pool.publish(relayUrls, event);\n },\n\n selectRelayTier(filters: NostrFilter[]): string[] {\n return shellHooks.relayPool.selectRelayTier(filters);\n },\n\n trackSubscription(subKey: string, cleanup: () => void): void {\n shellHooks.relayPool.trackSubscription(subKey, cleanup);\n },\n\n untrackSubscription(subKey: string): void {\n shellHooks.relayPool.untrackSubscription(subKey);\n },\n\n openScopedRelay(\n windowId: string,\n relayUrl: string,\n subId: string,\n filters: NostrFilter[],\n _sendFn: SendToNapplet,\n ): void {\n const win = originRegistry.getIframeWindow(windowId);\n if (win) shellHooks.relayPool.openScopedRelay(windowId, relayUrl, subId, filters, win);\n },\n\n closeScopedRelay(windowId: string): void {\n shellHooks.relayPool.closeScopedRelay(windowId);\n },\n\n publishToScopedRelay(windowId: string, event: NostrEvent): boolean | Promise<boolean> {\n return shellHooks.relayPool.publishToScopedRelay(windowId, event);\n },\n\n isAvailable(): boolean {\n return shellHooks.relayPool.getRelayPool() !== null;\n },\n };\n}\n\nfunction createCacheAdapter(shellHooks: ShellAdapter): CacheAdapter {\n return {\n async query(filters: NostrFilter[]): Promise<NostrEvent[]> {\n const workerRelay = shellHooks.workerRelay.getWorkerRelay();\n if (!workerRelay) return [];\n const subId = crypto.randomUUID();\n return workerRelay.query(['REQ', subId, ...filters]);\n },\n\n store(event: NostrEvent): void {\n const workerRelay = shellHooks.workerRelay.getWorkerRelay();\n if (!workerRelay) return;\n try { workerRelay.event(event)?.catch?.(() => { /* best-effort */ }); } catch { /* best-effort */ }\n },\n\n isAvailable(): boolean {\n return shellHooks.workerRelay.getWorkerRelay() !== null;\n },\n };\n}\n\nfunction createAuthAdapter(shellHooks: ShellAdapter): AuthAdapter {\n return {\n getUserPubkey(): string | null {\n return shellHooks.auth.getUserPubkey();\n },\n getSigner(windowId?: string): Signer | null {\n return shellHooks.auth.getSigner(windowId);\n },\n };\n}\n\nfunction createConfigAdapter(shellHooks: ShellAdapter): ConfigAdapter {\n return {\n getNappUpdateBehavior(): 'auto-grant' | 'banner' | 'silent-reprompt' {\n return shellHooks.config.getNappUpdateBehavior();\n },\n };\n}\n\nfunction createHotkeyAdapter(shellHooks: ShellAdapter): HotkeyAdapter {\n return {\n executeHotkeyFromForward(event): void {\n shellHooks.hotkeys.executeHotkeyFromForward(event);\n },\n };\n}\n\nfunction createCryptoAdapter(shellHooks: ShellAdapter): CryptoAdapter {\n return {\n async verifyEvent(event: NostrEvent): Promise<boolean> {\n return shellHooks.crypto.verifyEvent(event);\n },\n randomUUID(): string {\n return crypto.randomUUID();\n },\n randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n },\n };\n}\n\nfunction createAclPersistence(): AclPersistence {\n return {\n persist(data: string): void {\n try { localStorage.setItem('napplet:acl', data); } catch { /* best-effort */ }\n },\n load(): string | null {\n try { return localStorage.getItem('napplet:acl'); } catch { return null; }\n },\n };\n}\n\nfunction createManifestPersistence(): ManifestPersistence {\n return {\n persist(data: string): void {\n try { localStorage.setItem('napplet:manifest-cache', data); } catch { /* best-effort */ }\n },\n load(): string | null {\n try { return localStorage.getItem('napplet:manifest-cache'); } catch { return null; }\n },\n };\n}\n\nfunction createStatePersistence(): StatePersistence {\n return {\n get(scopedKey: string): string | null {\n try { return localStorage.getItem(scopedKey); } catch { return null; }\n },\n set(scopedKey: string, value: string): boolean {\n try { localStorage.setItem(scopedKey, value); return true; } catch { return false; }\n },\n remove(scopedKey: string): void {\n try { localStorage.removeItem(scopedKey); } catch { /* best-effort */ }\n },\n clear(prefix: string): void {\n try {\n const keysToRemove: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(prefix)) keysToRemove.push(key);\n }\n for (const key of keysToRemove) localStorage.removeItem(key);\n } catch { /* best-effort */ }\n },\n keys(prefix: string): string[] {\n try {\n const result: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(prefix)) result.push(key);\n }\n return result;\n } catch { return []; }\n },\n calculateBytes(prefix: string, excludeKey?: string): number {\n try {\n let total = 0;\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (!key?.startsWith(prefix)) continue;\n if (excludeKey && key === excludeKey) continue;\n const value = localStorage.getItem(key) ?? '';\n total += new TextEncoder().encode(key + value).length;\n }\n return total;\n } catch { return 0; }\n },\n };\n}\n\nfunction createWindowManagerAdapter(shellHooks: ShellAdapter): WindowManagerAdapter {\n return {\n createWindow(options): string | null {\n return shellHooks.windowManager.createWindow(options);\n },\n };\n}\n\nfunction createRelayConfigAdapter(shellHooks: ShellAdapter): RelayConfigAdapter {\n return {\n addRelay(tier: string, url: string): void {\n shellHooks.relayConfig.addRelay(tier, url);\n },\n removeRelay(tier: string, url: string): void {\n shellHooks.relayConfig.removeRelay(tier, url);\n },\n getRelayConfig(): { discovery: string[]; super: string[]; outbox: string[] } {\n return shellHooks.relayConfig.getRelayConfig();\n },\n getNip66Suggestions(): unknown {\n return shellHooks.relayConfig.getNip66Suggestions();\n },\n };\n}\n\nfunction createShellSecretPersistence(): ShellSecretPersistence {\n return {\n get(): Uint8Array | null {\n try {\n const hex = localStorage.getItem('napplet-shell-secret');\n if (!hex) return null;\n return hexToBytes(hex);\n } catch { return null; }\n },\n set(secret: Uint8Array): void {\n try {\n localStorage.setItem('napplet-shell-secret', bytesToHex(secret));\n } catch { /* localStorage unavailable */ }\n },\n };\n}\n\nfunction createGuidPersistence(): GuidPersistence {\n return {\n get(windowId: string): string | null {\n try {\n return localStorage.getItem(`napplet-guid:${windowId}`);\n } catch { return null; }\n },\n set(windowId: string, guid: string): void {\n try {\n localStorage.setItem(`napplet-guid:${windowId}`, guid);\n } catch { /* localStorage unavailable */ }\n },\n remove(windowId: string): void {\n try {\n localStorage.removeItem(`napplet-guid:${windowId}`);\n } catch { /* localStorage unavailable */ }\n },\n };\n}\n\nfunction createDmAdapter(shellHooks: ShellAdapter): DmAdapter | undefined {\n return shellHooks.dm\n ? {\n sendDm(recipientPubkey: string, message: string) {\n return shellHooks.dm!.sendDm(recipientPubkey, message);\n },\n }\n : undefined;\n}\n\n/**\n * Convert ShellAdapter (browser-facing) into RuntimeAdapter (environment-agnostic).\n *\n * The adapter is the single translation layer between browser APIs and the\n * runtime's abstract interfaces. It:\n * - Converts Window references to windowId strings via originRegistry\n * - Wraps localStorage-backed singletons into persistence interfaces\n * - Translates relay pool API shapes (Observable → callback)\n *\n * @param shellHooks - The browser-oriented ShellAdapter provided by the host app\n * @param deps - Browser-specific singletons (originRegistry, aclStore, etc.)\n * @returns RuntimeAdapter suitable for createRuntime()\n *\n * @example\n * ```ts\n * const runtimeHooks = adaptHooks(shellHooks, {\n * originRegistry, manifestCache, aclStore, audioManager, nappKeyRegistry,\n * });\n * const runtime = createRuntime(runtimeHooks);\n * ```\n */\nexport function adaptHooks(shellHooks: ShellAdapter, deps: BrowserDeps): RuntimeAdapter {\n const { originRegistry } = deps;\n\n return {\n sendToNapplet: createSendToNapplet(originRegistry),\n relayPool: createRelayPoolAdapter(shellHooks, originRegistry),\n cache: createCacheAdapter(shellHooks),\n auth: createAuthAdapter(shellHooks),\n config: createConfigAdapter(shellHooks),\n hotkeys: createHotkeyAdapter(shellHooks),\n crypto: createCryptoAdapter(shellHooks),\n aclPersistence: createAclPersistence(),\n manifestPersistence: createManifestPersistence(),\n statePersistence: createStatePersistence(),\n windowManager: createWindowManagerAdapter(shellHooks),\n relayConfig: createRelayConfigAdapter(shellHooks),\n dm: createDmAdapter(shellHooks),\n shellSecretPersistence: createShellSecretPersistence(),\n guidPersistence: createGuidPersistence(),\n onAclCheck: shellHooks.onAclCheck,\n onHashMismatch: shellHooks.onHashMismatch,\n services: shellHooks.services,\n getConfigOverrides: shellHooks.getConfigOverrides,\n };\n}\n","\nimport type { ShellEnvironment } from './types.js';\n\ninterface OriginEntry {\n windowId: string;\n dTag?: string;\n aggregateHash?: string;\n environment?: ShellEnvironment;\n registrationId: number;\n}\n\n/** NIP-5D identity metadata associated with a registered iframe window. */\nexport interface OriginIdentity {\n readonly dTag: string;\n readonly aggregateHash: string;\n}\n\nconst registry = new Map<Window, OriginEntry>();\nlet nextRegistrationId = 0;\n\n/**\n * Bidirectional registry mapping Window references to windowId strings.\n * Optionally stores NIP-5D identity metadata (dTag and aggregateHash) per window.\n *\n * @example\n * ```ts\n * import { originRegistry } from '@kehto/shell';\n *\n * originRegistry.register(iframe.contentWindow, 'napp-1');\n * const id = originRegistry.getWindowId(iframe.contentWindow); // 'napp-1'\n * ```\n */\nexport interface OriginRegistry {\n register(win: Window, windowId: string, identity?: OriginIdentity): void;\n unregister(windowId: string): void;\n getWindowId(win: Window): string | undefined;\n getIframeWindow(windowId: string): Window | null;\n getAllWindowIds(): string[];\n getIdentity(win: Window): OriginIdentity | undefined;\n setEnvironment(win: Window, environment: ShellEnvironment): void;\n getEnvironment(win: Window): ShellEnvironment | undefined;\n getRegistrationId(win: Window): number | undefined;\n clear(): void;\n}\n\n/** Shell-wide iframe window registry singleton. */\nexport const originRegistry: OriginRegistry = {\n /**\n * Register a window reference with a windowId and optional identity metadata.\n *\n * @param win - The iframe's contentWindow reference\n * @param windowId - The unique identifier for this napplet window\n * @param identity - Optional NIP-5D identity metadata (dTag and aggregateHash)\n */\n register(win: Window, windowId: string, identity?: OriginIdentity): void {\n for (const [registeredWin, entry] of registry.entries()) {\n if (registeredWin === win || entry.windowId === windowId) {\n registry.delete(registeredWin);\n }\n }\n\n registry.set(win, {\n windowId,\n dTag: identity?.dTag,\n aggregateHash: identity?.aggregateHash,\n registrationId: ++nextRegistrationId,\n });\n },\n\n /**\n * Unregister a window by its windowId, removing the mapping.\n *\n * @param windowId - The window identifier to remove\n */\n unregister(windowId: string): void {\n for (const [win, entry] of registry.entries()) {\n if (entry.windowId === windowId) {\n registry.delete(win);\n }\n }\n },\n\n /**\n * Look up the windowId for a given Window reference.\n *\n * @param win - The Window reference (typically from event.source)\n * @returns The windowId string, or undefined if not registered\n */\n getWindowId(win: Window): string | undefined {\n return registry.get(win)?.windowId;\n },\n\n /**\n * Look up the Window reference for a given windowId.\n *\n * @param windowId - The window identifier to look up\n * @returns The Window reference, or null if not found\n */\n getIframeWindow(windowId: string): Window | null {\n for (const [win, entry] of registry.entries()) {\n if (entry.windowId === windowId) return win;\n }\n return null;\n },\n\n /**\n * Get all registered windowId strings.\n *\n * @returns Array of all registered window identifiers\n */\n getAllWindowIds(): string[] {\n return Array.from(registry.values()).map(entry => entry.windowId);\n },\n\n /**\n * Get identity metadata for a registered Window.\n *\n * @param win - The Window reference to look up\n * @returns Identity metadata, or undefined if not registered or no identity set\n */\n getIdentity(win: Window): OriginIdentity | undefined {\n const entry = registry.get(win);\n if (typeof entry?.dTag !== 'string' || !entry?.aggregateHash) return undefined;\n return { dTag: entry.dTag, aggregateHash: entry.aggregateHash };\n },\n\n /** Store the immutable environment captured for this exact frame registration. */\n setEnvironment(win: Window, environment: ShellEnvironment): void {\n const entry = registry.get(win);\n if (!entry) return;\n entry.environment = Object.freeze({\n capabilities: Object.freeze({ domains: Object.freeze([...environment.capabilities.domains]) }),\n services: Object.freeze([...environment.services]),\n });\n },\n\n /** Return the immutable environment captured before this frame executes. */\n getEnvironment(win: Window): ShellEnvironment | undefined {\n return registry.get(win)?.environment;\n },\n\n /**\n * Look up the monotonically increasing registration id for a Window.\n *\n * @param win - The Window reference to look up\n * @returns The registration id, or undefined if the Window is not registered\n */\n getRegistrationId(win: Window): number | undefined {\n return registry.get(win)?.registrationId;\n },\n\n /** Clear all registrations. */\n clear(): void {\n registry.clear();\n },\n};\n","/**\n * SessionRegistry — windowId to verified napplet pubkey bidirectional mapping.\n *\n * After a successful AUTH handshake, the ShellBridge registers the napplet's\n * verified pubkey here. Both mappings are kept in sync.\n */\n\nimport type { PendingUpdate, SessionEntry } from '@kehto/runtime';\n\n/**\n * A pending napplet update — raised when a napplet reconnects with a different aggregateHash.\n * @example\n * ```ts\n * const update: PendingUpdate = {\n * windowId: 'win-1', pubkey: 'abc...', dTag: '3chat',\n * oldHash: 'aaa', newHash: 'bbb',\n * resolve: (action) => { if (action === 'accept') { // apply } },\n * };\n * ```\n */\nexport type { PendingUpdate } from '@kehto/runtime';\n\nconst byWindowId = new Map<string, string>();\nconst byPubkey = new Map<string, SessionEntry>();\nconst pendingUpdates = new Map<string, PendingUpdate>();\n\nlet _pendingVersion = 0;\n\n/**\n * Bidirectional registry mapping windowIds to verified napplet pubkeys.\n * Maintained by ShellBridge after successful AUTH handshakes.\n *\n * @example\n * ```ts\n * import { sessionRegistry } from '@kehto/shell';\n *\n * const pubkey = sessionRegistry.getPubkey('win-1');\n * const entry = pubkey ? sessionRegistry.getEntry(pubkey) : undefined;\n * ```\n */\nexport interface SessionRegistry {\n register(windowId: string, entry: SessionEntry): void;\n unregister(windowId: string): void;\n getPubkey(windowId: string): string | undefined;\n getEntry(pubkey: string): SessionEntry | undefined;\n getWindowId(pubkey: string): string | undefined;\n isRegistered(windowId: string): boolean;\n getAllEntries(): SessionEntry[];\n setPendingUpdate(windowId: string, update: PendingUpdate): void;\n getPendingUpdate(windowId: string): PendingUpdate | undefined;\n clearPendingUpdate(windowId: string): void;\n clear(): void;\n}\n\n/** Shell-wide verified napplet session registry singleton. */\nexport const sessionRegistry: SessionRegistry = {\n /**\n * Register a napplet entry, mapping windowId to pubkey and vice versa.\n *\n * @param windowId - The window identifier\n * @param entry - The verified napplet session entry from AUTH handshake\n */\n register(windowId: string, entry: SessionEntry): void {\n byWindowId.set(windowId, entry.pubkey);\n byPubkey.set(entry.pubkey, entry);\n },\n\n /**\n * Unregister a napplet by windowId, removing both mappings.\n *\n * @param windowId - The window identifier to remove\n */\n unregister(windowId: string): void {\n const pubkey = byWindowId.get(windowId);\n if (pubkey) {\n byPubkey.delete(pubkey);\n byWindowId.delete(windowId);\n }\n pendingUpdates.delete(windowId);\n },\n\n /**\n * Get the pubkey associated with a windowId.\n *\n * @param windowId - The window identifier\n * @returns The napplet's pubkey, or undefined if not registered\n */\n getPubkey(windowId: string): string | undefined {\n return byWindowId.get(windowId);\n },\n\n /**\n * Get the full entry for a napplet pubkey.\n *\n * @param pubkey - The napplet's pubkey\n * @returns The full SessionEntry, or undefined if not found\n */\n getEntry(pubkey: string): SessionEntry | undefined {\n return byPubkey.get(pubkey);\n },\n\n /**\n * Get the windowId for a napplet pubkey.\n *\n * @param pubkey - The napplet's pubkey\n * @returns The windowId, or undefined if not found\n */\n getWindowId(pubkey: string): string | undefined {\n return byPubkey.get(pubkey)?.windowId;\n },\n\n /**\n * Check if a windowId has a registered napplet.\n *\n * @param windowId - The window identifier\n * @returns True if the windowId has a registered napplet\n */\n isRegistered(windowId: string): boolean {\n return byWindowId.has(windowId);\n },\n\n /**\n * Get all registered napplet entries.\n *\n * @returns Array of all SessionEntry objects\n */\n getAllEntries(): SessionEntry[] {\n return Array.from(byPubkey.values());\n },\n\n /**\n * Set a pending update for a window (napplet reconnected with different hash).\n *\n * @param windowId - The window identifier\n * @param update - The pending update details with resolve callback\n */\n setPendingUpdate(windowId: string, update: PendingUpdate): void {\n pendingUpdates.set(windowId, update);\n _pendingVersion++;\n if (typeof window !== 'undefined') {\n window.dispatchEvent(new CustomEvent('napplet:pending-update', { detail: { windowId } }));\n }\n },\n\n /**\n * Get a pending update for a window.\n *\n * @param windowId - The window identifier\n * @returns The pending update, or undefined if none\n */\n getPendingUpdate(windowId: string): PendingUpdate | undefined {\n return pendingUpdates.get(windowId);\n },\n\n /**\n * Clear a pending update for a window.\n *\n * @param windowId - The window identifier\n */\n clearPendingUpdate(windowId: string): void {\n pendingUpdates.delete(windowId);\n _pendingVersion++;\n if (typeof window !== 'undefined') {\n window.dispatchEvent(new CustomEvent('napplet:pending-update', { detail: { windowId } }));\n }\n },\n\n /** Clear all registrations and pending updates. */\n clear(): void {\n byWindowId.clear();\n byPubkey.clear();\n pendingUpdates.clear();\n },\n};\n\n/** @deprecated Use sessionRegistry. Will be removed in v0.9.0. */\nexport const nappKeyRegistry: SessionRegistry = sessionRegistry;\n","\nimport { ALL_CAPABILITIES, type Capability } from '@kehto/runtime';\nimport { migrateAclState, type AclState } from '@kehto/acl';\nimport type { AclEntry } from './types.js';\n\nconst STORAGE_KEY = 'napplet:acl';\n\n/** Default state quota in bytes (512 KB) per napplet identity. */\nexport const DEFAULT_STATE_QUOTA = 512 * 1024;\n\ninterface InternalAclEntry {\n key: string;\n pubkey: string;\n dTag: string;\n aggregateHash: string;\n capabilities: Set<Capability>;\n blocked: boolean;\n stateQuota: number;\n}\n\nfunction aclKey(_pubkey: string, dTag: string, aggregateHash: string): string {\n return `${dTag}:${aggregateHash}`;\n}\n\nconst store = new Map<string, InternalAclEntry>();\n\n// Capability name to bit position mapping for bitfield conversion.\n// Plan 12-10: signer bit slots (32/64/128) reclaimed by the v1.2\n// identity:read / keys:bind / keys:forward caps. v1.1 persisted ACL\n// state with those bits is reinterpreted under the v1.2 surface —\n// acceptable because the v1.1 signer actions have no napplet-visible\n// surface in NIP-5D.\nconst CAP_BITS: Record<string, number> = {\n 'relay:read': 1, 'relay:write': 2, 'cache:read': 4, 'cache:write': 8,\n 'hotkey:forward': 16,\n 'identity:read': 32, 'keys:bind': 64, 'keys:forward': 128,\n 'state:read': 256, 'state:write': 512,\n 'media:control': 1024, 'notify:send': 2048, 'notify:channel': 4096,\n 'theme:read': 8192,\n // 65536 RETIRED — was identity:decrypt (removed as a spec violation); left as\n // a permanent gap, do NOT reuse this bit.\n};\n\nfunction capArrayToBitfield(caps: Capability[]): number {\n let bits = 0;\n for (const cap of caps) bits |= (CAP_BITS[cap] ?? 0);\n return bits;\n}\n\nfunction bitfieldToCapArray(bits: number): Capability[] {\n return (Object.entries(CAP_BITS)\n .filter(([, bit]) => (bits & bit) !== 0)\n .map(([name]) => name)) as Capability[];\n}\n\nfunction getOrCreate(pubkey: string, dTag: string, aggregateHash: string): InternalAclEntry {\n const key = aclKey(pubkey, dTag, aggregateHash);\n let entry = store.get(key);\n if (!entry) {\n entry = {\n key,\n pubkey,\n dTag,\n aggregateHash,\n capabilities: new Set(ALL_CAPABILITIES),\n blocked: false,\n stateQuota: DEFAULT_STATE_QUOTA,\n };\n store.set(key, entry);\n }\n return entry;\n}\n\n/**\n * ACL store — manages capability grants, revocations, and blocks for napp identities.\n * Persists to localStorage and uses a permissive default policy (all capabilities granted).\n *\n * @example\n * ```ts\n * import { aclStore } from '@kehto/shell';\n *\n * aclStore.grant(pubkey, dTag, hash, 'relay:read');\n * const allowed = aclStore.check(pubkey, dTag, hash, 'relay:read'); // true\n * ```\n */\nexport interface AclStore {\n check(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): boolean;\n grant(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void;\n revoke(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void;\n block(pubkey: string, dTag: string, aggregateHash: string): void;\n unblock(pubkey: string, dTag: string, aggregateHash: string): void;\n isBlocked(pubkey: string, dTag: string, aggregateHash: string): boolean;\n getEntry(pubkey: string, dTag: string, aggregateHash: string): AclEntry | undefined;\n getAllEntries(): AclEntry[];\n persist(): void;\n load(): void;\n getStateQuota(pubkey: string, dTag: string, aggregateHash: string): number;\n clear(): void;\n}\n\n/** Shell ACL store singleton. */\nexport const aclStore: AclStore = {\n /**\n * Check if a napp identity has a specific capability.\n * Returns true for unknown identities (permissive default).\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @param capability - The capability to check\n * @returns True if the capability is granted and the napp is not blocked\n */\n check(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): boolean {\n const key = aclKey(pubkey, dTag, aggregateHash);\n const entry = store.get(key);\n if (!entry) return true;\n if (entry.blocked) return false;\n return entry.capabilities.has(capability);\n },\n\n /**\n * Grant a capability to a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @param capability - The capability to grant\n */\n grant(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void {\n getOrCreate(pubkey, dTag, aggregateHash).capabilities.add(capability);\n },\n\n /**\n * Revoke a capability from a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @param capability - The capability to revoke\n */\n revoke(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void {\n getOrCreate(pubkey, dTag, aggregateHash).capabilities.delete(capability);\n },\n\n /**\n * Block a napp identity entirely (all capabilities denied).\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n */\n block(pubkey: string, dTag: string, aggregateHash: string): void {\n getOrCreate(pubkey, dTag, aggregateHash).blocked = true;\n },\n\n /**\n * Unblock a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n */\n unblock(pubkey: string, dTag: string, aggregateHash: string): void {\n getOrCreate(pubkey, dTag, aggregateHash).blocked = false;\n },\n\n /**\n * Check if a napp identity is blocked.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @returns True if the identity is blocked\n */\n isBlocked(pubkey: string, dTag: string, aggregateHash: string): boolean {\n const key = aclKey(pubkey, dTag, aggregateHash);\n return store.get(key)?.blocked ?? false;\n },\n\n /**\n * Get the external ACL entry for a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @returns The ACL entry, or undefined if no explicit entry exists\n */\n getEntry(pubkey: string, dTag: string, aggregateHash: string): AclEntry | undefined {\n const key = aclKey(pubkey, dTag, aggregateHash);\n const internal = store.get(key);\n if (!internal) return undefined;\n return {\n pubkey: internal.pubkey,\n capabilities: Array.from(internal.capabilities),\n blocked: internal.blocked,\n stateQuota: internal.stateQuota,\n };\n },\n\n /**\n * Get all ACL entries.\n *\n * @returns Array of all ACL entries\n */\n getAllEntries(): AclEntry[] {\n return Array.from(store.values()).map(e => ({\n pubkey: e.pubkey,\n capabilities: Array.from(e.capabilities),\n blocked: e.blocked,\n stateQuota: e.stateQuota,\n }));\n },\n\n /** Persist the ACL store to localStorage. */\n persist(): void {\n try {\n const entries = Array.from(store.entries()).map(([key, val]) => [\n key,\n {\n pubkey: val.pubkey,\n dTag: val.dTag,\n aggregateHash: val.aggregateHash,\n capabilities: Array.from(val.capabilities),\n blocked: val.blocked,\n stateQuota: val.stateQuota,\n },\n ]);\n localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));\n } catch {\n // localStorage unavailable\n }\n },\n\n /** Load the ACL store from localStorage. Migrates old 3-segment keys to 2-segment format. */\n load(): void {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n let entries = JSON.parse(raw) as Array<\n [string, {\n pubkey: string;\n dTag?: string;\n aggregateHash?: string;\n capabilities: Capability[];\n blocked: boolean;\n stateQuota?: number;\n }]\n >;\n\n const hasOldKeys = entries.some(([key]) => key.split(':').length === 3);\n if (hasOldKeys) {\n const tempState: AclState = {\n defaultPolicy: 'permissive',\n entries: Object.fromEntries(\n entries.map(([key, val]) => [key, {\n caps: capArrayToBitfield(val.capabilities),\n blocked: val.blocked,\n quota: val.stateQuota ?? DEFAULT_STATE_QUOTA,\n }])\n ),\n };\n const migrated = migrateAclState(tempState);\n if (migrated !== tempState) {\n // Rebuild entries from migrated state\n entries = Object.entries(migrated.entries).map(([key, entry]) => {\n const parts = key.split(':');\n return [key, {\n pubkey: '',\n dTag: parts[0] ?? '',\n aggregateHash: parts[1] ?? '',\n capabilities: bitfieldToCapArray(entry.caps),\n blocked: entry.blocked,\n stateQuota: entry.quota,\n }] as [string, typeof entries[0][1]];\n });\n // Re-persist migrated data immediately\n localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));\n }\n }\n\n store.clear();\n for (const [key, val] of entries) {\n if (val.dTag === undefined || val.aggregateHash === undefined) continue;\n store.set(key, {\n key,\n pubkey: val.pubkey,\n dTag: val.dTag,\n aggregateHash: val.aggregateHash,\n capabilities: new Set(val.capabilities),\n blocked: val.blocked,\n stateQuota: val.stateQuota ?? DEFAULT_STATE_QUOTA,\n });\n }\n } catch {\n /* Corrupted ACL data in localStorage — clear and use defaults */\n store.clear();\n }\n },\n\n /**\n * Get the state quota for a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @returns The quota in bytes (defaults to DEFAULT_STATE_QUOTA)\n */\n getStateQuota(pubkey: string, dTag: string, aggregateHash: string): number {\n const key = aclKey(pubkey, dTag, aggregateHash);\n return store.get(key)?.stateQuota ?? DEFAULT_STATE_QUOTA;\n },\n\n /** Clear all ACL entries and remove from localStorage. */\n clear(): void {\n store.clear();\n try {\n localStorage.removeItem(STORAGE_KEY);\n } catch {\n /* localStorage unavailable — ACL clear is best-effort */\n }\n },\n};\n","/**\n * Manifest cache — persists verified NIP-5A aggregate hashes per napplet identity.\n */\n\n/**\n * A cached manifest entry for a verified napplet build.\n * @example\n * ```ts\n * const entry: ManifestCacheEntry = {\n * pubkey: 'abc123...', dTag: '3chat',\n * aggregateHash: 'deadbeef', verifiedAt: Date.now(),\n * };\n * ```\n */\nexport interface ManifestCacheEntry {\n pubkey: string;\n dTag: string;\n aggregateHash: string;\n verifiedAt: number;\n}\n\nconst STORAGE_KEY = 'napplet:manifest-cache';\nconst cache = new Map<string, ManifestCacheEntry>();\n\nfunction cacheKey(pubkey: string, dTag: string): string {\n return `${pubkey}:${dTag}`;\n}\n\n/**\n * Cache for verified napplet manifest entries. Persists to localStorage.\n * Used to detect napplet updates (aggregateHash changes) across sessions.\n *\n * @example\n * ```ts\n * import { manifestCache } from '@kehto/shell';\n *\n * manifestCache.set({ pubkey: 'abc...', dTag: 'chat', aggregateHash: 'dead', verifiedAt: Date.now() });\n * const entry = manifestCache.get('abc...', 'chat');\n * ```\n */\nexport interface ManifestCache {\n get(pubkey: string, dTag: string): ManifestCacheEntry | undefined;\n set(entry: ManifestCacheEntry): void;\n has(pubkey: string, dTag: string, hash: string): boolean;\n remove(pubkey: string, dTag: string): void;\n load(): void;\n persist(): void;\n clear(): void;\n}\n\n/** Shell-wide manifest verification cache singleton. */\nexport const manifestCache: ManifestCache = {\n /**\n * Get a cached manifest entry by pubkey and dTag.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @returns The cached entry, or undefined if not found\n */\n get(pubkey: string, dTag: string): ManifestCacheEntry | undefined {\n return cache.get(cacheKey(pubkey, dTag));\n },\n\n /**\n * Set (upsert) a manifest cache entry and persist to localStorage.\n *\n * @param entry - The manifest entry to cache\n */\n set(entry: ManifestCacheEntry): void {\n cache.set(cacheKey(entry.pubkey, entry.dTag), entry);\n manifestCache.persist();\n },\n\n /**\n * Check if a specific hash is cached for a pubkey/dTag combination.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param hash - The aggregateHash to check\n * @returns True if the exact hash matches the cached entry\n */\n has(pubkey: string, dTag: string, hash: string): boolean {\n const entry = cache.get(cacheKey(pubkey, dTag));\n return !!entry && entry.aggregateHash === hash;\n },\n\n /**\n * Remove a cached entry for a pubkey/dTag and persist.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n */\n remove(pubkey: string, dTag: string): void {\n cache.delete(cacheKey(pubkey, dTag));\n manifestCache.persist();\n },\n\n /** Load the cache from localStorage. */\n load(): void {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n const entries = JSON.parse(raw) as Array<[string, ManifestCacheEntry]>;\n cache.clear();\n for (const [key, val] of entries) cache.set(key, val);\n } catch { /* Corrupted cache data — clear and start fresh */ cache.clear(); }\n },\n\n /** Persist the cache to localStorage. */\n persist(): void {\n try {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(Array.from(cache.entries())));\n } catch { /* localStorage unavailable in sandboxed contexts — persist is best-effort */ }\n },\n\n /** Clear all cached entries and remove from localStorage. */\n clear(): void {\n cache.clear();\n try { localStorage.removeItem(STORAGE_KEY); } catch { /* localStorage unavailable — cleanup is best-effort */ }\n },\n};\n","/**\n * audio-manager.ts — Shell-side registry of active audio sources.\n *\n * Tracks which windows are producing audio. UI components read the registry\n * reactively via the version counter and CustomEvent pattern.\n */\n\nimport { originRegistry } from './origin-registry.js';\n\n/**\n * An active audio source registered by a napplet.\n * @example\n * ```ts\n * const source: AudioSource = {\n * windowId: 'win-1', nappletClass: 'music-player',\n * title: 'Now Playing', muted: false,\n * };\n * ```\n */\nexport interface AudioSource {\n windowId: string;\n nappletClass: string;\n title: string;\n muted: boolean;\n}\n\nconst sources: Map<string, AudioSource> = new Map<string, AudioSource>();\nlet version = 0;\n\nfunction bump(): void {\n version++;\n if (typeof window !== 'undefined') {\n window.dispatchEvent(new CustomEvent('napplet:audio-changed'));\n }\n}\n\n/**\n * Registry of active audio sources across all napplet windows.\n * Emits 'napplet:audio-changed' CustomEvents when the registry changes.\n *\n * @example\n * ```ts\n * import { audioManager } from '@kehto/shell';\n *\n * audioManager.register('win-1', 'music', 'My Song');\n * audioManager.mute('win-1', true);\n * ```\n */\nexport interface AudioManager {\n register(windowId: string, nappletClass: string, title: string): void;\n unregister(windowId: string): void;\n updateState(windowId: string, update: { title?: string }): void;\n mute(windowId: string, muted: boolean): void;\n has(windowId: string): boolean;\n get(windowId: string): AudioSource | undefined;\n getSources(): Map<string, AudioSource>;\n readonly version: number;\n readonly count: number;\n clear(): void;\n}\n\n/** Shell-wide audio source registry singleton. */\nexport const audioManager: AudioManager = {\n /**\n * Register a new audio source for a window.\n *\n * @param windowId - The window identifier\n * @param nappletClass - The napplet class/type (e.g., 'music-player')\n * @param title - Human-readable title for the audio source\n */\n register(windowId: string, nappletClass: string, title: string): void {\n sources.set(windowId, { windowId, nappletClass, title, muted: false });\n bump();\n },\n\n /**\n * Unregister an audio source for a window.\n *\n * @param windowId - The window identifier to remove\n */\n unregister(windowId: string): void {\n if (sources.delete(windowId)) bump();\n },\n\n /**\n * Update the state of an audio source (e.g., change title).\n *\n * @param windowId - The window identifier\n * @param update - Partial update with optional title\n */\n updateState(windowId: string, update: { title?: string }): void {\n const src = sources.get(windowId);\n if (!src) return;\n if (update.title !== undefined) src.title = update.title;\n bump();\n },\n\n /**\n * Mute or unmute an audio source and notify the napplet via postMessage.\n *\n * @param windowId - The window identifier\n * @param muted - True to mute, false to unmute\n * @example\n * ```ts\n * audioManager.mute('win-1', true); // mute\n * audioManager.mute('win-1', false); // unmute\n * ```\n */\n mute(windowId: string, muted: boolean): void {\n const src = sources.get(windowId);\n if (src) { src.muted = muted; bump(); }\n const iframeWindow = originRegistry.getIframeWindow(windowId);\n if (iframeWindow) {\n const muteEvent = {\n kind: 29000, // INC_PEER — inlined numeric after Phase 24 DRIFT-01 shim removal\n created_at: Math.floor(Date.now() / 1000),\n tags: [['t', 'napplet:audio-muted']],\n content: JSON.stringify({ muted }),\n pubkey: '__shell__',\n id: `audio-mute-${windowId}-${Date.now()}`,\n sig: '',\n };\n iframeWindow.postMessage(['EVENT', '__shell__', muteEvent], '*');\n }\n },\n\n /**\n * Check if a window has a registered audio source.\n *\n * @param windowId - The window identifier\n * @returns True if the window has an active audio source\n */\n has(windowId: string): boolean { return sources.has(windowId); },\n\n /**\n * Get the audio source for a window.\n *\n * @param windowId - The window identifier\n * @returns The AudioSource, or undefined if not found\n */\n get(windowId: string): AudioSource | undefined { return sources.get(windowId); },\n\n /**\n * Get a snapshot of all audio sources.\n *\n * @returns A new Map of all active audio sources\n */\n getSources(): Map<string, AudioSource> { return new Map(sources); },\n\n /** Current version counter (incremented on every change). */\n get version(): number { return version; },\n\n /** Number of active audio sources. */\n get count(): number { return sources.size; },\n\n /** Clear all audio sources and reset version counter. */\n clear(): void { sources.clear(); version = 0; },\n};\n","import type { OriginIdentity } from './origin-registry.js';\nimport type { ShellAdapter, ShellCapabilities, ShellEnvironment } from './types.js';\n\nconst RUNTIME_NATIVE_DOMAINS = [\n 'relay', 'identity', 'storage', 'inc', 'theme', 'keys', 'media', 'notify',\n] as const;\n\nconst SERVICE_ONLY_DOMAINS = [\n 'outbox', 'config', 'resource', 'cvm', 'upload', 'intent', 'link', 'common',\n 'lists', 'serial', 'ble', 'webrtc', 'dm', 'count',\n 'fs',\n] as const;\n\n/**\n * Build the shell's immutable live capability snapshot from adapter wiring.\n *\n * @param hooks - The ShellAdapter provided by the host app.\n * @returns Domain-only ShellCapabilities for the current live wiring.\n * @example\n * ```ts\n * const caps = buildShellCapabilities(hooks);\n * // caps.domains => ['relay', 'identity', 'storage', 'inc', 'theme', 'keys', 'media', 'notify']\n * ```\n */\nexport function buildShellCapabilities(hooks: ShellAdapter): ShellCapabilities {\n const disabled = new Set(hooks.capabilities?.disabledDomains ?? []);\n const domains: string[] = RUNTIME_NATIVE_DOMAINS.filter((domain) => !disabled.has(domain));\n\n for (const domain of SERVICE_ONLY_DOMAINS) {\n if (!disabled.has(domain) && isServiceDomainLive(hooks, domain)) domains.push(domain);\n }\n\n return Object.freeze({ domains: freezeList(domains) });\n}\n\n/**\n * Resolve a trusted creation identity's immutable NAP-SHELL environment.\n *\n * This host-adapter API is intentionally not part of `window.napplet`: it\n * bounds host policy to current runtime wiring before `shell.init` crosses into\n * an untrusted iframe.\n *\n * @param hooks - Shell host wiring and optional per-identity grant policy.\n * @param identity - The source's creation-time identity.\n * @returns A fresh immutable environment whose entries are exact live subsets.\n */\nexport function resolveShellEnvironment(\n hooks: ShellAdapter,\n identity: OriginIdentity,\n): ShellEnvironment {\n const capabilities = buildShellCapabilities(hooks);\n const disabled = new Set(hooks.capabilities?.disabledDomains ?? []);\n const services = getLiveServices(hooks, capabilities.domains, disabled);\n const available = Object.freeze({\n domains: freezeList(capabilities.domains),\n services: freezeList(services),\n });\n const granted = hooks.capabilities?.resolveEnvironment?.(identity, available) ?? available;\n\n return Object.freeze({\n capabilities: Object.freeze({\n domains: freezeList(intersectInOrder(available.domains, granted.domains)),\n }),\n services: freezeList(intersectInOrder(available.services, granted.services)),\n });\n}\n\nfunction isServiceDomainLive(hooks: ShellAdapter, domain: string): boolean {\n if (!hooks.services?.[domain]) return false;\n\n switch (domain) {\n case 'outbox': return Boolean(hooks.relayPool);\n case 'upload': return hooks.upload?.getUploader() !== null && hooks.upload?.getUploader() !== undefined;\n case 'intent': return hooks.intent?.isAvailable() === true;\n case 'link': return hooks.link?.isAvailable() === true;\n case 'common': return hooks.common?.isAvailable() === true;\n case 'lists': return hooks.lists?.isAvailable() === true;\n case 'serial': return hooks.serial?.isAvailable() === true;\n case 'ble': return hooks.ble?.isAvailable() === true;\n case 'webrtc': return hooks.webrtc?.isAvailable() === true;\n default: return true;\n }\n}\n\nfunction getLiveServices(\n hooks: ShellAdapter,\n domains: readonly string[],\n disabled: ReadonlySet<string>,\n): string[] {\n const liveDomains = new Set(domains);\n return Object.keys(hooks.services ?? {}).filter((name) => {\n if (disabled.has(name)) return false;\n return !SERVICE_ONLY_DOMAINS.includes(name as typeof SERVICE_ONLY_DOMAINS[number]) || liveDomains.has(name);\n });\n}\n\nfunction intersectInOrder(available: readonly string[], requested: readonly string[]): string[] {\n const requestedSet = new Set(requested);\n return available.filter((entry) => requestedSet.has(entry));\n}\n\nfunction freezeList(values: readonly string[]): readonly string[] {\n return Object.freeze([...values]);\n}\n","import type { Runtime, SessionEntry } from '@kehto/runtime';\nimport { originRegistry, type OriginIdentity } from './origin-registry.js';\nimport { resolveShellEnvironment } from './shell-init.js';\nimport type { ShellAdapter, ShellEnvironment } from './types.js';\n\ninterface ShellReadyOptions {\n hooks: ShellAdapter;\n origin: string;\n runtime: Runtime;\n state: ShellReadyState;\n sourceRegistrationId: number;\n sourceWindow: Window;\n windowId: string;\n}\n\n/** State owned by one ShellBridge instance for its NAP-SHELL lifecycles. */\nexport interface ShellReadyState {\n isDomainAllowed(windowId: string, domain: string): boolean;\n clear(): void;\n readonly initSent: WeakMap<Window, number>;\n readonly sessionRegistration: Map<string, number>;\n readonly environments: Map<string, ShellEnvironment>;\n}\n\n/** Create isolated handshake state for one bridge/runtime pair. */\nexport function createShellReadyState(): ShellReadyState {\n const initSent = new WeakMap<Window, number>();\n const sessionRegistration = new Map<string, number>();\n const environments = new Map<string, ShellEnvironment>();\n return {\n initSent,\n sessionRegistration,\n environments,\n isDomainAllowed(windowId, domain): boolean {\n return environments.get(windowId)?.capabilities.domains.includes(domain) ?? false;\n },\n clear(): void {\n sessionRegistration.clear();\n environments.clear();\n },\n };\n}\n\nexport function handleShellReady({\n hooks,\n origin,\n runtime,\n state,\n sourceRegistrationId,\n sourceWindow,\n windowId,\n}: ShellReadyOptions): void {\n // SHELL-01: exactly-once shell.init per registered Window lifecycle.\n if (state.initSent.get(sourceWindow) === sourceRegistrationId) {\n return;\n }\n\n const identity = resolveNip5dIdentity(hooks, windowId, sourceWindow);\n if (!identity) return;\n\n registerNip5dSessionIfNeeded({ origin, runtime, state, sourceRegistrationId, windowId, identity });\n const environment = originRegistry.getEnvironment(sourceWindow) ?? resolveShellEnvironment(hooks, identity);\n state.environments.set(windowId, environment);\n postShellInit(sourceWindow, environment);\n state.initSent.set(sourceWindow, sourceRegistrationId);\n}\n\nfunction registerNip5dSessionIfNeeded({\n origin,\n runtime,\n state,\n sourceRegistrationId,\n windowId,\n identity,\n}: Pick<ShellReadyOptions, 'origin' | 'runtime' | 'state' | 'sourceRegistrationId' | 'windowId'> & {\n identity: OriginIdentity;\n}): void {\n // NIP-5D: register a source-identity session entry in runtime.sessionRegistry\n // if one does not already exist for this windowId. This wires the originRegistry\n // identity into the runtime so domain handlers (storage/state, inc, etc.) can\n // resolve the napplet via getEntryByWindowId(windowId).\n const existing = runtime.sessionRegistry.getEntryByWindowId(windowId);\n const previousRegistration = state.sessionRegistration.get(windowId);\n if (existing && previousRegistration === sourceRegistrationId) {\n return;\n }\n if (existing && previousRegistration !== undefined) {\n runtime.sessionRegistry.unregister(windowId);\n }\n if (existing && previousRegistration === undefined) return;\n\n const entry: SessionEntry = {\n pubkey: '',\n windowId,\n origin,\n type: 'nip5d',\n dTag: identity.dTag,\n aggregateHash: identity.aggregateHash,\n registeredAt: Date.now(),\n instanceId: crypto.randomUUID(),\n provenance: 'nip-5d',\n };\n runtime.sessionRegistry.register(windowId, entry);\n state.sessionRegistration.set(windowId, sourceRegistrationId);\n}\n\nfunction resolveNip5dIdentity(\n hooks: ShellAdapter,\n windowId: string,\n sourceWindow: Window,\n): { dTag: string; aggregateHash: string } | null {\n // Identity resolution order:\n // 1. hooks.onNip5dIframeCreate?.(windowId) — preferred.\n // 2. originRegistry.getIdentity(win) — fallback for hosts that register\n // identity directly via originRegistry.register(win, windowId, identity).\n const hookIdentity = hooks.onNip5dIframeCreate?.(windowId);\n if (hookIdentity !== null && hookIdentity !== undefined) {\n return Object.freeze({\n dTag: hookIdentity.dTag,\n aggregateHash: hookIdentity.aggregateHash,\n });\n }\n\n const originIdentity = originRegistry.getIdentity(sourceWindow);\n if (!originIdentity) {\n return null;\n }\n\n return Object.freeze({\n dTag: originIdentity.dTag,\n aggregateHash: originIdentity.aggregateHash,\n });\n}\n\nfunction postShellInit(\n win: Window,\n environment: ShellEnvironment,\n): void {\n const initMsg = {\n type: 'shell.init',\n capabilities: environment.capabilities,\n services: environment.services,\n };\n win.postMessage(initMsg, '*');\n}\n","/**\n * The injected implementation must remain one self-contained function: the\n * renderer serializes it ahead of verified artifact scripts without changing\n * the signed artifact bytes. Splitting it into imported helpers would leave\n * unresolved closures in the generated `srcdoc`.\n *\n * aislop-ignore-file complexity/file-too-large complexity/function-too-long\n */\n\n/**\n * Options for rendering the host-owned NIP-5D `window.napplet` namespace prelude.\n *\n * @example\n * ```ts\n * const options: NappletNamespacePreludeOptions = {\n * domains: ['shell', 'relay', 'identity'],\n * };\n * ```\n */\nexport interface NappletNamespacePreludeOptions {\n /**\n * Optional bare NAP domain names the shell exposes to this napplet.\n * Mandatory `shell` is injected even when omitted here.\n */\n domains: readonly string[];\n}\n\nfunction uniqueBareDomains(domains: readonly string[]): string[] {\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const domain of domains) {\n const value = domain.trim();\n if (!value || value.includes(':') || value.startsWith('perm:') || seen.has(value)) {\n continue;\n }\n seen.add(value);\n normalized.push(value);\n }\n return normalized;\n}\n\nfunction scriptJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/**\n * Render the host-owned NIP-5D bootstrap that exposes available NAP domains\n * under `window.napplet` before napplet artifact code runs.\n *\n * @param options - Domain availability to inject.\n * @returns An inline script tag suitable for `srcdoc` prelude insertion.\n * @example\n * ```ts\n * const prelude = renderNappletNamespacePrelude({\n * domains: ['shell', 'relay', 'identity'],\n * });\n * ```\n */\nexport function renderNappletNamespacePrelude(options: NappletNamespacePreludeOptions): string {\n const domains = uniqueBareDomains(['shell', ...options.domains]);\n return `<script data-kehto-nip5d-injection>(${nappletNamespacePrelude.toString()})(${scriptJson(domains)});</script>`;\n}\n\n/**\n * Insert the NIP-5D namespace prelude into HTML before authored scripts.\n *\n * @param html - Verified napplet artifact HTML.\n * @param options - Domain availability to inject.\n * @returns HTML with the prelude inside `<head>` when possible.\n * @example\n * ```ts\n * const srcdoc = injectNappletNamespacePrelude(verifiedHtml, {\n * domains: ['shell', 'relay', 'identity'],\n * });\n * iframe.srcdoc = srcdoc;\n * ```\n */\nexport function injectNappletNamespacePrelude(\n html: string,\n options: NappletNamespacePreludeOptions,\n): string {\n const prelude = renderNappletNamespacePrelude(options);\n const cspMeta = /(<meta\\s+http-equiv=[\"']Content-Security-Policy[\"'][^>]*>)/i;\n if (cspMeta.test(html)) {\n return html.replace(cspMeta, (match) => `${match}${prelude}`);\n }\n if (/<head[^>]*>/i.test(html)) {\n return html.replace(/<head[^>]*>/i, (open) => `${open}${prelude}`);\n }\n if (/<html[^>]*>/i.test(html)) {\n return html.replace(/<html[^>]*>/i, (open) => `${open}<head>${prelude}</head>`);\n }\n return `${prelude}${html}`;\n}\n\nfunction nappletNamespacePrelude(domains: string[]): void {\n const target = window as Window & { napplet?: Record<string, unknown> };\n const allowed = new Set(domains);\n const requestTimeoutMs = 30_000;\n\n type RuntimeMessage = { type: string; id?: string; [key: string]: unknown };\n type Listener = (event: MessageEvent) => void;\n\n function id(): string {\n if (target.crypto?.randomUUID) return target.crypto.randomUUID();\n return `napplet-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n }\n\n function post(message: RuntimeMessage): void {\n target.parent.postMessage(message, '*');\n }\n\n function listen(listener: Listener): () => void {\n target.addEventListener('message', listener);\n return () => target.removeEventListener('message', listener);\n }\n\n function isParentMessage(event: MessageEvent): boolean {\n return event.source === target.parent;\n }\n\n function request<T>(\n message: RuntimeMessage,\n resultType: string,\n map: (message: RuntimeMessage) => T,\n options: {\n rejectOnError?: boolean;\n timeoutMs?: number | null;\n signal?: AbortSignal;\n cancelOnAbort?: boolean;\n } = {},\n ): Promise<T> {\n const requestId = message.id ?? id();\n const outbound = { ...message, id: requestId };\n const timeoutMs = options.timeoutMs === undefined ? requestTimeoutMs : options.timeoutMs;\n if (options.signal?.aborted) return Promise.reject(new DOMException('Aborted', 'AbortError'));\n return new Promise<T>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let off: (() => void) | undefined;\n const cleanup = (): void => {\n off?.();\n if (timer !== undefined) clearTimeout(timer);\n options.signal?.removeEventListener('abort', abort);\n };\n const abort = (): void => {\n cleanup();\n if (options.cancelOnAbort) post({ type: 'resource.cancel', id: requestId });\n reject(new DOMException('Aborted', 'AbortError'));\n };\n off = listen((event) => {\n if (!isParentMessage(event)) return;\n const incoming = event.data;\n if (typeof incoming !== 'object' || incoming === null) return;\n const msg = incoming as RuntimeMessage;\n if (msg.type !== resultType && msg.type !== `${message.type}.error`) return;\n if (msg.id !== requestId) return;\n cleanup();\n const error = typeof msg.error === 'string' ? msg.error : '';\n if (error && options.rejectOnError !== false) {\n reject(new Error(error));\n return;\n }\n try {\n resolve(map(msg));\n } catch (err) {\n reject(err);\n }\n });\n if (timeoutMs !== null) {\n timer = setTimeout(() => {\n cleanup();\n reject(new Error(`${message.type} timed out`));\n }, timeoutMs);\n }\n options.signal?.addEventListener('abort', abort, { once: true });\n post(outbound);\n });\n }\n\n function fire(message: RuntimeMessage): void {\n post(message);\n }\n\n function isConventionTopic(topic: string): boolean {\n const pathEnd = topic.search(/[?#]/);\n const path = pathEnd === -1 ? topic : topic.slice(0, pathEnd);\n return /^napplet:[^/?#]+\\/[^/?#]+$/.test(path);\n }\n\n function normalizeConventionUri(\n topic: unknown,\n hasExplicitPayload: boolean,\n ): { topic: string; payload?: Record<string, string> } {\n if (typeof topic !== 'string') throw new TypeError('INC topic must be text');\n if (!isConventionTopic(topic)) return { topic };\n if (topic.includes('#')) throw new TypeError('Convention topics cannot contain fragments');\n const queryStart = topic.indexOf('?');\n if (queryStart === -1) {\n return { topic };\n }\n if (hasExplicitPayload) {\n throw new TypeError('Convention queries cannot be combined with an explicit payload');\n }\n\n const entries: Array<[string, string]> = [];\n const names = new Set<string>();\n const query = topic.slice(queryStart + 1);\n if (query) {\n for (const pair of query.split('&')) {\n const separator = pair.indexOf('=');\n if (separator < 0) {\n throw new TypeError('Convention query parameters must use name=value form');\n }\n let name: string;\n let value: string;\n try {\n name = decodeURIComponent(pair.slice(0, separator));\n value = decodeURIComponent(pair.slice(separator + 1));\n } catch {\n throw new TypeError('Convention query contains malformed percent encoding');\n }\n if (names.has(name)) throw new TypeError('Convention query names must be unique');\n names.add(name);\n entries.push([name, value]);\n }\n }\n return { topic: topic.slice(0, queryStart), payload: Object.fromEntries(entries) };\n }\n\n function resultOrError(msg: RuntimeMessage): Record<string, unknown> {\n return msg;\n }\n\n function withoutEnvelope(msg: Record<string, unknown>): Record<string, unknown> {\n const { type: _type, id: _id, ...result } = msg;\n return result;\n }\n\n function fieldOrThrow<T>(msg: RuntimeMessage, field: string, fallback: string): T {\n if (Object.prototype.hasOwnProperty.call(msg, field)) return msg[field] as T;\n throw new Error(typeof msg.error === 'string' ? msg.error : fallback);\n }\n\n function voidResult(msg: RuntimeMessage, fallback: string): void {\n if (typeof msg.error === 'string' && msg.error) throw new Error(msg.error);\n if (msg.ok === false) throw new Error(fallback);\n }\n\n function subscriptionHandle(close: () => void): { close(): void } {\n let closed = false;\n return {\n close() {\n if (closed) return;\n closed = true;\n close();\n },\n };\n }\n\n function makeShell(): Record<string, unknown> {\n type ShellEnvironment = {\n capabilities: Readonly<{ domains: readonly string[] }>;\n services: readonly string[];\n };\n type ReadyHandler = (environment: ShellEnvironment) => void;\n\n const emptyServices = Object.freeze([] as string[]);\n const readyHandlers = new Set<ReadyHandler>();\n let environment: ShellEnvironment | undefined;\n let resolveReady: (environment: ShellEnvironment) => void = () => undefined;\n const ready = new Promise<ShellEnvironment>((resolve) => {\n resolveReady = resolve;\n });\n\n const off = listen((event) => {\n if (!isParentMessage(event) || environment) return;\n const incoming = event.data;\n if (typeof incoming !== 'object' || incoming === null) return;\n const message = incoming as RuntimeMessage;\n if (message.type !== 'shell.init') return;\n\n const rawCapabilities = message.capabilities;\n const rawDomains = typeof rawCapabilities === 'object' && rawCapabilities !== null\n ? (rawCapabilities as Record<string, unknown>).domains\n : undefined;\n if (!Array.isArray(rawDomains)) return;\n\n const domains = freezeStrings(rawDomains);\n const services = freezeStrings(Array.isArray(message.services) ? message.services : []);\n environment = Object.freeze({\n capabilities: Object.freeze({ domains }),\n services,\n });\n off();\n resolveReady(environment);\n for (const handler of readyHandlers) handler(environment);\n readyHandlers.clear();\n });\n\n function freezeStrings(values: readonly unknown[]): readonly string[] {\n const seen = new Set<string>();\n const strings: string[] = [];\n for (const value of values) {\n if (typeof value !== 'string' || value.length === 0 || seen.has(value)) continue;\n seen.add(value);\n strings.push(value);\n }\n return Object.freeze(strings);\n }\n\n function supports(domain: string): boolean {\n return typeof domain === 'string' && environment?.capabilities.domains.includes(domain) === true;\n }\n\n const shell = {\n ready: () => ready,\n supports,\n get services(): readonly string[] {\n return environment?.services ?? emptyServices;\n },\n set services(_services: readonly string[]) {\n // Ignore napplet/shim reassignment; NAP-SHELL services stay runtime-owned.\n },\n onReady(handler: ReadyHandler) {\n if (environment) {\n handler(environment);\n return subscriptionHandle(() => undefined);\n }\n readyHandlers.add(handler);\n return subscriptionHandle(() => readyHandlers.delete(handler));\n },\n };\n\n post({ type: 'shell.ready' });\n return shell;\n }\n\n function domainEventHandle(\n eventType: string,\n callback: (event: unknown) => void,\n select: (message: RuntimeMessage) => unknown = (message) => message.event,\n ): { close(): void } {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === eventType) callback(select(msg));\n });\n return subscriptionHandle(off);\n }\n\n function makeRelay(): Record<string, unknown> {\n return {\n subscribe(filters: unknown, onEvent: (result: unknown) => void, onEose: () => void, options?: { relay?: string }) {\n const subId = id();\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.subId !== subId) return;\n if (msg.type === 'relay.event') onEvent(msg.result);\n else if (msg.type === 'relay.eose') onEose();\n else if (msg.type === 'relay.closed') off();\n });\n fire({\n type: 'relay.subscribe',\n id: id(),\n subId,\n filters: Array.isArray(filters) ? filters : [filters],\n ...(options?.relay ? { relay: options.relay } : {}),\n });\n return subscriptionHandle(() => {\n fire({ type: 'relay.close', id: id(), subId });\n off();\n });\n },\n publish(template: unknown) {\n return request(\n { type: 'relay.publish', event: template },\n 'relay.publish.result',\n (msg) => {\n if (!msg.event) throw new Error('relay.publish.result missing event');\n return msg.event;\n },\n );\n },\n publishEncrypted(template: unknown, recipient: string, encryption = 'nip44') {\n return request(\n { type: 'relay.publishEncrypted', event: template, recipient, encryption },\n 'relay.publishEncrypted.result',\n (msg) => {\n if (!msg.event) throw new Error('relay.publishEncrypted.result missing event');\n return msg.event;\n },\n );\n },\n query(filters: unknown) {\n return request(\n { type: 'relay.query', filters: Array.isArray(filters) ? filters : [filters] },\n 'relay.query.result',\n (msg) => Array.isArray(msg.events) ? msg.events : [],\n );\n },\n };\n }\n\n function makeInc(): Record<string, unknown> {\n type IncEvent = { topic: string; sender: string; payload?: unknown };\n type TopicState = {\n handlers: Set<(event: IncEvent) => void>;\n offEvent: () => void;\n offResult: () => void;\n };\n const topicStates = new Map<string, TopicState>();\n type ChannelEvent = { channelId: string; sender: string; payload?: unknown };\n type ChannelClosed = { channelId: string; reason?: string };\n type ChannelState = {\n channelId: string;\n peer: string;\n eventHandlers: Set<(event: ChannelEvent) => void>;\n closedHandlers: Set<(closed: ChannelClosed) => void>;\n pendingEvents: ChannelEvent[];\n closed?: ChannelClosed;\n };\n const maxRetainedEvents = 32;\n const channelStates = new Map<string, ChannelState>();\n const openedHandlers = new Set<(handle: Record<string, unknown>) => void>();\n const pendingOpened: ChannelState[] = [];\n const unopenedEvents = new Map<string, ChannelEvent[]>();\n const unopenedClosed = new Map<string, ChannelClosed>();\n\n function stableSubscriptionTopic(topic: unknown): string {\n if (typeof topic !== 'string') throw new TypeError('INC topic must be text');\n if (isConventionTopic(topic) && (topic.includes('?') || topic.includes('#'))) {\n throw new TypeError('INC subscriptions require a queryless topic identity');\n }\n return topic;\n }\n\n function closeChannelState(state: ChannelState, closed: ChannelClosed, notifyShell: boolean): void {\n if (state.closed) return;\n state.closed = closed;\n if (notifyShell) fire({ type: 'inc.channel.close', channelId: state.channelId });\n for (const handler of state.closedHandlers) handler(closed);\n }\n\n function makeChannelHandle(state: ChannelState): Record<string, unknown> {\n return {\n id: state.channelId,\n peer: state.peer,\n emit(payload?: unknown) {\n if (state.closed) return;\n fire({ type: 'inc.channel.emit', channelId: state.channelId, ...(payload === undefined ? {} : { payload }) });\n },\n on(handler: (event: ChannelEvent) => void) {\n if (typeof handler !== 'function') throw new TypeError('INC channel event handler must be a function');\n state.eventHandlers.add(handler);\n const pending = state.pendingEvents.splice(0);\n for (const event of pending) handler(event);\n return subscriptionHandle(() => state.eventHandlers.delete(handler));\n },\n onClosed(handler: (closed: ChannelClosed) => void) {\n if (typeof handler !== 'function') throw new TypeError('INC channel close handler must be a function');\n state.closedHandlers.add(handler);\n if (state.closed) handler(state.closed);\n return subscriptionHandle(() => state.closedHandlers.delete(handler));\n },\n close() {\n closeChannelState(state, { channelId: state.channelId }, true);\n },\n };\n }\n\n function materializeChannel(channelId: string, peer: string): ChannelState {\n const existing = channelStates.get(channelId);\n if (existing) return existing;\n const state: ChannelState = {\n channelId,\n peer,\n eventHandlers: new Set(),\n closedHandlers: new Set(),\n pendingEvents: unopenedEvents.get(channelId) ?? [],\n };\n unopenedEvents.delete(channelId);\n channelStates.set(channelId, state);\n const closed = unopenedClosed.get(channelId);\n unopenedClosed.delete(channelId);\n if (closed) closeChannelState(state, closed, false);\n return state;\n }\n\n function deliverOpened(state: ChannelState): void {\n const handle = makeChannelHandle(state);\n if (openedHandlers.size > 0) {\n for (const handler of openedHandlers) handler(handle);\n return;\n }\n pendingOpened.push(state);\n }\n\n function receiveChannelEvent(channelId: string, sender: string, payloadPresent: boolean, payload: unknown): void {\n const event: ChannelEvent = payloadPresent ? { channelId, sender, payload } : { channelId, sender };\n const state = channelStates.get(channelId);\n if (!state) {\n const pending = unopenedEvents.get(channelId) ?? [];\n if (pending.length >= maxRetainedEvents) {\n unopenedEvents.delete(channelId);\n unopenedClosed.set(channelId, { channelId, reason: 'buffer overflow' });\n fire({ type: 'inc.channel.close', channelId });\n return;\n }\n pending.push(event);\n unopenedEvents.set(channelId, pending);\n return;\n }\n if (state.closed) return;\n if (state.eventHandlers.size > 0) {\n for (const handler of state.eventHandlers) handler(event);\n return;\n }\n if (state.pendingEvents.length >= maxRetainedEvents) {\n closeChannelState(state, { channelId, reason: 'buffer overflow' }, true);\n return;\n }\n state.pendingEvents.push(event);\n }\n\n listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || typeof msg.type !== 'string') return;\n if (msg.type === 'inc.channel.opened' && typeof msg.channelId === 'string' && typeof msg.peer === 'string') {\n deliverOpened(materializeChannel(msg.channelId, msg.peer));\n return;\n }\n if (msg.type === 'inc.channel.event' && typeof msg.channelId === 'string' && typeof msg.sender === 'string') {\n receiveChannelEvent(msg.channelId, msg.sender, Object.prototype.hasOwnProperty.call(msg, 'payload'), msg.payload);\n return;\n }\n if (msg.type === 'inc.channel.closed' && typeof msg.channelId === 'string') {\n const closed: ChannelClosed = typeof msg.reason === 'string'\n ? { channelId: msg.channelId, reason: msg.reason }\n : { channelId: msg.channelId };\n const state = channelStates.get(msg.channelId);\n if (state) closeChannelState(state, closed, false);\n else unopenedClosed.set(msg.channelId, closed);\n }\n });\n\n return {\n emit(topic: string, payload?: unknown) {\n const transposed = normalizeConventionUri(topic, arguments.length > 1);\n fire({\n type: 'inc.emit',\n topic: transposed.topic,\n ...(transposed.payload === undefined && payload === undefined ? {} : { payload: transposed.payload ?? payload }),\n });\n },\n on(topic: string, callback: (event: IncEvent) => void) {\n const stableTopic = stableSubscriptionTopic(topic);\n if (typeof callback !== 'function') throw new TypeError('INC subscription handler must be a function');\n let state = topicStates.get(stableTopic);\n if (!state) {\n const handlers = new Set<(event: IncEvent) => void>();\n const subscriptionId = id();\n const offEvent = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (\n typeof msg !== 'object'\n || msg === null\n || msg.type !== 'inc.event'\n || msg.topic !== stableTopic\n || typeof msg.sender !== 'string'\n ) return;\n const delivered: IncEvent = Object.prototype.hasOwnProperty.call(msg, 'payload')\n ? { topic: stableTopic, sender: msg.sender, payload: msg.payload }\n : { topic: stableTopic, sender: msg.sender };\n for (const handler of handlers) handler(delivered);\n });\n const offResult = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.type !== 'inc.subscribe.result' || msg.id !== subscriptionId) return;\n offResult();\n if (typeof msg.error === 'string' && msg.error) {\n offEvent();\n topicStates.delete(stableTopic);\n }\n });\n state = { handlers, offEvent, offResult };\n topicStates.set(stableTopic, state);\n fire({ type: 'inc.subscribe', id: subscriptionId, topic: stableTopic });\n }\n state.handlers.add(callback);\n const offLegacy = intentDelivery?.onLegacy(stableTopic, (delivery) => callback({\n topic: delivery.convention,\n sender: delivery.sender,\n ...(Object.prototype.hasOwnProperty.call(delivery, 'payload') ? { payload: delivery.payload } : {}),\n }));\n return subscriptionHandle(() => {\n offLegacy?.();\n const current = topicStates.get(stableTopic);\n if (!current) return;\n current.handlers.delete(callback);\n if (current.handlers.size !== 0) return;\n current.offEvent();\n current.offResult();\n topicStates.delete(stableTopic);\n fire({ type: 'inc.unsubscribe', topic: stableTopic });\n });\n },\n channel: {\n open(targetDTag: string) {\n return request(\n { type: 'inc.channel.open', target: targetDTag },\n 'inc.channel.open.result',\n (msg) => {\n if (typeof msg.channelId !== 'string' || typeof msg.peer !== 'string') {\n throw new Error('inc.channel.open.result missing channel identity');\n }\n return makeChannelHandle(materializeChannel(msg.channelId, msg.peer));\n },\n );\n },\n onOpened(handler: (handle: Record<string, unknown>) => void) {\n if (typeof handler !== 'function') throw new TypeError('INC opened handler must be a function');\n openedHandlers.add(handler);\n const pending = pendingOpened.splice(0);\n for (const state of pending) handler(makeChannelHandle(state));\n return subscriptionHandle(() => openedHandlers.delete(handler));\n },\n list() {\n return request(\n { type: 'inc.channel.list' },\n 'inc.channel.list.result',\n (msg) => Object.freeze((Array.isArray(msg.channels) ? msg.channels : []).flatMap((channel) => (\n channel\n && typeof channel === 'object'\n && typeof (channel as Record<string, unknown>).id === 'string'\n && typeof (channel as Record<string, unknown>).peer === 'string'\n ? [Object.freeze({\n id: (channel as Record<string, unknown>).id as string,\n peer: (channel as Record<string, unknown>).peer as string,\n })]\n : []\n ))),\n );\n },\n broadcast(payload?: unknown) {\n fire({ type: 'inc.channel.broadcast', ...(payload === undefined ? {} : { payload }) });\n },\n },\n };\n }\n\n function makeStorage(): Record<string, unknown> {\n const makeScope = (scope?: string) => ({\n getItem(key: string) {\n return request(\n { type: 'storage.get', key, ...(scope ? { scope } : {}) },\n 'storage.get.result',\n (msg) => msg.value ?? null,\n );\n },\n setItem(key: string, value: string) {\n return request(\n { type: 'storage.set', key, value, ...(scope ? { scope } : {}) },\n 'storage.set.result',\n () => undefined,\n );\n },\n removeItem(key: string) {\n return request(\n { type: 'storage.remove', key, ...(scope ? { scope } : {}) },\n 'storage.remove.result',\n () => undefined,\n );\n },\n keys() {\n return request(\n { type: 'storage.keys', ...(scope ? { scope } : {}) },\n 'storage.keys.result',\n (msg) => Array.isArray(msg.keys) ? msg.keys : [],\n );\n },\n });\n return { ...makeScope(), instance: makeScope('instance') };\n }\n\n function makeIdentity(): Record<string, unknown> {\n const read = <T>(type: string, field: string, fallback: T, payload: Record<string, unknown> = {}) => request(\n { type, ...payload },\n `${type}.result`,\n (msg) => (Object.prototype.hasOwnProperty.call(msg, field) ? msg[field] : fallback) as T,\n { rejectOnError: type !== 'identity.getPublicKey' },\n );\n return Object.freeze({\n getPublicKey: () => read('identity.getPublicKey', 'pubkey', ''),\n getRelays: () => read('identity.getRelays', 'relays', {}),\n getProfile: () => read('identity.getProfile', 'profile', null),\n getFollows: () => read('identity.getFollows', 'pubkeys', []),\n getList: (listType: string) => read('identity.getList', 'entries', [], { listType }),\n getZaps: () => read('identity.getZaps', 'zaps', []),\n getMutes: () => read('identity.getMutes', 'pubkeys', []),\n getBlocked: () => read('identity.getBlocked', 'pubkeys', []),\n getBadges: () => read('identity.getBadges', 'badges', []),\n onChanged(handler: (pubkey: string) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.type !== 'identity.changed') return;\n if (typeof msg.pubkey === 'string') handler(msg.pubkey);\n });\n return subscriptionHandle(off);\n },\n });\n }\n\n function makeTheme(): Record<string, unknown> {\n return {\n get: () => request({ type: 'theme.get' }, 'theme.get.result', (msg) => msg.theme),\n onChanged(handler: (theme: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'theme.changed') handler(msg.theme);\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n const keyActionCallbacks = new Map<string, Set<() => void>>();\n const keyBindingActions = new Map<string, string>();\n const modifierKeys = new Set(['Control', 'Alt', 'Shift', 'Meta']);\n const reservedKeyNames = new Set(['Tab', 'Escape']);\n const nonTextInputTypes = new Set([\n 'button',\n 'checkbox',\n 'color',\n 'file',\n 'hidden',\n 'image',\n 'radio',\n 'range',\n 'reset',\n 'submit',\n ]);\n let keysSmartForwardingInstalled = false;\n\n function normalizeKeyName(key: unknown): string {\n if (typeof key !== 'string') return '';\n return key.length === 1 ? key.toUpperCase() : key;\n }\n\n function keyComboKey(value: {\n ctrl: boolean;\n alt: boolean;\n shift: boolean;\n meta: boolean;\n key: string;\n }): string {\n return `${value.ctrl}|${value.alt}|${value.shift}|${value.meta}|${normalizeKeyName(value.key)}`;\n }\n\n function bindingComboKey(binding: unknown): string | null {\n if (typeof binding !== 'string' || binding.trim() === '') return null;\n const parts = binding.split('+');\n const key = parts.pop()?.trim();\n if (!key) return null;\n const combo = { ctrl: false, alt: false, shift: false, meta: false, key };\n for (const raw of parts) {\n const token = raw.trim().toLowerCase();\n if (!token) continue;\n if (token === 'ctrl' || token === 'control') combo.ctrl = true;\n else if (token === 'alt' || token === 'option') combo.alt = true;\n else if (token === 'shift') combo.shift = true;\n else if (token === 'meta' || token === 'cmd' || token === 'command' || token === 'win' || token === 'super') combo.meta = true;\n else return null;\n }\n return keyComboKey(combo);\n }\n\n function eventComboKey(event: {\n key?: unknown;\n ctrlKey?: unknown;\n altKey?: unknown;\n shiftKey?: unknown;\n metaKey?: unknown;\n }): string | null {\n const key = typeof event.key === 'string' ? event.key : '';\n if (!key) return null;\n return keyComboKey({\n ctrl: Boolean(event.ctrlKey),\n alt: Boolean(event.altKey),\n shift: Boolean(event.shiftKey),\n meta: Boolean(event.metaKey),\n key,\n });\n }\n\n function isTextEntryTarget(value: unknown): boolean {\n if (!value || typeof value !== 'object') return false;\n const targetNode = value as {\n tagName?: unknown;\n type?: unknown;\n isContentEditable?: unknown;\n closest?: (selector: string) => unknown;\n };\n if (targetNode.isContentEditable === true) return true;\n const tagName = typeof targetNode.tagName === 'string' ? targetNode.tagName.toLowerCase() : '';\n if (tagName === 'textarea' || tagName === 'select') return true;\n if (tagName === 'input') {\n const type = typeof targetNode.type === 'string' && targetNode.type ? targetNode.type.toLowerCase() : 'text';\n return !nonTextInputTypes.has(type);\n }\n if (typeof targetNode.closest === 'function') {\n try {\n return Boolean(targetNode.closest('[contenteditable=\"\"],[contenteditable=\"true\"],[contenteditable=\"plaintext-only\"]'));\n } catch {\n return false;\n }\n }\n return false;\n }\n\n function rememberKeyBinding(actionId: unknown, binding: unknown): void {\n if (typeof actionId !== 'string') return;\n const combo = bindingComboKey(binding);\n if (combo) keyBindingActions.set(combo, actionId);\n }\n\n function removeKeyBindingsForAction(actionId: string): void {\n for (const [combo, boundActionId] of keyBindingActions) {\n if (boundActionId === actionId) keyBindingActions.delete(combo);\n }\n }\n\n function replaceKeyBindings(bindings: unknown): void {\n keyBindingActions.clear();\n if (!Array.isArray(bindings)) return;\n for (const binding of bindings) {\n if (!binding || typeof binding !== 'object') continue;\n const entry = binding as { actionId?: unknown; key?: unknown };\n rememberKeyBinding(entry.actionId, entry.key);\n }\n }\n\n function notifyKeyAction(actionId: string): void {\n for (const callback of keyActionCallbacks.get(actionId) ?? []) callback();\n }\n\n function forwardKeyEvent(event: {\n key?: unknown;\n code?: unknown;\n ctrl?: unknown;\n alt?: unknown;\n shift?: unknown;\n meta?: unknown;\n ctrlKey?: unknown;\n altKey?: unknown;\n shiftKey?: unknown;\n metaKey?: unknown;\n } = {}): void {\n fire({\n type: 'keys.forward',\n key: typeof event.key === 'string' ? event.key : '',\n code: typeof event.code === 'string' ? event.code : '',\n ctrl: Boolean(event.ctrl ?? event.ctrlKey),\n alt: Boolean(event.alt ?? event.altKey),\n shift: Boolean(event.shift ?? event.shiftKey),\n meta: Boolean(event.meta ?? event.metaKey),\n });\n }\n\n function installKeysSmartForwarding(): void {\n if (keysSmartForwardingInstalled) return;\n keysSmartForwardingInstalled = true;\n\n listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'keys.bindings') {\n replaceKeyBindings(msg.bindings);\n }\n });\n\n const documentLike = target.document as {\n activeElement?: unknown;\n addEventListener?: (type: string, listener: (event: Event) => void) => void;\n } | undefined;\n const listenerTarget = typeof documentLike?.addEventListener === 'function' ? documentLike : target;\n if (typeof listenerTarget.addEventListener !== 'function') return;\n\n listenerTarget.addEventListener('keydown', (event: Event) => {\n const keyEvent = event as Event & {\n key?: string;\n code?: string;\n ctrlKey?: boolean;\n altKey?: boolean;\n shiftKey?: boolean;\n metaKey?: boolean;\n isComposing?: boolean;\n target?: unknown;\n preventDefault?: () => void;\n };\n if (keyEvent.isComposing) return;\n if (typeof keyEvent.key === 'string' && modifierKeys.has(keyEvent.key)) return;\n if (isTextEntryTarget(keyEvent.target ?? documentLike?.activeElement)) return;\n\n const combo = eventComboKey(keyEvent);\n const actionId = combo ? keyBindingActions.get(combo) : undefined;\n const isReserved = typeof keyEvent.key === 'string' && reservedKeyNames.has(keyEvent.key);\n if (actionId && !isReserved) {\n keyEvent.preventDefault?.();\n notifyKeyAction(actionId);\n return;\n }\n\n forwardKeyEvent(keyEvent);\n });\n }\n\n function makeKeys(): Record<string, unknown> {\n installKeysSmartForwarding();\n return {\n forward: forwardKeyEvent,\n registerAction: (action: unknown) => request(\n { type: 'keys.registerAction', action },\n 'keys.registerAction.result',\n resultOrError,\n ).then((result) => {\n const actionRecord = action && typeof action === 'object' ? action as { id?: unknown } : {};\n const resultRecord = result as { actionId?: unknown; binding?: unknown };\n rememberKeyBinding(\n typeof resultRecord.actionId === 'string' ? resultRecord.actionId : actionRecord.id,\n resultRecord.binding,\n );\n return result;\n }),\n unregisterAction: (actionId: string) => {\n removeKeyBindingsForAction(actionId);\n fire({ type: 'keys.unregisterAction', actionId });\n },\n onAction(actionId: string, callback: () => void) {\n let callbacks = keyActionCallbacks.get(actionId);\n if (!callbacks) {\n callbacks = new Set();\n keyActionCallbacks.set(actionId, callbacks);\n }\n callbacks.add(callback);\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'keys.action' && msg.actionId === actionId) callback();\n });\n return subscriptionHandle(() => {\n off();\n callbacks.delete(callback);\n if (callbacks.size === 0) keyActionCallbacks.delete(actionId);\n });\n },\n };\n }\n\n function makeMedia(): Record<string, unknown> {\n const on = (type: string, sessionId: string, callback: (msg: RuntimeMessage) => void) => {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === type && msg.sessionId === sessionId) callback(msg);\n });\n return subscriptionHandle(off);\n };\n return {\n createSession: (options: unknown) => request(\n { type: 'media.session.create', ...((options && typeof options === 'object') ? options as Record<string, unknown> : {}) },\n 'media.session.create.result',\n withoutEnvelope,\n { rejectOnError: false },\n ),\n updateSession: (sessionId: string, metadata: unknown) => fire({ type: 'media.session.update', sessionId, metadata }),\n destroySession: (sessionId: string) => fire({ type: 'media.session.destroy', sessionId }),\n reportState: (sessionId: string, state: unknown) => fire({ type: 'media.state', sessionId, ...((state && typeof state === 'object') ? state as Record<string, unknown> : {}) }),\n reportCapabilities: (sessionId: string, actions: unknown) => fire({ type: 'media.capabilities', sessionId, actions }),\n sendCommand: (sessionId: string, action: string, value?: unknown) => fire({ type: 'media.command', sessionId, action, ...(value === undefined ? {} : { value }) }),\n onCommand: (sessionId: string, callback: (action: unknown, value?: unknown) => void) => on('media.command', sessionId, (msg) => callback(msg.action, msg.value)),\n onState: (sessionId: string, callback: (state: Record<string, unknown>) => void) => on('media.state', sessionId, (msg) => callback({\n status: msg.status,\n position: msg.position,\n duration: msg.duration,\n volume: msg.volume,\n })),\n onCapabilities: (sessionId: string, callback: (actions: unknown) => void) => on('media.capabilities', sessionId, (msg) => callback(msg.actions)),\n onControls: (sessionId: string, callback: (controls: unknown) => void) => on('media.controls', sessionId, (msg) => callback(msg.controls)),\n };\n }\n\n function makeNotify(): Record<string, unknown> {\n const on = (type: string, callback: (msg: RuntimeMessage) => void) => {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === type) callback(msg);\n });\n return subscriptionHandle(off);\n };\n return {\n send: (notification: Record<string, unknown>) => request(\n { type: 'notify.send', ...notification },\n 'notify.send.result',\n (msg) => ({ notificationId: fieldOrThrow(msg, 'notificationId', 'notify.send.result missing notificationId') }),\n ),\n dismiss: (notificationId: string) => fire({ type: 'notify.dismiss', notificationId }),\n badge: (count: number) => fire({ type: 'notify.badge', count }),\n registerChannel: (channel: Record<string, unknown>) => fire({ type: 'notify.channel.register', ...channel }),\n requestPermission: (channel?: string) => request(\n { type: 'notify.permission.request', ...(channel ? { channel } : {}) },\n 'notify.permission.result',\n (msg) => ({ granted: msg.granted }),\n ),\n onAction: (callback: (notificationId: unknown, actionId: unknown) => void) => on('notify.action', (msg) => callback(msg.notificationId, msg.actionId)),\n onClicked: (callback: (notificationId: unknown) => void) => on('notify.clicked', (msg) => callback(msg.notificationId)),\n onDismissed: (callback: (notificationId: unknown, reason: unknown) => void) => on('notify.dismissed', (msg) => callback(msg.notificationId, msg.reason)),\n onControls: (callback: (controls: unknown) => void) => on('notify.controls', (msg) => callback(msg.controls)),\n };\n }\n\n function makeConfig(): Record<string, unknown> {\n let schema: unknown = null;\n return {\n registerSchema: (nextSchema: unknown, version?: number) => request(\n { type: 'config.registerSchema', schema: nextSchema, ...(version === undefined ? {} : { version }) },\n 'config.registerSchema.result',\n (msg) => {\n if (!msg.error) schema = nextSchema;\n return undefined;\n },\n ),\n get: () => request({ type: 'config.get' }, 'config.values', (msg) => msg.values ?? {}),\n subscribe(callback: (values: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'config.values') callback(msg.values ?? {});\n });\n fire({ type: 'config.subscribe' });\n return subscriptionHandle(() => {\n fire({ type: 'config.unsubscribe' });\n off();\n });\n },\n openSettings: (options?: unknown) => fire({ type: 'config.openSettings', ...((options && typeof options === 'object') ? options as Record<string, unknown> : {}) }),\n onSchemaError(callback: (error: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'config.schemaError') callback(msg);\n });\n return off;\n },\n get schema() {\n return schema;\n },\n };\n }\n\n function makeResource(): Record<string, unknown> {\n const objectUrls = new Set<string>();\n const bytes = (url: string, options?: { servers?: string[]; signal?: AbortSignal }) => request({\n type: 'resource.bytes',\n url,\n ...(Array.isArray(options?.servers) ? { servers: Array.from(options.servers) } : {}),\n }, 'resource.bytes.result', (msg) => msg.blob, {\n timeoutMs: null,\n signal: options?.signal,\n cancelOnAbort: true,\n });\n return {\n info: () => request({ type: 'resource.info' }, 'resource.info.result', (msg) => msg.info),\n bytes,\n bytesMany: (\n requests: Array<{ url: string; servers?: string[] }>,\n options?: { signal?: AbortSignal },\n ) => request({\n type: 'resource.bytesMany',\n requests: Array.from(requests || [], (entry) => ({\n url: entry.url,\n ...(Array.isArray(entry.servers) ? { servers: Array.from(entry.servers) } : {}),\n })),\n }, 'resource.bytesMany.result', (msg) => Array.isArray(msg.items) ? msg.items : [], {\n timeoutMs: null,\n signal: options?.signal,\n cancelOnAbort: true,\n }),\n bytesAsObjectURL(url: string) {\n let objectUrl = '';\n const handle = {\n get url() {\n return objectUrl;\n },\n revoke() {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrls.delete(objectUrl);\n objectUrl = '';\n }\n },\n };\n void bytes(url).then((blob) => {\n objectUrl = URL.createObjectURL(blob as Blob);\n objectUrls.add(objectUrl);\n });\n return handle;\n },\n hydrateResourceCache: () => undefined,\n revokeAllObjectURLs() {\n for (const url of objectUrls) URL.revokeObjectURL(url);\n objectUrls.clear();\n },\n };\n }\n\n function makeCvm(): Record<string, unknown> {\n const req = <T>(type: string, payload: Record<string, unknown>, map: (msg: RuntimeMessage) => T) => request(\n { type, ...payload },\n `${type}.result`,\n map,\n );\n const cvmRequest = (server: unknown, message: unknown, options?: Record<string, unknown>) => req(\n 'cvm.request',\n { server, message, ...(options === undefined ? {} : { options }) },\n (msg) => fieldOrThrow(msg, 'message', 'cvm.request.result missing message'),\n );\n const mcpCall = async (\n server: unknown,\n method: string,\n params?: Record<string, unknown>,\n options?: Record<string, unknown>,\n ) => {\n const reply = await cvmRequest(server, {\n jsonrpc: '2.0',\n id: id(),\n method,\n ...(params === undefined ? {} : { params }),\n }, options) as { result?: unknown; error?: { message?: string } | string };\n if (reply.error !== undefined) {\n const error = reply.error;\n throw new Error(typeof error === 'object' && error !== null && typeof error.message === 'string'\n ? `${method}: ${error.message}`\n : `${method} failed`);\n }\n return reply.result;\n };\n return {\n discover: (query?: unknown) => req('cvm.discover', query === undefined ? {} : { query }, (msg) => Array.isArray(msg.servers) ? msg.servers : []),\n request: cvmRequest,\n listTools: async (server: unknown, options?: Record<string, unknown>) => {\n const result = await mcpCall(server, 'tools/list', undefined, options) as { tools?: unknown[] } | undefined;\n return result?.tools ?? [];\n },\n callTool: (server: unknown, name: string, args?: unknown, options?: Record<string, unknown>) => mcpCall(\n server,\n 'tools/call',\n { name, ...(args === undefined ? {} : { arguments: args }) },\n options,\n ),\n listResources: async (server: unknown, options?: Record<string, unknown>) => {\n const result = await mcpCall(server, 'resources/list', undefined, options) as { resources?: unknown[] } | undefined;\n return result?.resources ?? [];\n },\n readResource: async (server: unknown, uri: string, options?: Record<string, unknown>) => {\n const result = await mcpCall(server, 'resources/read', { uri }, options) as { contents?: unknown[] } | undefined;\n const first = result?.contents?.[0];\n if (!first) throw new Error(`resources/read returned no contents for ${uri}`);\n return first;\n },\n close: (server: unknown) => req('cvm.close', { server }, (msg) => voidResult(msg, 'cvm close failed')),\n onEvent(callback: (server: unknown, message: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (\n typeof msg === 'object'\n && msg !== null\n && msg.type === 'cvm.event'\n && msg.server !== undefined\n && msg.message !== undefined\n ) {\n callback(msg.server, msg.message);\n }\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n function makeOutbox(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>, resultType = `${type}.result`) => request(\n { type, ...payload },\n resultType,\n resultOrError,\n { rejectOnError: false },\n );\n return {\n getEvent: (eventId: string, options?: Record<string, unknown>) => req('outbox.getEvent', { eventId, ...(options ? { options } : {}) }),\n query: (filters: unknown, options?: Record<string, unknown>) => req('outbox.query', { filters: Array.isArray(filters) ? filters : [filters], ...(options ? { options } : {}) }),\n subscribe(filters: unknown, options?: Record<string, unknown>) {\n const subId = id();\n const handlers = { event: new Set<(result: unknown) => void>(), closed: new Set<(reason?: unknown) => void>() };\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.subId !== subId) return;\n if (msg.type === 'outbox.event') for (const handler of handlers.event) handler(msg.result);\n if (msg.type === 'outbox.closed') {\n for (const handler of handlers.closed) handler(msg.reason);\n off();\n }\n });\n fire({ type: 'outbox.subscribe', id: id(), subId, filters: Array.isArray(filters) ? filters : [filters], ...(options ? { options } : {}) });\n return {\n on(event: 'event' | 'closed', handler: (value?: unknown) => void) {\n handlers[event].add(handler);\n return { close: () => handlers[event].delete(handler) };\n },\n close() {\n fire({ type: 'outbox.close', id: id(), subId });\n off();\n handlers.event.clear();\n handlers.closed.clear();\n },\n };\n },\n publish: (event: unknown, options?: Record<string, unknown>) => req('outbox.publish', { event, ...(options ? { options } : {}) }),\n resolveRelays: (targetValue: unknown) => req('outbox.resolveRelays', { target: targetValue }).then((msg) => msg.plan ?? msg),\n };\n }\n\n function makeUpload(): Record<string, unknown> {\n return {\n info: () => request({ type: 'upload.info' }, 'upload.info.result', (msg) => fieldOrThrow(msg, 'info', 'upload info unavailable')),\n upload: (requestPayload: unknown) => request({ type: 'upload.upload', request: requestPayload }, 'upload.upload.result', (msg) => fieldOrThrow(msg, 'result', 'upload failed')),\n status: (uploadId: string) => request({ type: 'upload.status', uploadId }, 'upload.status.result', (msg) => fieldOrThrow(msg, 'status', 'upload status unavailable')),\n onStatus(callback: (status: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'upload.status.changed' && msg.status !== undefined) callback(msg.status);\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n // NAP-INTENT@25b29ee: the packaged 0.32 binding lacks delivery support.\n // Keep this receiver live before shell.ready, independently of listener timing.\n function makeIntentDelivery() {\n type Delivery = Readonly<{\n sender: string; archetype: string; action: string; convention: string; payload?: unknown;\n }>;\n type Handler = (delivery: Delivery) => void;\n const handlers = new Set<Handler>();\n const legacy = new Map<Handler, string>();\n const pending: Delivery[] = [];\n let draining = false;\n let warned = false;\n\n function drain(): void {\n if (draining) return;\n draining = true;\n try {\n while (pending.length > 0) {\n const index = handlers.size > 0 ? 0 : pending.findIndex((delivery) =>\n [...legacy.values()].includes(delivery.convention));\n if (index < 0) break;\n const [delivery] = pending.splice(index, 1);\n const canonical = handlers.size > 0;\n const recipients = canonical ? [...handlers] : [...legacy.entries()]\n .filter(([, topic]) => topic === delivery.convention).map(([handler]) => handler);\n if (!canonical && !warned) {\n warned = true;\n console.warn('[KEHTO_COMPAT_INTENT_INC] Intent delivered to a legacy INC listener. Migrate to window.napplet.intent.onDelivery. See docs/compatibility.md.');\n }\n for (const handler of recipients) {\n try { handler(delivery); } catch (error) { console.error('Intent delivery handler failed', error); }\n }\n }\n } finally {\n draining = false;\n }\n }\n\n listen((event) => {\n if (!isParentMessage(event)) return;\n const message = event.data as RuntimeMessage | null;\n if (!message || message.type !== 'intent.deliver') return;\n const value = message.delivery;\n if (!value || typeof value !== 'object' || Array.isArray(value)) return;\n const delivery = value as Record<string, unknown>;\n if (typeof delivery.sender !== 'string' || typeof delivery.archetype !== 'string'\n || typeof delivery.action !== 'string' || typeof delivery.convention !== 'string') return;\n pending.push(Object.freeze({\n sender: delivery.sender, archetype: delivery.archetype,\n action: delivery.action, convention: delivery.convention,\n ...(Object.prototype.hasOwnProperty.call(delivery, 'payload') ? { payload: delivery.payload } : {}),\n }));\n drain();\n });\n return {\n onDelivery(handler: Handler) {\n if (typeof handler !== 'function') throw new TypeError('Intent delivery handler must be a function');\n handlers.add(handler);\n drain();\n return subscriptionHandle(() => handlers.delete(handler));\n },\n onLegacy(topic: string, handler: Handler) {\n legacy.set(handler, topic);\n drain();\n return () => legacy.delete(handler);\n },\n };\n }\n\n function makeIntent(): Record<string, unknown> {\n const hasOwn = (value: Record<string, unknown>, key: string): boolean => (\n Object.prototype.hasOwnProperty.call(value, key)\n );\n const normalizeRequest = (value: unknown): Record<string, unknown> => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError('Intent request must be an object');\n }\n const supplied = value as Record<string, unknown>;\n if (hasOwn(supplied, 'sender')) {\n throw new TypeError('Intent callers cannot supply sender');\n }\n const allowed = ['archetype', 'action', 'convention', 'payload', 'handler', 'behavior'];\n if (Object.keys(supplied).some((field) => !allowed.includes(field))) {\n throw new TypeError('Intent request contains unsupported fields');\n }\n if (typeof supplied.archetype !== 'string' || supplied.archetype.length === 0) {\n throw new TypeError('Intent request requires an archetype');\n }\n const action = supplied.action === undefined ? 'open' : supplied.action;\n if (typeof action !== 'string' || action.length === 0) {\n throw new TypeError('Intent action must be a non-empty string');\n }\n if (\n supplied.convention !== undefined\n && (\n typeof supplied.convention !== 'string'\n || !/^napplet:[^/?#\\s]+\\/[^/?#\\s]+$/.test(supplied.convention)\n )\n ) {\n throw new TypeError('Intent convention must be queryless');\n }\n if (\n supplied.handler !== undefined\n && (typeof supplied.handler !== 'string' || supplied.handler.length === 0)\n ) {\n throw new TypeError('Intent handler must be a non-empty string');\n }\n const behaviorValue = supplied?.behavior;\n const behavior = behaviorValue && typeof behaviorValue === 'object'\n ? behaviorValue as Record<string, unknown>\n : undefined;\n if (\n behaviorValue !== undefined\n && (\n !behavior\n || Array.isArray(behaviorValue)\n || Object.keys(behavior).some((field) =>\n field !== 'focus' && field !== 'newWindow' && field !== 'reuse')\n || (hasOwn(behavior, 'focus') && typeof behavior.focus !== 'boolean')\n || (hasOwn(behavior, 'newWindow') && typeof behavior.newWindow !== 'boolean')\n || (hasOwn(behavior, 'reuse') && typeof behavior.reuse !== 'boolean')\n )\n ) {\n throw new TypeError('Intent behavior contains unsupported fields');\n }\n const sanitizedBehavior = {\n ...(typeof behavior?.focus === 'boolean' ? { focus: behavior.focus } : {}),\n ...(typeof behavior?.newWindow === 'boolean'\n ? { newWindow: behavior.newWindow }\n : {}),\n ...(typeof behavior?.reuse === 'boolean' ? { reuse: behavior.reuse } : {}),\n };\n return {\n archetype: supplied.archetype,\n action,\n ...(typeof supplied.convention === 'string'\n ? { convention: supplied.convention }\n : {}),\n ...(hasOwn(supplied, 'payload') ? { payload: supplied.payload } : {}),\n ...(typeof supplied.handler === 'string' ? { handler: supplied.handler } : {}),\n ...(Object.keys(sanitizedBehavior).length === 0\n ? {}\n : { behavior: sanitizedBehavior }),\n };\n };\n const invoke = (value: unknown) => {\n const normalized = normalizeRequest(value);\n return request(\n {\n type: 'intent.invoke',\n request: normalized,\n },\n 'intent.invoke.result',\n (msg) => fieldOrThrow(msg, 'result', 'intent.invoke.result missing result'),\n );\n };\n return {\n onDelivery: intentDelivery!.onDelivery,\n invoke,\n open: (\n archetype: string,\n payload?: unknown,\n opts?: Record<string, unknown>,\n ) => invoke({\n archetype,\n action: 'open',\n ...(payload === undefined ? {} : { payload }),\n ...opts,\n }),\n available: (archetype: string) => request(\n { type: 'intent.available', archetype },\n 'intent.available.result',\n (msg) => fieldOrThrow(msg, 'availability', 'intent.available.result missing availability'),\n ),\n handlers: () => request(\n { type: 'intent.handlers' },\n 'intent.handlers.result',\n (msg) => fieldOrThrow(msg, 'handlers', 'intent.handlers.result missing handlers'),\n ),\n onChanged: (callback: (availability: unknown) => void) => domainEventHandle(\n 'intent.changed',\n callback,\n (msg) => msg.availability,\n ),\n };\n }\n\n function makeWebrtc(): Record<string, unknown> {\n return {\n open: (requestPayload?: unknown) => request(\n { type: 'webrtc.open', request: requestPayload },\n 'webrtc.open.result',\n (msg) => ({ session: fieldOrThrow(msg, 'session', 'webrtc.open.result missing session') }),\n ),\n send: (sessionId: string, payload: unknown) => request(\n { type: 'webrtc.send', sessionId, payload },\n 'webrtc.send.result',\n (msg) => voidResult(msg, 'webrtc send failed'),\n ),\n close: (sessionId: string, reason?: string) => request(\n { type: 'webrtc.close', sessionId, ...(reason ? { reason } : {}) },\n 'webrtc.close.result',\n (msg) => voidResult(msg, 'webrtc close failed'),\n ),\n onEvent: (callback: (event: unknown) => void) => domainEventHandle('webrtc.event', callback),\n };\n }\n\n function makeBle(): Record<string, unknown> {\n const req = (action: string, payload: Record<string, unknown>, map: (msg: RuntimeMessage) => unknown) => request(\n { type: `ble.${action}`, ...payload },\n `ble.${action}.result`,\n map,\n );\n return {\n open: (requestPayload?: unknown) => req('open', { request: requestPayload }, (msg) => ({ session: fieldOrThrow(msg, 'session', 'ble.open.result missing session') })),\n services: (sessionId: string) => req('services', { sessionId }, (msg) => fieldOrThrow(msg, 'services', 'ble.services.result missing services')),\n read: (sessionId: string, targetValue: unknown) => req('read', { sessionId, target: targetValue }, (msg) => fieldOrThrow(msg, 'data', 'ble.read.result missing data')),\n write: (sessionId: string, targetValue: unknown, data: unknown, options?: Record<string, unknown>) => req(\n 'write',\n { sessionId, target: targetValue, data, ...(options ? { options } : {}) },\n (msg) => voidResult(msg, 'ble write failed'),\n ),\n subscribe: (sessionId: string, targetValue: unknown) => req('subscribe', { sessionId, target: targetValue }, (msg) => voidResult(msg, 'ble subscribe failed')),\n unsubscribe: (sessionId: string, targetValue: unknown) => req('unsubscribe', { sessionId, target: targetValue }, (msg) => voidResult(msg, 'ble unsubscribe failed')),\n close: (sessionId: string, reason?: string) => req('close', { sessionId, ...(reason ? { reason } : {}) }, (msg) => voidResult(msg, 'ble close failed')),\n onEvent: (callback: (event: unknown) => void) => domainEventHandle('ble.event', callback),\n };\n }\n\n function makeSerial(): Record<string, unknown> {\n return {\n open: (requestPayload?: unknown) => request(\n { type: 'serial.open', request: requestPayload },\n 'serial.open.result',\n (msg) => ({ session: fieldOrThrow(msg, 'session', 'serial.open.result missing session') }),\n ),\n write: (sessionId: string, data: Uint8Array | number[]) => request(\n { type: 'serial.write', sessionId, data: Array.from(data) },\n 'serial.write.result',\n (msg) => voidResult(msg, 'serial write failed'),\n ),\n close: (sessionId: string, reason?: string) => request(\n { type: 'serial.close', sessionId, ...(reason === undefined ? {} : { reason }) },\n 'serial.close.result',\n (msg) => voidResult(msg, 'serial close failed'),\n ),\n onEvent: (callback: (event: unknown) => void) => domainEventHandle('serial.event', callback),\n };\n }\n\n function makeLink(): Record<string, unknown> {\n return {\n open: (url: string, options?: Record<string, unknown>) => request(\n { type: 'link.open', url, ...(options ? { options } : {}) },\n 'link.open.result',\n resultOrError,\n { rejectOnError: false },\n ),\n };\n }\n\n function makeCount(): Record<string, unknown> {\n return {\n query: (filters: unknown, options?: Record<string, unknown>) => request(\n { type: 'count.query', filters: Array.isArray(filters) ? filters : [filters], ...(options ? { options } : {}) },\n 'count.query.result',\n resultOrError,\n { rejectOnError: false },\n ),\n };\n }\n\n function makeLists(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>) => request({ type, ...payload }, `${type}.result`, resultOrError, { rejectOnError: false });\n return {\n supported: () => req('lists.supported', {}),\n add: (list: unknown, items: unknown, options?: unknown) => req('lists.add', { list, items, ...(options ? { options } : {}) }),\n remove: (list: unknown, items: unknown, options?: unknown) => req('lists.remove', { list, items, ...(options ? { options } : {}) }),\n };\n }\n\n function makeCommon(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>) => request({ type, ...payload }, `${type}.result`, withoutEnvelope, { rejectOnError: false });\n return {\n encodeNip19: (input: unknown) => req('common.encodeNip19', { input }),\n decodeNip19: (value: string) => req('common.decodeNip19', { value }),\n getProfile: (targetValue: unknown) => req('common.getProfile', { target: targetValue }),\n follows: () => req('common.follows', {}),\n follow: (...pubkeys: string[]) => req('common.follow', { pubkeys }),\n unfollow: (...pubkeys: string[]) => req('common.unfollow', { pubkeys }),\n react: (targetEventId: string, reaction?: string, customEmojiHref?: string) => req('common.react', {\n targetEventId,\n reaction,\n ...(customEmojiHref === undefined ? {} : { customEmojiHref }),\n }),\n report: (targetValue: unknown, reason?: string, text?: string) => req('common.report', {\n target: targetValue,\n reason,\n text,\n }),\n };\n }\n\n function makeDm(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>) => request({ type, ...payload }, `${type}.result`, withoutEnvelope, { rejectOnError: false });\n return {\n status: () => req('dm.status', {}),\n conversations: (query?: Record<string, unknown>) => req('dm.conversations', query ?? {}),\n messages: (query: Record<string, unknown>) => req('dm.messages', query ?? {}),\n send: (requestPayload: Record<string, unknown>) => req('dm.send', requestPayload ?? {}),\n subscribe: (requestPayload?: Record<string, unknown>) => req('dm.subscribe', requestPayload ?? {}),\n unsubscribe: (subscriptionId: string) => req('dm.unsubscribe', { subscriptionId }),\n onMessage(callback: (message: unknown, subscriptionId: string) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (\n typeof msg === 'object'\n && msg !== null\n && msg.type === 'dm.message'\n && typeof msg.subscriptionId === 'string'\n ) {\n callback(msg.message, msg.subscriptionId);\n }\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n function makeFs(): Record<string, unknown> {\n const withOptions = (payload: Record<string, unknown>, options: unknown) => {\n if (options !== undefined) payload.options = options;\n return payload;\n };\n const req = (\n action: string,\n payload: Record<string, unknown>,\n map: (msg: RuntimeMessage) => unknown,\n ) => request({ type: `fs.${action}`, ...payload }, `fs.${action}.result`, map);\n return {\n info: () => req('info', {}, (msg) => fieldOrThrow(msg, 'info', 'fs.info.result missing info')),\n pickFile: (options?: unknown) => req('pickFile', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickFile.result missing result')),\n pickFiles: (options?: unknown) => req('pickFiles', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickFiles.result missing result')),\n pickDirectory: (options?: unknown) => req('pickDirectory', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickDirectory.result missing result')),\n pickSaveFile: (options?: unknown) => req('pickSaveFile', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickSaveFile.result missing result')),\n stat: (path: string) => req('stat', { path }, (msg) => fieldOrThrow(msg, 'metadata', 'fs.stat.result missing metadata')),\n list: (path: string) => req('list', { path }, (msg) => fieldOrThrow(msg, 'entries', 'fs.list.result missing entries')),\n read: (path: string, options?: unknown) => req('read', withOptions({ path }, options), (msg) => fieldOrThrow(msg, 'result', 'fs.read.result missing result')),\n write: (path: string, data: string, options?: unknown) => req('write', withOptions({ path, data }, options), (msg) => fieldOrThrow(msg, 'result', 'fs.write.result missing result')),\n mkdir: (path: string, options?: unknown) => req('mkdir', withOptions({ path }, options), (msg) => voidResult(msg, 'fs mkdir failed')),\n remove: (path: string, recursive?: boolean) => req('remove', { path, ...(recursive === undefined ? {} : { recursive }) }, (msg) => voidResult(msg, 'fs remove failed')),\n move: (fromPath: string, toPath: string) => req('move', { fromPath, toPath }, (msg) => voidResult(msg, 'fs move failed')),\n watch: (path: string, options?: unknown) => req('watch', withOptions({ path }, options), (msg) => fieldOrThrow(msg, 'watchId', 'fs.watch.result missing watchId')),\n unwatch: (watchId: string) => req('unwatch', { watchId }, (msg) => voidResult(msg, 'fs unwatch failed')),\n onChanged: (callback: (change: unknown) => void) => domainEventHandle('fs.changed', callback, (msg) => msg.change),\n };\n }\n\n const intentDelivery = allowed.has('intent') ? makeIntentDelivery() : undefined;\n const shell = makeShell();\n let inc: Record<string, unknown> | undefined;\n let identity: Record<string, unknown> | undefined;\n let theme: Record<string, unknown> | undefined;\n let intent: Record<string, unknown> | undefined;\n\n function makeProtectedInc(existing: unknown): Record<string, unknown> {\n const extensions = existing && typeof existing === 'object'\n ? existing as Record<string, unknown>\n : {};\n inc ??= makeInc();\n return { ...extensions, ...inc };\n }\n\n function makeProtectedIdentity(): Record<string, unknown> {\n identity ??= makeIdentity();\n return identity;\n }\n\n function makeProtectedTheme(): Record<string, unknown> {\n theme ??= Object.freeze(makeTheme());\n return theme;\n }\n\n function makeProtectedIntent(): Record<string, unknown> {\n intent ??= Object.freeze(makeIntent());\n return intent;\n }\n\n function isProtectedDomain(domain: string): boolean {\n return domain === 'shell'\n || domain === 'inc'\n || domain === 'identity'\n || domain === 'theme'\n || domain === 'intent';\n }\n\n function makeDomain(domain: string, existing: unknown): unknown {\n if (domain === 'shell') return shell;\n if (domain === 'inc') return makeProtectedInc(existing);\n if (domain === 'identity') return makeProtectedIdentity();\n if (domain === 'theme') return makeProtectedTheme();\n if (domain === 'intent') return makeProtectedIntent();\n if (existing && typeof existing === 'object' && Object.keys(existing).length > 0) return existing;\n switch (domain) {\n case 'relay': return makeRelay();\n case 'storage': return makeStorage();\n case 'keys': return makeKeys();\n case 'media': return makeMedia();\n case 'notify': return makeNotify();\n case 'config': return makeConfig();\n case 'resource': return makeResource();\n case 'cvm': return makeCvm();\n case 'outbox': return makeOutbox();\n case 'upload': return makeUpload();\n case 'webrtc': return makeWebrtc();\n case 'ble': return makeBle();\n case 'link': return makeLink();\n case 'count': return makeCount();\n case 'lists': return makeLists();\n case 'common': return makeCommon();\n case 'serial': return makeSerial();\n case 'dm': return makeDm();\n case 'fs': return makeFs();\n default: return {};\n }\n }\n\n function guardNappletNamespace(namespace: Record<string, unknown>): Record<string, unknown> {\n return new Proxy(namespace, {\n set(obj, prop, value) {\n if (typeof prop !== 'string' || !allowed.has(prop)) return true;\n obj[prop] = makeDomain(prop, value);\n return true;\n },\n defineProperty(obj, prop, descriptor) {\n if (typeof prop !== 'string' || !allowed.has(prop)) return true;\n if (isProtectedDomain(prop)) {\n return Reflect.defineProperty(obj, prop, {\n value: makeDomain(prop, descriptor.value),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return Reflect.defineProperty(obj, prop, {\n ...descriptor,\n value: makeDomain(prop, descriptor.value),\n });\n },\n deleteProperty(obj, prop) {\n if (typeof prop === 'string' && allowed.has(prop) && isProtectedDomain(prop)) return true;\n return Reflect.deleteProperty(obj, prop);\n },\n });\n }\n\n function buildNappletNamespace(value: unknown): Record<string, unknown> {\n const candidate = typeof value === 'object' && value !== null\n ? value as Record<string, unknown>\n : {};\n const next: Record<string, unknown> = {};\n for (const domain of domains) {\n if (!allowed.has(domain)) continue;\n Object.defineProperty(next, domain, {\n value: makeDomain(\n domain,\n Object.prototype.hasOwnProperty.call(candidate, domain) ? candidate[domain] : undefined,\n ),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return guardNappletNamespace(next);\n }\n\n let root = buildNappletNamespace(target.napplet);\n Object.defineProperty(target, 'napplet', {\n get() {\n return root;\n },\n set(value) {\n root = buildNappletNamespace(value);\n },\n enumerable: false,\n configurable: false,\n });\n}\n","\n// Factory function — main entry point\nexport { createShellBridge } from './shell-bridge.js';\nexport type { ShellBridge } from './shell-bridge.js';\nexport {\n injectNappletNamespacePrelude,\n renderNappletNamespacePrelude,\n} from './napplet-namespace.js';\nexport type { NappletNamespacePreludeOptions } from './napplet-namespace.js';\n\n// Hooks adapter — for advanced integrators who need to customize the adapter\nexport { adaptHooks } from './hooks-adapter.js';\nexport type { BrowserDeps } from './hooks-adapter.js';\n\n// Protocol types (re-exported from @napplet/core + @kehto/runtime).\n// Phase 24 DRIFT-01: former @napplet/core compatibility shim deleted; legacy\n// NIP-01 constants no longer re-exported. Shell consumers import Capability +\n// ALL_CAPABILITIES from @kehto/runtime (sourced from @kehto/acl/capabilities).\nexport type { NostrEvent, NostrFilter, NappletMessage } from '@napplet/core';\nexport type { Capability } from '@kehto/runtime';\nexport { ALL_CAPABILITIES } from '@kehto/runtime';\n\n// Types for host app integration (shell-specific)\nexport type {\n ShellAdapter,\n ShellCapabilities,\n ShellEnvironment,\n RelayPoolHooks,\n RelayPoolLike,\n RelayConfigHooks,\n WindowManagerHooks,\n AuthHooks,\n ConfigHooks,\n HotkeyHooks,\n WorkerRelayHooks,\n WorkerRelayLike,\n CryptoHooks,\n DmHooks,\n UploadHooks,\n UploadBackendLike,\n IntentHooks,\n LinkHooks,\n CommonHooks,\n ListsHooks,\n SerialHooks,\n BleHooks,\n WebrtcHooks,\n CapabilityHooks,\n SessionEntry,\n NappKeyEntry, // @deprecated — use SessionEntry\n AclEntry,\n AclCheckEvent,\n UnroutedMessageInfo,\n ServiceDescriptor,\n ServiceHandler,\n ServiceRegistry,\n} from './types.js';\n\n// Shell initialization — capability construction for shell.ready / shell.init handshake\nexport { buildShellCapabilities, resolveShellEnvironment } from './shell-init.js';\n\nexport { sessionRegistry, nappKeyRegistry } from './session-registry.js';\nexport type { PendingUpdate, SessionRegistry } from './session-registry.js';\n\n// Standalone utilities (usable without full shell)\nexport { originRegistry } from './origin-registry.js';\nexport type { OriginIdentity, OriginRegistry } from './origin-registry.js';\nexport { audioManager } from './audio-manager.js';\nexport type { AudioManager, AudioSource } from './audio-manager.js';\nexport { manifestCache } from './manifest-cache.js';\nexport type { ManifestCache, ManifestCacheEntry } from './manifest-cache.js';\nexport type { AclStore } from './acl-store.js';\n\n// Enforcement gate (re-exported from @kehto/runtime for backwards compatibility)\nexport { createEnforceGate, createNapEnforceGate, formatDenialReason } from '@kehto/runtime';\nexport type { EnforceResult, EnforceConfig, NapEnforceConfig, IdentityResolver, AclChecker, NapMessage } from '@kehto/runtime';\n// ConsentRequest canonical definition re-exported from @kehto/runtime\nexport type { ConsentRequest } from '@kehto/runtime';\n\n// Topic constants for shell command routing\nexport { TOPICS } from './topics.js';\nexport type { TopicKey, TopicValue } from './topics.js';\n\nexport { createIdentityProxy } from './identity-proxy.js';\nexport type { IdentityProxy, IdentityProxyDeps, ProxyOriginRegistry } from './identity-proxy.js';\nexport { createThemeProxy } from './theme-proxy.js';\nexport type { ThemeProxy, ThemeProxyDeps } from './theme-proxy.js';\nexport { createKeysProxy } from './keys-proxy.js';\nexport type { KeysProxy, KeysProxyDeps } from './keys-proxy.js';\nexport { createMediaProxy } from './media-proxy.js';\nexport type { MediaProxy, MediaProxyDeps } from './media-proxy.js';\nexport { createNotifyProxy } from './notify-proxy.js';\nexport type { NotifyProxy, NotifyProxyDeps } from './notify-proxy.js';\n\nexport type {\n ResourceBytesRequest,\n ResourceInfo,\n ResourceInfoError,\n ResourceInfoRequest,\n ResourceInfoResult,\n ResourceBytesManyRequest,\n ResourceBytesManyItem,\n ResourceCancelRequest,\n ResourceBytesResult,\n ResourceBytesManyResult,\n ResourceBytesError,\n ResourceBytesManyError,\n ResourceErrorCode,\n ResourceRequestId,\n ResourceInbound,\n ResourceOutbound,\n} from './types/internal-resource.js';\n","/**\n * topics.ts — Re-exports topic constants from @napplet/core.\n *\n * Shell previously owned these constants. They now live in @napplet/core\n * so all packages share a single source of truth.\n */\nexport { TOPICS } from '@napplet/core';\nexport type { TopicKey, TopicValue } from '@napplet/core';\n","/**\n * identity-proxy.ts — Shell-side per-domain proxy for identity.* envelopes.\n *\n * Establishes the canonical proxy shape for @kehto/shell (Plan 12-11): each\n * per-domain proxy exposes a `dispatch` method that delegates napplet→shell\n * requests to the runtime.\n *\n * By default, `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime already owns identity.* dispatch per Plan\n * 12-03 (see @kehto/services identity-service). This module exists as an\n * optional composition point for host apps that want to intercept or\n * augment identity dispatch (e.g. custom logging, sandboxed rewrites, test\n * doubles).\n *\n * Identity changes are deliberately not emitted through this proxy. Hosts\n * must use `ShellBridge.publishIdentityChanged()`, which enforces the live\n * session, granted-domain, and current recipient-capability checks.\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\n\n/**\n * Minimal origin-registry contract used by per-domain proxies.\n *\n * Accepts the `@kehto/shell` singleton `originRegistry` as well as any test\n * double with a matching `getIframeWindow` method.\n */\nexport interface ProxyOriginRegistry {\n /** Resolve a registered napplet windowId to its iframe Window, or null. */\n getIframeWindow(windowId: string): Window | null;\n}\n\n/**\n * Dependencies for `createIdentityProxy`.\n *\n * @example\n * ```ts\n * const proxy = createIdentityProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface IdentityProxyDeps {\n /** The runtime engine that owns identity.* dispatch (Plan 12-03). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `identity.*` envelopes.\n *\n * `dispatch` routes napplet→shell requests into the runtime. The deprecated\n * `emit` member remains only as a fail-closed compatibility trap.\n */\nexport interface IdentityProxy {\n /**\n * Route a napplet-originated identity.* envelope into the runtime.\n *\n * Delegation only — the runtime already owns identity.* dispatch after\n * Plan 12-03. Override by wrapping or replacing this method.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Direct identity delivery is prohibited.\n *\n * @deprecated Use `ShellBridge.publishIdentityChanged()` so delivery is\n * filtered by live session, granted domain, and current ACL.\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical identity-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns An {@link IdentityProxy} ready to route identity.* envelopes\n * @example\n * ```ts\n * import { createIdentityProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const identityProxy = createIdentityProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Optional composition: intercept napplet->shell identity requests\n * const originalDispatch = identityProxy.dispatch;\n * identityProxy.dispatch = (windowId, envelope) => {\n * console.log('identity dispatch', windowId, envelope.type);\n * originalDispatch(windowId, envelope);\n * };\n * ```\n */\nexport function createIdentityProxy(deps: IdentityProxyDeps): IdentityProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(_windowId: string, _envelope: NappletMessage): void {\n throw new Error(\n 'Direct identity proxy emit is prohibited; use ShellBridge.publishIdentityChanged()',\n );\n },\n };\n}\n","/**\n * theme-proxy.ts — Shell-side per-domain proxy for theme.* envelopes.\n *\n * Establishes the shell-side shape that Phase 13 composes into. Phase 13 is\n * expected to add `theme-service.ts` (runtime) + the shell-side `theme.set`\n * API that emits `theme.changed` push envelopes to registered napplets;\n * this proxy is the canonical seam those pieces plug into.\n *\n * `dispatch(windowId, envelope)` routes napplet→shell `theme.get` into the\n * runtime. Theme changes must use `ShellBridge.publishTheme()` so the host\n * projection enforces live-session, granted-domain, and current-ACL checks.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns theme.* dispatch. This module is an\n * optional composition point for host apps or Phase 13 wiring.\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createThemeProxy`.\n *\n * @example\n * ```ts\n * const proxy = createThemeProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface ThemeProxyDeps {\n /** The runtime engine that will own theme.* dispatch (Phase 13). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `theme.*` envelopes.\n *\n * `dispatch` routes napplet→shell requests into the runtime. The deprecated\n * `emit` member remains only as a fail-closed compatibility trap.\n */\nexport interface ThemeProxy {\n /**\n * Route a napplet-originated theme.* envelope (e.g. `theme.get`) into\n * the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Direct theme delivery is prohibited.\n *\n * @deprecated Use `ShellBridge.publishTheme()` so delivery is filtered by\n * live session, granted domain, and current ACL.\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical theme-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link ThemeProxy} ready to route theme.* envelopes\n * @example\n * ```ts\n * import { createThemeProxy, originRegistry } from '@kehto/shell';\n *\n * const themeProxy = createThemeProxy({\n * runtime,\n * originRegistry,\n * });\n * themeProxy.dispatch(windowId, { type: 'theme.get', id: requestId });\n * ```\n */\nexport function createThemeProxy(deps: ThemeProxyDeps): ThemeProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(_windowId: string, _envelope: NappletMessage): void {\n throw new Error(\n 'Direct theme proxy emit is prohibited; use ShellBridge.publishTheme()',\n );\n },\n };\n}\n","/**\n * keys-proxy.ts — Shell-side per-domain proxy for keys.* envelopes.\n *\n * The runtime already dispatches napplet-originated `keys.*` (forward,\n * registerAction, unregisterAction) to the keys service. This proxy is the\n * shell-side composition point for host apps that want to observe requests or\n * inject shell-originated keys envelopes such as `keys.action` and\n * `keys.bindings`.\n *\n * Shape mirrors identity-proxy (Plan 12-11):\n *\n * - `dispatch(windowId, envelope)` routes napplet→shell keys requests\n * into the runtime.\n * - `emit(windowId, envelope)` posts shell→napplet pushes (`keys.action`,\n * `keys.bindings`, `keys.registerAction.result`) through the origin\n * registry.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns keys.* dispatch. This module is an\n * optional composition point for host apps (e.g. global hotkey UIs).\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createKeysProxy`.\n *\n * @example\n * ```ts\n * const proxy = createKeysProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface KeysProxyDeps {\n /** The runtime engine that owns keys.* dispatch (Plan 12-05). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `keys.*` envelopes.\n *\n * Shape: `dispatch` routes napplet→shell requests into the runtime; `emit`\n * pushes shell→napplet envelopes through the iframe's Window.\n */\nexport interface KeysProxy {\n /**\n * Route a napplet-originated keys.* envelope (e.g. `keys.forward`,\n * `keys.registerAction`) into the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Push a shell-initiated keys-domain envelope (e.g. `keys.action`,\n * `keys.bindings`) into a napplet iframe.\n *\n * No-op when the originRegistry cannot resolve the windowId (unknown or\n * unregistered napplet). Never throws.\n *\n * @param windowId - The target napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope to deliver\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical keys-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link KeysProxy} ready to route keys.* envelopes\n * @example\n * ```ts\n * import { createKeysProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const keysProxy = createKeysProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Host-app-initiated action trigger:\n * keysProxy.emit('win-editor', { type: 'keys.action', actionId: 'editor.save' });\n * ```\n */\nexport function createKeysProxy(deps: KeysProxyDeps): KeysProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(windowId: string, envelope: NappletMessage): void {\n const win = deps.originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(envelope, '*');\n },\n };\n}\n","/**\n * media-proxy.ts — Shell-side per-domain proxy for media.* envelopes.\n *\n * Establishes the shell-side composition seam for `@napplet/nap/media`\n * session-control envelopes. Shape mirrors identity-proxy (Plan 12-11):\n *\n * - `dispatch(windowId, envelope)` routes napplet→shell media requests\n * (`media.session.create`, `media.session.update`, `media.session.destroy`,\n * `media.state`, `media.capabilities`) into the runtime (Plan 12-06).\n * - `emit(windowId, envelope)` posts shell→napplet pushes (`media.command`,\n * `media.controls`, `media.session.create.result`) through the origin\n * registry.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns media.* dispatch. This module is an\n * optional composition point for host apps (e.g. shell-rendered playback\n * UIs that want to send `media.command` pushes).\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createMediaProxy`.\n *\n * @example\n * ```ts\n * const proxy = createMediaProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface MediaProxyDeps {\n /** The runtime engine that owns media.* dispatch (Plan 12-06). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `media.*` envelopes.\n *\n * Shape: `dispatch` routes napplet→shell requests into the runtime; `emit`\n * pushes shell→napplet envelopes through the iframe's Window.\n */\nexport interface MediaProxy {\n /**\n * Route a napplet-originated media.* envelope into the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Push a shell-initiated media-domain envelope (e.g. `media.command`,\n * `media.controls`) into a napplet iframe.\n *\n * No-op when the originRegistry cannot resolve the windowId (unknown or\n * unregistered napplet). Never throws.\n *\n * @param windowId - The target napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope to deliver\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical media-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link MediaProxy} ready to route media.* envelopes\n * @example\n * ```ts\n * import { createMediaProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const mediaProxy = createMediaProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Shell-UI-initiated media command:\n * mediaProxy.emit('win-player', {\n * type: 'media.command',\n * sessionId: 's1',\n * action: 'seek',\n * value: 120,\n * });\n * ```\n */\nexport function createMediaProxy(deps: MediaProxyDeps): MediaProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(windowId: string, envelope: NappletMessage): void {\n const win = deps.originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(envelope, '*');\n },\n };\n}\n","/**\n * notify-proxy.ts — Shell-side per-domain proxy for notify.* envelopes.\n *\n * Establishes the shell-side composition seam for `@napplet/nap/notify`\n * notification envelopes. Shape mirrors identity-proxy (Plan 12-11):\n *\n * - `dispatch(windowId, envelope)` routes napplet→shell notify requests\n * (`notify.send`, `notify.dismiss`, `notify.badge`,\n * `notify.channel.register`, `notify.permission.request`) into the\n * runtime (Plan 12-07).\n * - `emit(windowId, envelope)` posts shell→napplet pushes\n * (`notify.send.result`, `notify.permission.result`, `notify.action`,\n * `notify.clicked`, `notify.dismissed`, `notify.controls`) through the\n * origin registry.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns notify.* dispatch. This module is an\n * optional composition point for host apps (e.g. custom notification UIs\n * that need to emit `notify.clicked` / `notify.action` pushes).\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createNotifyProxy`.\n *\n * @example\n * ```ts\n * const proxy = createNotifyProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface NotifyProxyDeps {\n /** The runtime engine that owns notify.* dispatch (Plan 12-07). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `notify.*` envelopes.\n *\n * Shape: `dispatch` routes napplet→shell requests into the runtime; `emit`\n * pushes shell→napplet envelopes through the iframe's Window.\n */\nexport interface NotifyProxy {\n /**\n * Route a napplet-originated notify.* envelope into the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Push a shell-initiated notify-domain envelope (e.g. `notify.action`,\n * `notify.clicked`) into a napplet iframe.\n *\n * No-op when the originRegistry cannot resolve the windowId (unknown or\n * unregistered napplet). Never throws.\n *\n * @param windowId - The target napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope to deliver\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical notify-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link NotifyProxy} ready to route notify.* envelopes\n * @example\n * ```ts\n * import { createNotifyProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const notifyProxy = createNotifyProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Shell-UI notifies napplet that user clicked its toast:\n * notifyProxy.emit('win-chat', {\n * type: 'notify.clicked',\n * notificationId: 'shell-42',\n * });\n * ```\n */\nexport function createNotifyProxy(deps: NotifyProxyDeps): NotifyProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(windowId: string, envelope: NappletMessage): void {\n const win = deps.originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(envelope, '*');\n },\n };\n}\n"],"mappings":";AACA,SAAS,qBAAwD;;;AC6BjE,SAAS,WAAW,OAA2B;AAC7C,SAAO,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC1E;AAEA,SAAS,WAAW,KAAyB;AAC3C,QAAM,QAAQ,IAAI,WAAW,IAAI,SAAS,CAAC;AAC3C,WAAS,IAAI,GAAG,IAAI,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,IAAK,KAAI,YAAY,UAAU,GAAG;AAAA,IACxC;AAAA,EACF;AACF;","names":["originRegistry","STORAGE_KEY","domains","shell","version","delivery","allowed","ALL_CAPABILITIES"]}
|
|
1
|
+
{"version":3,"sources":["../src/shell-bridge.ts","../src/hooks-adapter.ts","../src/origin-registry.ts","../src/session-registry.ts","../src/acl-store.ts","../src/manifest-cache.ts","../src/audio-manager.ts","../src/shell-init.ts","../src/shell-ready.ts","../src/intent-uri.ts","../src/napplet-namespace.ts","../src/napplet-head.ts","../src/napplet-csp.ts","../src/napplet-srcdoc.ts","../src/index.ts","../src/topics.ts","../src/identity-proxy.ts","../src/theme-proxy.ts","../src/keys-proxy.ts","../src/media-proxy.ts","../src/notify-proxy.ts"],"sourcesContent":["\nimport { createRuntime, type ConsentRequest, type Runtime } from '@kehto/runtime';\nimport { adaptHooks } from './hooks-adapter.js';\nimport { originRegistry } from './origin-registry.js';\nimport { nappKeyRegistry } from './session-registry.js';\nimport { aclStore } from './acl-store.js';\nimport { manifestCache } from './manifest-cache.js';\nimport { audioManager } from './audio-manager.js';\nimport type { ShellAdapter, UnroutedMessageInfo } from './types.js';\nimport type { NappletMessage } from '@napplet/core';\nimport type { Theme } from '@napplet/nap/theme/types';\nimport { createShellReadyState, handleShellReady } from './shell-ready.js';\n\n/**\n * Shell-side message bridge that handles NIP-5D communication with napplet iframes.\n *\n * The bridge acts as a browser adapter: it receives raw MessageEvents from\n * window.addEventListener('message', ...), extracts the source Window, resolves\n * it to a windowId via originRegistry, and delegates NIP-5D envelope messages\n * to the runtime engine. The shell.ready/shell.init capability handshake is\n * handled locally within the bridge and never forwarded to the runtime.\n *\n * @example\n * ```ts\n * import { createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * window.addEventListener('message', bridge.handleMessage);\n * ```\n */\nexport interface ShellBridge {\n /**\n * Handle an incoming postMessage from a napplet iframe.\n *\n * Only NIP-5D envelope objects (plain objects with a `.type` string) are\n * accepted. NIP-01 arrays and all other message shapes are silently dropped\n * (clean break — no legacy array fallback).\n *\n * shell.ready messages are handled locally: the bridge responds with shell.init\n * containing the capability set and registered service list. All other envelopes\n * are delegated to the runtime's NAP domain dispatch.\n *\n * @param event - The raw MessageEvent from window.addEventListener('message', ...)\n * @example\n * ```ts\n * window.addEventListener('message', bridge.handleMessage);\n * ```\n */\n handleMessage(event: MessageEvent): void;\n\n /**\n * Inject a shell-originated event into subscription delivery. Under NIP-5D,\n * shell-originated events are forwarded to napplets as inc.event envelope\n * messages. The runtime's injectEvent() handles the per-session routing.\n *\n * v1.10 hard-removed the v1.8 soft-rename compatibility branch for the\n * old `auth:identity-changed` topic. Use the canonical `identity:changed`\n * topic for identity-change pushes.\n *\n * @param topic - The event topic tag value. Forwarded exactly once.\n * @param payload - The event content\n * @example\n * ```ts\n * bridge.injectEvent('identity:changed', { pubkey: userPubkey });\n * ```\n */\n injectEvent(topic: string, payload: unknown): void;\n\n /**\n * Destroy the bridge instance, cleaning up all internal state.\n * Persists manifest cache and clears all subscriptions, buffers, and registries.\n * Call when the shell is shutting down or the bridge is no longer needed.\n *\n * @example\n * ```ts\n * bridge.destroy();\n * ```\n */\n destroy(): void;\n\n /**\n * Register a handler for consent requests on destructive signing kinds.\n * Called when a napplet requests signing for kinds 0, 3, 5, or 10002.\n *\n * @param handler - Callback receiving the consent request with a resolve function\n * @example\n * ```ts\n * bridge.registerConsentHandler((request) => {\n * const allowed = confirm(`Allow signing kind ${request.event.kind}?`);\n * request.resolve(allowed);\n * });\n * ```\n */\n registerConsentHandler(handler: (request: ConsentRequest) => void): void;\n\n /**\n * Publish a theme update to each eligible napplet.\n *\n * Posts a `theme.changed` envelope (shell → napplet push) to every\n * live authenticated session whose frozen environment grants `theme` and\n * whose current ACL grants `theme:read`. Stale or ineligible sessions are\n * skipped before origin-registry delivery; recipient code is not trusted\n * to enforce host authorization.\n *\n * @param theme - The new theme payload to broadcast.\n * @example\n * ```ts\n * bridge.publishTheme({\n * colors: { background: '#0a0a0a', text: '#e0e0e0', primary: '#7aa2f7' },\n * title: 'Dark',\n * });\n * ```\n */\n publishTheme(theme: Theme): void;\n\n /**\n * Publish the current shell-user identity to every loaded napplet.\n *\n * Posts an `identity.changed` envelope (shell → napplet push) with the\n * current user pubkey. An empty pubkey means no signer/user identity is\n * currently connected. This is distinct from NIP-5D napplet session identity,\n * which remains source-bound at iframe creation.\n *\n * @param pubkey - Current user's hex pubkey, or empty string when signed out.\n */\n publishIdentityChanged(pubkey: string): void;\n\n /**\n * Access the underlying runtime instance for advanced use cases.\n * Provides direct access to the runtime's sessionRegistry, aclState,\n * and manifestCache.\n */\n readonly runtime: Runtime;\n\n}\n\n/**\n * Create a ShellBridge instance with dependency injection via hooks.\n *\n * Internally creates a Runtime from @kehto/runtime and adapts the\n * browser-oriented ShellAdapter into environment-agnostic RuntimeAdapter.\n *\n * @param hooks - Host application provides relay pool, auth, config, etc.\n * @returns A ShellBridge instance ready to handle napplet messages\n * @example\n * ```ts\n * import { createShellBridge, type ShellAdapter } from '@kehto/shell';\n *\n * const hooks: ShellAdapter = {\n * relayPool: myRelayPoolHooks,\n * relayConfig: myRelayConfigHooks,\n * windowManager: myWindowManagerHooks,\n * auth: myAuthHooks,\n * config: myConfigHooks,\n * hotkeys: myHotkeyHooks,\n * workerRelay: myWorkerRelayHooks,\n * crypto: myCryptoHooks,\n * };\n * const bridge = createShellBridge(hooks);\n * ```\n */\n/**\n * Fire the optional {@link ShellAdapter.onUnroutedMessage} diagnostic hook for a\n * message the bridge is about to drop. Extracts the envelope `type` defensively\n * (the message-shape guard hasn't run yet at the drop points) and never throws —\n * a misbehaving host hook must not break message handling.\n */\nfunction reportUnrouted(\n hooks: ShellAdapter,\n event: MessageEvent,\n reason: UnroutedMessageInfo['reason'],\n): void {\n if (!hooks.onUnroutedMessage) return;\n const data = event.data as { type?: unknown } | null | undefined;\n const type = typeof data === 'object' && data !== null && typeof data.type === 'string'\n ? data.type\n : undefined;\n try {\n hooks.onUnroutedMessage({ type, origin: event.origin, reason });\n } catch {\n // Observability must never break routing — swallow host hook errors.\n }\n}\n\nexport function createShellBridge(hooks: ShellAdapter): ShellBridge {\n const shellReadyState = createShellReadyState();\n const runtimeHooks = adaptHooks(hooks, {\n originRegistry,\n manifestCache,\n aclStore,\n audioManager,\n nappKeyRegistry,\n });\n\n const runtime: Runtime = createRuntime({\n ...runtimeHooks,\n isDomainAllowed: shellReadyState.isDomainAllowed,\n });\n\n function publishToEligibleNapplets(\n envelope: NappletMessage,\n domain: 'identity' | 'theme',\n capability: 'identity:read' | 'theme:read',\n ): void {\n // A session exists only after shell.ready. Iterate entries, not a pubkey\n // lookup, because different live windows may legitimately share pubkey ''.\n for (const entry of runtime.sessionRegistry.getAllEntries()) {\n const environment = shellReadyState.environments.get(entry.windowId);\n if (!environment?.capabilities.domains.includes(domain)) continue;\n if (!runtime.aclState.check(entry.pubkey, entry.dTag, entry.aggregateHash, capability)) continue;\n\n const win = originRegistry.getIframeWindow(entry.windowId);\n if (!win) continue;\n win.postMessage(envelope, '*');\n }\n }\n\n return {\n handleMessage(event: MessageEvent): void {\n const sourceWindow = event.source as Window | null;\n if (!sourceWindow) {\n reportUnrouted(hooks, event, 'no-source-window');\n return;\n }\n const windowId = originRegistry.getWindowId(sourceWindow);\n if (!windowId) {\n reportUnrouted(hooks, event, 'unregistered-window');\n return;\n }\n const msg = event.data;\n\n // NIP-5D envelope-only guard (clean break — no legacy array support)\n if (typeof msg !== 'object' || msg === null || typeof msg.type !== 'string') return;\n\n // Handle shell.ready handshake locally (not forwarded to runtime)\n if (msg.type === 'shell.ready') {\n handleShellReady({\n hooks,\n origin: event.origin,\n runtime,\n state: shellReadyState,\n sourceRegistrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0,\n sourceWindow,\n windowId,\n });\n return;\n }\n\n // Delegate to runtime — runtime handles NAP domain dispatch\n runtime.handleMessage(windowId, msg);\n },\n\n injectEvent(topic: string, payload: unknown): void {\n runtime.injectEvent(topic, payload);\n },\n\n destroy(): void {\n runtime.destroy();\n shellReadyState.clear();\n },\n\n registerConsentHandler(handler: (request: ConsentRequest) => void): void {\n runtime.registerConsentHandler(handler);\n },\n\n publishTheme(theme: Theme): void {\n const envelope: NappletMessage = { type: 'theme.changed', theme } as NappletMessage;\n publishToEligibleNapplets(envelope, 'theme', 'theme:read');\n },\n\n publishIdentityChanged(pubkey: string): void {\n const envelope: NappletMessage = { type: 'identity.changed', pubkey } as NappletMessage;\n publishToEligibleNapplets(envelope, 'identity', 'identity:read');\n },\n\n get runtime() {\n return runtime;\n },\n };\n}\n","/**\n * hooks-adapter.ts — Converts ShellAdapter (browser-facing) to RuntimeAdapter (environment-agnostic).\n *\n * The adapter bridges the gap between the shell's browser-oriented ShellAdapter interfaces\n * (Window references, localStorage, postMessage) and the runtime's abstract RuntimeAdapter\n * (windowId strings, persistence interfaces, sendToNapplet callbacks).\n */\n\nimport type { NostrEvent, NostrFilter } from '@napplet/core';\nimport type {\n RuntimeAdapter,\n RelayPoolAdapter,\n CacheAdapter,\n AuthAdapter,\n Signer,\n ConfigAdapter,\n HotkeyAdapter,\n AclPersistence,\n ManifestPersistence,\n StatePersistence,\n CryptoAdapter,\n WindowManagerAdapter,\n RelayConfigAdapter,\n DmAdapter,\n SendToNapplet,\n RelaySubscriptionHandle,\n ShellSecretPersistence,\n GuidPersistence,\n} from '@kehto/runtime';\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);\n }\n return bytes;\n}\nimport type { ShellAdapter } from './types.js';\nimport type { originRegistry as OriginRegistryType } from './origin-registry.js';\nimport type { manifestCache as ManifestCacheType } from './manifest-cache.js';\nimport type { aclStore as AclStoreType } from './acl-store.js';\nimport type { audioManager as AudioManagerType } from './audio-manager.js';\nimport type { sessionRegistry as SessionRegistryType } from './session-registry.js';\n\n/**\n * Browser-specific singletons that the adapter bridges to the runtime.\n * These use browser APIs (Window, localStorage, postMessage, CustomEvent)\n * that the runtime cannot access directly.\n */\nexport interface BrowserDeps {\n originRegistry: typeof OriginRegistryType;\n manifestCache: typeof ManifestCacheType;\n aclStore: typeof AclStoreType;\n audioManager: typeof AudioManagerType;\n nappKeyRegistry: typeof SessionRegistryType;\n}\n\nfunction createSendToNapplet(originRegistry: BrowserDeps['originRegistry']): SendToNapplet {\n return (windowId, msg) => {\n const win = originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(msg, '*');\n };\n}\n\nfunction createRelayPoolAdapter(\n shellHooks: ShellAdapter,\n originRegistry: BrowserDeps['originRegistry'],\n): RelayPoolAdapter {\n return {\n subscribe(\n filters: NostrFilter[],\n callback: (item: NostrEvent | 'EOSE') => void,\n relayUrls?: string[],\n ): RelaySubscriptionHandle {\n const pool = shellHooks.relayPool.getRelayPool();\n if (!pool) return { unsubscribe() { /* no-op */ } };\n\n const urls = relayUrls ?? shellHooks.relayPool.selectRelayTier(filters);\n const sub = pool.subscription(urls, filters).subscribe((item) => {\n if (item === 'EOSE') callback('EOSE');\n else callback(item as NostrEvent);\n });\n return { unsubscribe: () => sub.unsubscribe() };\n },\n\n publish(event: NostrEvent): void | Promise<void> {\n const pool = shellHooks.relayPool.getRelayPool();\n if (!pool) return;\n const relayUrls = shellHooks.relayPool.selectRelayTier([]);\n return pool.publish(relayUrls, event);\n },\n\n selectRelayTier(filters: NostrFilter[]): string[] {\n return shellHooks.relayPool.selectRelayTier(filters);\n },\n\n trackSubscription(subKey: string, cleanup: () => void): void {\n shellHooks.relayPool.trackSubscription(subKey, cleanup);\n },\n\n untrackSubscription(subKey: string): void {\n shellHooks.relayPool.untrackSubscription(subKey);\n },\n\n openScopedRelay(\n windowId: string,\n relayUrl: string,\n subId: string,\n filters: NostrFilter[],\n _sendFn: SendToNapplet,\n ): void {\n const win = originRegistry.getIframeWindow(windowId);\n if (win) shellHooks.relayPool.openScopedRelay(windowId, relayUrl, subId, filters, win);\n },\n\n closeScopedRelay(windowId: string): void {\n shellHooks.relayPool.closeScopedRelay(windowId);\n },\n\n publishToScopedRelay(windowId: string, event: NostrEvent): boolean | Promise<boolean> {\n return shellHooks.relayPool.publishToScopedRelay(windowId, event);\n },\n\n isAvailable(): boolean {\n return shellHooks.relayPool.getRelayPool() !== null;\n },\n };\n}\n\nfunction createCacheAdapter(shellHooks: ShellAdapter): CacheAdapter {\n return {\n async query(filters: NostrFilter[]): Promise<NostrEvent[]> {\n const workerRelay = shellHooks.workerRelay.getWorkerRelay();\n if (!workerRelay) return [];\n const subId = crypto.randomUUID();\n return workerRelay.query(['REQ', subId, ...filters]);\n },\n\n store(event: NostrEvent): void {\n const workerRelay = shellHooks.workerRelay.getWorkerRelay();\n if (!workerRelay) return;\n try { workerRelay.event(event)?.catch?.(() => { /* best-effort */ }); } catch { /* best-effort */ }\n },\n\n isAvailable(): boolean {\n return shellHooks.workerRelay.getWorkerRelay() !== null;\n },\n };\n}\n\nfunction createAuthAdapter(shellHooks: ShellAdapter): AuthAdapter {\n return {\n getUserPubkey(): string | null {\n return shellHooks.auth.getUserPubkey();\n },\n getSigner(windowId?: string): Signer | null {\n return shellHooks.auth.getSigner(windowId);\n },\n };\n}\n\nfunction createConfigAdapter(shellHooks: ShellAdapter): ConfigAdapter {\n return {\n getNappUpdateBehavior(): 'auto-grant' | 'banner' | 'silent-reprompt' {\n return shellHooks.config.getNappUpdateBehavior();\n },\n };\n}\n\nfunction createHotkeyAdapter(shellHooks: ShellAdapter): HotkeyAdapter {\n return {\n executeHotkeyFromForward(event): void {\n shellHooks.hotkeys.executeHotkeyFromForward(event);\n },\n };\n}\n\nfunction createCryptoAdapter(shellHooks: ShellAdapter): CryptoAdapter {\n return {\n async verifyEvent(event: NostrEvent): Promise<boolean> {\n return shellHooks.crypto.verifyEvent(event);\n },\n randomUUID(): string {\n return crypto.randomUUID();\n },\n randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n },\n };\n}\n\nfunction createAclPersistence(): AclPersistence {\n return {\n persist(data: string): void {\n try { localStorage.setItem('napplet:acl', data); } catch { /* best-effort */ }\n },\n load(): string | null {\n try { return localStorage.getItem('napplet:acl'); } catch { return null; }\n },\n };\n}\n\nfunction createManifestPersistence(): ManifestPersistence {\n return {\n persist(data: string): void {\n try { localStorage.setItem('napplet:manifest-cache', data); } catch { /* best-effort */ }\n },\n load(): string | null {\n try { return localStorage.getItem('napplet:manifest-cache'); } catch { return null; }\n },\n };\n}\n\nfunction createStatePersistence(): StatePersistence {\n return {\n get(scopedKey: string): string | null {\n try { return localStorage.getItem(scopedKey); } catch { return null; }\n },\n set(scopedKey: string, value: string): boolean {\n try { localStorage.setItem(scopedKey, value); return true; } catch { return false; }\n },\n remove(scopedKey: string): void {\n try { localStorage.removeItem(scopedKey); } catch { /* best-effort */ }\n },\n clear(prefix: string): void {\n try {\n const keysToRemove: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(prefix)) keysToRemove.push(key);\n }\n for (const key of keysToRemove) localStorage.removeItem(key);\n } catch { /* best-effort */ }\n },\n keys(prefix: string): string[] {\n try {\n const result: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key?.startsWith(prefix)) result.push(key);\n }\n return result;\n } catch { return []; }\n },\n calculateBytes(prefix: string, excludeKey?: string): number {\n try {\n let total = 0;\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (!key?.startsWith(prefix)) continue;\n if (excludeKey && key === excludeKey) continue;\n const value = localStorage.getItem(key) ?? '';\n total += new TextEncoder().encode(key + value).length;\n }\n return total;\n } catch { return 0; }\n },\n };\n}\n\nfunction createWindowManagerAdapter(shellHooks: ShellAdapter): WindowManagerAdapter {\n return {\n createWindow(options): string | null {\n return shellHooks.windowManager.createWindow(options);\n },\n };\n}\n\nfunction createRelayConfigAdapter(shellHooks: ShellAdapter): RelayConfigAdapter {\n return {\n addRelay(tier: string, url: string): void {\n shellHooks.relayConfig.addRelay(tier, url);\n },\n removeRelay(tier: string, url: string): void {\n shellHooks.relayConfig.removeRelay(tier, url);\n },\n getRelayConfig(): { discovery: string[]; super: string[]; outbox: string[] } {\n return shellHooks.relayConfig.getRelayConfig();\n },\n getNip66Suggestions(): unknown {\n return shellHooks.relayConfig.getNip66Suggestions();\n },\n };\n}\n\nfunction createShellSecretPersistence(): ShellSecretPersistence {\n return {\n get(): Uint8Array | null {\n try {\n const hex = localStorage.getItem('napplet-shell-secret');\n if (!hex) return null;\n return hexToBytes(hex);\n } catch { return null; }\n },\n set(secret: Uint8Array): void {\n try {\n localStorage.setItem('napplet-shell-secret', bytesToHex(secret));\n } catch { /* localStorage unavailable */ }\n },\n };\n}\n\nfunction createGuidPersistence(): GuidPersistence {\n return {\n get(windowId: string): string | null {\n try {\n return localStorage.getItem(`napplet-guid:${windowId}`);\n } catch { return null; }\n },\n set(windowId: string, guid: string): void {\n try {\n localStorage.setItem(`napplet-guid:${windowId}`, guid);\n } catch { /* localStorage unavailable */ }\n },\n remove(windowId: string): void {\n try {\n localStorage.removeItem(`napplet-guid:${windowId}`);\n } catch { /* localStorage unavailable */ }\n },\n };\n}\n\nfunction createDmAdapter(shellHooks: ShellAdapter): DmAdapter | undefined {\n return shellHooks.dm\n ? {\n sendDm(recipientPubkey: string, message: string) {\n return shellHooks.dm!.sendDm(recipientPubkey, message);\n },\n }\n : undefined;\n}\n\n/**\n * Convert ShellAdapter (browser-facing) into RuntimeAdapter (environment-agnostic).\n *\n * The adapter is the single translation layer between browser APIs and the\n * runtime's abstract interfaces. It:\n * - Converts Window references to windowId strings via originRegistry\n * - Wraps localStorage-backed singletons into persistence interfaces\n * - Translates relay pool API shapes (Observable → callback)\n *\n * @param shellHooks - The browser-oriented ShellAdapter provided by the host app\n * @param deps - Browser-specific singletons (originRegistry, aclStore, etc.)\n * @returns RuntimeAdapter suitable for createRuntime()\n *\n * @example\n * ```ts\n * const runtimeHooks = adaptHooks(shellHooks, {\n * originRegistry, manifestCache, aclStore, audioManager, nappKeyRegistry,\n * });\n * const runtime = createRuntime(runtimeHooks);\n * ```\n */\nexport function adaptHooks(shellHooks: ShellAdapter, deps: BrowserDeps): RuntimeAdapter {\n const { originRegistry } = deps;\n\n return {\n sendToNapplet: createSendToNapplet(originRegistry),\n relayPool: createRelayPoolAdapter(shellHooks, originRegistry),\n cache: createCacheAdapter(shellHooks),\n auth: createAuthAdapter(shellHooks),\n config: createConfigAdapter(shellHooks),\n hotkeys: createHotkeyAdapter(shellHooks),\n crypto: createCryptoAdapter(shellHooks),\n aclPersistence: createAclPersistence(),\n manifestPersistence: createManifestPersistence(),\n statePersistence: createStatePersistence(),\n windowManager: createWindowManagerAdapter(shellHooks),\n relayConfig: createRelayConfigAdapter(shellHooks),\n dm: createDmAdapter(shellHooks),\n shellSecretPersistence: createShellSecretPersistence(),\n guidPersistence: createGuidPersistence(),\n onAclCheck: shellHooks.onAclCheck,\n onHashMismatch: shellHooks.onHashMismatch,\n services: shellHooks.services,\n getConfigOverrides: shellHooks.getConfigOverrides,\n };\n}\n","\nimport type { ShellEnvironment } from './types.js';\n\ninterface OriginEntry {\n windowId: string;\n dTag?: string;\n aggregateHash?: string;\n environment?: ShellEnvironment;\n registrationId: number;\n}\n\n/** NIP-5D identity metadata associated with a registered iframe window. */\nexport interface OriginIdentity {\n readonly dTag: string;\n readonly aggregateHash: string;\n}\n\nconst registry = new Map<Window, OriginEntry>();\nlet nextRegistrationId = 0;\n\n/**\n * Bidirectional registry mapping Window references to windowId strings.\n * Optionally stores NIP-5D identity metadata (dTag and aggregateHash) per window.\n *\n * @example\n * ```ts\n * import { originRegistry } from '@kehto/shell';\n *\n * originRegistry.register(iframe.contentWindow, 'napp-1');\n * const id = originRegistry.getWindowId(iframe.contentWindow); // 'napp-1'\n * ```\n */\nexport interface OriginRegistry {\n register(win: Window, windowId: string, identity?: OriginIdentity): void;\n unregister(windowId: string): void;\n getWindowId(win: Window): string | undefined;\n getIframeWindow(windowId: string): Window | null;\n getAllWindowIds(): string[];\n getIdentity(win: Window): OriginIdentity | undefined;\n setEnvironment(win: Window, environment: ShellEnvironment): void;\n getEnvironment(win: Window): ShellEnvironment | undefined;\n getRegistrationId(win: Window): number | undefined;\n clear(): void;\n}\n\n/** Shell-wide iframe window registry singleton. */\nexport const originRegistry: OriginRegistry = {\n /**\n * Register a window reference with a windowId and optional identity metadata.\n *\n * @param win - The iframe's contentWindow reference\n * @param windowId - The unique identifier for this napplet window\n * @param identity - Optional NIP-5D identity metadata (dTag and aggregateHash)\n */\n register(win: Window, windowId: string, identity?: OriginIdentity): void {\n for (const [registeredWin, entry] of registry.entries()) {\n if (registeredWin === win || entry.windowId === windowId) {\n registry.delete(registeredWin);\n }\n }\n\n registry.set(win, {\n windowId,\n dTag: identity?.dTag,\n aggregateHash: identity?.aggregateHash,\n registrationId: ++nextRegistrationId,\n });\n },\n\n /**\n * Unregister a window by its windowId, removing the mapping.\n *\n * @param windowId - The window identifier to remove\n */\n unregister(windowId: string): void {\n for (const [win, entry] of registry.entries()) {\n if (entry.windowId === windowId) {\n registry.delete(win);\n }\n }\n },\n\n /**\n * Look up the windowId for a given Window reference.\n *\n * @param win - The Window reference (typically from event.source)\n * @returns The windowId string, or undefined if not registered\n */\n getWindowId(win: Window): string | undefined {\n return registry.get(win)?.windowId;\n },\n\n /**\n * Look up the Window reference for a given windowId.\n *\n * @param windowId - The window identifier to look up\n * @returns The Window reference, or null if not found\n */\n getIframeWindow(windowId: string): Window | null {\n for (const [win, entry] of registry.entries()) {\n if (entry.windowId === windowId) return win;\n }\n return null;\n },\n\n /**\n * Get all registered windowId strings.\n *\n * @returns Array of all registered window identifiers\n */\n getAllWindowIds(): string[] {\n return Array.from(registry.values()).map(entry => entry.windowId);\n },\n\n /**\n * Get identity metadata for a registered Window.\n *\n * @param win - The Window reference to look up\n * @returns Identity metadata, or undefined if not registered or no identity set\n */\n getIdentity(win: Window): OriginIdentity | undefined {\n const entry = registry.get(win);\n if (typeof entry?.dTag !== 'string' || !entry?.aggregateHash) return undefined;\n return { dTag: entry.dTag, aggregateHash: entry.aggregateHash };\n },\n\n /** Store the immutable environment captured for this exact frame registration. */\n setEnvironment(win: Window, environment: ShellEnvironment): void {\n const entry = registry.get(win);\n if (!entry) return;\n entry.environment = Object.freeze({\n capabilities: Object.freeze({ domains: Object.freeze([...environment.capabilities.domains]) }),\n services: Object.freeze([...environment.services]),\n });\n },\n\n /** Return the immutable environment captured before this frame executes. */\n getEnvironment(win: Window): ShellEnvironment | undefined {\n return registry.get(win)?.environment;\n },\n\n /**\n * Look up the monotonically increasing registration id for a Window.\n *\n * @param win - The Window reference to look up\n * @returns The registration id, or undefined if the Window is not registered\n */\n getRegistrationId(win: Window): number | undefined {\n return registry.get(win)?.registrationId;\n },\n\n /** Clear all registrations. */\n clear(): void {\n registry.clear();\n },\n};\n","/**\n * SessionRegistry — windowId to verified napplet pubkey bidirectional mapping.\n *\n * After a successful AUTH handshake, the ShellBridge registers the napplet's\n * verified pubkey here. Both mappings are kept in sync.\n */\n\nimport type { PendingUpdate, SessionEntry } from '@kehto/runtime';\n\n/**\n * A pending napplet update — raised when a napplet reconnects with a different aggregateHash.\n * @example\n * ```ts\n * const update: PendingUpdate = {\n * windowId: 'win-1', pubkey: 'abc...', dTag: '3chat',\n * oldHash: 'aaa', newHash: 'bbb',\n * resolve: (action) => { if (action === 'accept') { // apply } },\n * };\n * ```\n */\nexport type { PendingUpdate } from '@kehto/runtime';\n\nconst byWindowId = new Map<string, string>();\nconst byPubkey = new Map<string, SessionEntry>();\nconst pendingUpdates = new Map<string, PendingUpdate>();\n\nlet _pendingVersion = 0;\n\n/**\n * Bidirectional registry mapping windowIds to verified napplet pubkeys.\n * Maintained by ShellBridge after successful AUTH handshakes.\n *\n * @example\n * ```ts\n * import { sessionRegistry } from '@kehto/shell';\n *\n * const pubkey = sessionRegistry.getPubkey('win-1');\n * const entry = pubkey ? sessionRegistry.getEntry(pubkey) : undefined;\n * ```\n */\nexport interface SessionRegistry {\n register(windowId: string, entry: SessionEntry): void;\n unregister(windowId: string): void;\n getPubkey(windowId: string): string | undefined;\n getEntry(pubkey: string): SessionEntry | undefined;\n getWindowId(pubkey: string): string | undefined;\n isRegistered(windowId: string): boolean;\n getAllEntries(): SessionEntry[];\n setPendingUpdate(windowId: string, update: PendingUpdate): void;\n getPendingUpdate(windowId: string): PendingUpdate | undefined;\n clearPendingUpdate(windowId: string): void;\n clear(): void;\n}\n\n/** Shell-wide verified napplet session registry singleton. */\nexport const sessionRegistry: SessionRegistry = {\n /**\n * Register a napplet entry, mapping windowId to pubkey and vice versa.\n *\n * @param windowId - The window identifier\n * @param entry - The verified napplet session entry from AUTH handshake\n */\n register(windowId: string, entry: SessionEntry): void {\n byWindowId.set(windowId, entry.pubkey);\n byPubkey.set(entry.pubkey, entry);\n },\n\n /**\n * Unregister a napplet by windowId, removing both mappings.\n *\n * @param windowId - The window identifier to remove\n */\n unregister(windowId: string): void {\n const pubkey = byWindowId.get(windowId);\n if (pubkey) {\n byPubkey.delete(pubkey);\n byWindowId.delete(windowId);\n }\n pendingUpdates.delete(windowId);\n },\n\n /**\n * Get the pubkey associated with a windowId.\n *\n * @param windowId - The window identifier\n * @returns The napplet's pubkey, or undefined if not registered\n */\n getPubkey(windowId: string): string | undefined {\n return byWindowId.get(windowId);\n },\n\n /**\n * Get the full entry for a napplet pubkey.\n *\n * @param pubkey - The napplet's pubkey\n * @returns The full SessionEntry, or undefined if not found\n */\n getEntry(pubkey: string): SessionEntry | undefined {\n return byPubkey.get(pubkey);\n },\n\n /**\n * Get the windowId for a napplet pubkey.\n *\n * @param pubkey - The napplet's pubkey\n * @returns The windowId, or undefined if not found\n */\n getWindowId(pubkey: string): string | undefined {\n return byPubkey.get(pubkey)?.windowId;\n },\n\n /**\n * Check if a windowId has a registered napplet.\n *\n * @param windowId - The window identifier\n * @returns True if the windowId has a registered napplet\n */\n isRegistered(windowId: string): boolean {\n return byWindowId.has(windowId);\n },\n\n /**\n * Get all registered napplet entries.\n *\n * @returns Array of all SessionEntry objects\n */\n getAllEntries(): SessionEntry[] {\n return Array.from(byPubkey.values());\n },\n\n /**\n * Set a pending update for a window (napplet reconnected with different hash).\n *\n * @param windowId - The window identifier\n * @param update - The pending update details with resolve callback\n */\n setPendingUpdate(windowId: string, update: PendingUpdate): void {\n pendingUpdates.set(windowId, update);\n _pendingVersion++;\n if (typeof window !== 'undefined') {\n window.dispatchEvent(new CustomEvent('napplet:pending-update', { detail: { windowId } }));\n }\n },\n\n /**\n * Get a pending update for a window.\n *\n * @param windowId - The window identifier\n * @returns The pending update, or undefined if none\n */\n getPendingUpdate(windowId: string): PendingUpdate | undefined {\n return pendingUpdates.get(windowId);\n },\n\n /**\n * Clear a pending update for a window.\n *\n * @param windowId - The window identifier\n */\n clearPendingUpdate(windowId: string): void {\n pendingUpdates.delete(windowId);\n _pendingVersion++;\n if (typeof window !== 'undefined') {\n window.dispatchEvent(new CustomEvent('napplet:pending-update', { detail: { windowId } }));\n }\n },\n\n /** Clear all registrations and pending updates. */\n clear(): void {\n byWindowId.clear();\n byPubkey.clear();\n pendingUpdates.clear();\n },\n};\n\n/** @deprecated Use sessionRegistry. Will be removed in v0.9.0. */\nexport const nappKeyRegistry: SessionRegistry = sessionRegistry;\n","\nimport { ALL_CAPABILITIES, type Capability } from '@kehto/runtime';\nimport { migrateAclState, type AclState } from '@kehto/acl';\nimport type { AclEntry } from './types.js';\n\nconst STORAGE_KEY = 'napplet:acl';\n\n/** Default state quota in bytes (512 KB) per napplet identity. */\nexport const DEFAULT_STATE_QUOTA = 512 * 1024;\n\ninterface InternalAclEntry {\n key: string;\n pubkey: string;\n dTag: string;\n aggregateHash: string;\n capabilities: Set<Capability>;\n blocked: boolean;\n stateQuota: number;\n}\n\nfunction aclKey(_pubkey: string, dTag: string, aggregateHash: string): string {\n return `${dTag}:${aggregateHash}`;\n}\n\nconst store = new Map<string, InternalAclEntry>();\n\n// Capability name to bit position mapping for bitfield conversion.\n// Plan 12-10: signer bit slots (32/64/128) reclaimed by the v1.2\n// identity:read / keys:bind / keys:forward caps. v1.1 persisted ACL\n// state with those bits is reinterpreted under the v1.2 surface —\n// acceptable because the v1.1 signer actions have no napplet-visible\n// surface in NIP-5D.\nconst CAP_BITS: Record<string, number> = {\n 'relay:read': 1, 'relay:write': 2, 'cache:read': 4, 'cache:write': 8,\n 'hotkey:forward': 16,\n 'identity:read': 32, 'keys:bind': 64, 'keys:forward': 128,\n 'state:read': 256, 'state:write': 512,\n 'media:control': 1024, 'notify:send': 2048, 'notify:channel': 4096,\n 'theme:read': 8192,\n // 65536 RETIRED — was identity:decrypt (removed as a spec violation); left as\n // a permanent gap, do NOT reuse this bit.\n};\n\nfunction capArrayToBitfield(caps: Capability[]): number {\n let bits = 0;\n for (const cap of caps) bits |= (CAP_BITS[cap] ?? 0);\n return bits;\n}\n\nfunction bitfieldToCapArray(bits: number): Capability[] {\n return (Object.entries(CAP_BITS)\n .filter(([, bit]) => (bits & bit) !== 0)\n .map(([name]) => name)) as Capability[];\n}\n\nfunction getOrCreate(pubkey: string, dTag: string, aggregateHash: string): InternalAclEntry {\n const key = aclKey(pubkey, dTag, aggregateHash);\n let entry = store.get(key);\n if (!entry) {\n entry = {\n key,\n pubkey,\n dTag,\n aggregateHash,\n capabilities: new Set(ALL_CAPABILITIES),\n blocked: false,\n stateQuota: DEFAULT_STATE_QUOTA,\n };\n store.set(key, entry);\n }\n return entry;\n}\n\n/**\n * ACL store — manages capability grants, revocations, and blocks for napp identities.\n * Persists to localStorage and uses a permissive default policy (all capabilities granted).\n *\n * @example\n * ```ts\n * import { aclStore } from '@kehto/shell';\n *\n * aclStore.grant(pubkey, dTag, hash, 'relay:read');\n * const allowed = aclStore.check(pubkey, dTag, hash, 'relay:read'); // true\n * ```\n */\nexport interface AclStore {\n check(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): boolean;\n grant(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void;\n revoke(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void;\n block(pubkey: string, dTag: string, aggregateHash: string): void;\n unblock(pubkey: string, dTag: string, aggregateHash: string): void;\n isBlocked(pubkey: string, dTag: string, aggregateHash: string): boolean;\n getEntry(pubkey: string, dTag: string, aggregateHash: string): AclEntry | undefined;\n getAllEntries(): AclEntry[];\n persist(): void;\n load(): void;\n getStateQuota(pubkey: string, dTag: string, aggregateHash: string): number;\n clear(): void;\n}\n\n/** Shell ACL store singleton. */\nexport const aclStore: AclStore = {\n /**\n * Check if a napp identity has a specific capability.\n * Returns true for unknown identities (permissive default).\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @param capability - The capability to check\n * @returns True if the capability is granted and the napp is not blocked\n */\n check(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): boolean {\n const key = aclKey(pubkey, dTag, aggregateHash);\n const entry = store.get(key);\n if (!entry) return true;\n if (entry.blocked) return false;\n return entry.capabilities.has(capability);\n },\n\n /**\n * Grant a capability to a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @param capability - The capability to grant\n */\n grant(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void {\n getOrCreate(pubkey, dTag, aggregateHash).capabilities.add(capability);\n },\n\n /**\n * Revoke a capability from a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @param capability - The capability to revoke\n */\n revoke(pubkey: string, dTag: string, aggregateHash: string, capability: Capability): void {\n getOrCreate(pubkey, dTag, aggregateHash).capabilities.delete(capability);\n },\n\n /**\n * Block a napp identity entirely (all capabilities denied).\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n */\n block(pubkey: string, dTag: string, aggregateHash: string): void {\n getOrCreate(pubkey, dTag, aggregateHash).blocked = true;\n },\n\n /**\n * Unblock a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n */\n unblock(pubkey: string, dTag: string, aggregateHash: string): void {\n getOrCreate(pubkey, dTag, aggregateHash).blocked = false;\n },\n\n /**\n * Check if a napp identity is blocked.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @returns True if the identity is blocked\n */\n isBlocked(pubkey: string, dTag: string, aggregateHash: string): boolean {\n const key = aclKey(pubkey, dTag, aggregateHash);\n return store.get(key)?.blocked ?? false;\n },\n\n /**\n * Get the external ACL entry for a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @returns The ACL entry, or undefined if no explicit entry exists\n */\n getEntry(pubkey: string, dTag: string, aggregateHash: string): AclEntry | undefined {\n const key = aclKey(pubkey, dTag, aggregateHash);\n const internal = store.get(key);\n if (!internal) return undefined;\n return {\n pubkey: internal.pubkey,\n capabilities: Array.from(internal.capabilities),\n blocked: internal.blocked,\n stateQuota: internal.stateQuota,\n };\n },\n\n /**\n * Get all ACL entries.\n *\n * @returns Array of all ACL entries\n */\n getAllEntries(): AclEntry[] {\n return Array.from(store.values()).map(e => ({\n pubkey: e.pubkey,\n capabilities: Array.from(e.capabilities),\n blocked: e.blocked,\n stateQuota: e.stateQuota,\n }));\n },\n\n /** Persist the ACL store to localStorage. */\n persist(): void {\n try {\n const entries = Array.from(store.entries()).map(([key, val]) => [\n key,\n {\n pubkey: val.pubkey,\n dTag: val.dTag,\n aggregateHash: val.aggregateHash,\n capabilities: Array.from(val.capabilities),\n blocked: val.blocked,\n stateQuota: val.stateQuota,\n },\n ]);\n localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));\n } catch {\n // localStorage unavailable\n }\n },\n\n /** Load the ACL store from localStorage. Migrates old 3-segment keys to 2-segment format. */\n load(): void {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n let entries = JSON.parse(raw) as Array<\n [string, {\n pubkey: string;\n dTag?: string;\n aggregateHash?: string;\n capabilities: Capability[];\n blocked: boolean;\n stateQuota?: number;\n }]\n >;\n\n const hasOldKeys = entries.some(([key]) => key.split(':').length === 3);\n if (hasOldKeys) {\n const tempState: AclState = {\n defaultPolicy: 'permissive',\n entries: Object.fromEntries(\n entries.map(([key, val]) => [key, {\n caps: capArrayToBitfield(val.capabilities),\n blocked: val.blocked,\n quota: val.stateQuota ?? DEFAULT_STATE_QUOTA,\n }])\n ),\n };\n const migrated = migrateAclState(tempState);\n if (migrated !== tempState) {\n // Rebuild entries from migrated state\n entries = Object.entries(migrated.entries).map(([key, entry]) => {\n const parts = key.split(':');\n return [key, {\n pubkey: '',\n dTag: parts[0] ?? '',\n aggregateHash: parts[1] ?? '',\n capabilities: bitfieldToCapArray(entry.caps),\n blocked: entry.blocked,\n stateQuota: entry.quota,\n }] as [string, typeof entries[0][1]];\n });\n // Re-persist migrated data immediately\n localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));\n }\n }\n\n store.clear();\n for (const [key, val] of entries) {\n if (val.dTag === undefined || val.aggregateHash === undefined) continue;\n store.set(key, {\n key,\n pubkey: val.pubkey,\n dTag: val.dTag,\n aggregateHash: val.aggregateHash,\n capabilities: new Set(val.capabilities),\n blocked: val.blocked,\n stateQuota: val.stateQuota ?? DEFAULT_STATE_QUOTA,\n });\n }\n } catch {\n /* Corrupted ACL data in localStorage — clear and use defaults */\n store.clear();\n }\n },\n\n /**\n * Get the state quota for a napp identity.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param aggregateHash - The napp's build hash\n * @returns The quota in bytes (defaults to DEFAULT_STATE_QUOTA)\n */\n getStateQuota(pubkey: string, dTag: string, aggregateHash: string): number {\n const key = aclKey(pubkey, dTag, aggregateHash);\n return store.get(key)?.stateQuota ?? DEFAULT_STATE_QUOTA;\n },\n\n /** Clear all ACL entries and remove from localStorage. */\n clear(): void {\n store.clear();\n try {\n localStorage.removeItem(STORAGE_KEY);\n } catch {\n /* localStorage unavailable — ACL clear is best-effort */\n }\n },\n};\n","/**\n * Manifest cache — persists verified NIP-5A aggregate hashes per napplet identity.\n */\n\n/**\n * A cached manifest entry for a verified napplet build.\n * @example\n * ```ts\n * const entry: ManifestCacheEntry = {\n * pubkey: 'abc123...', dTag: '3chat',\n * aggregateHash: 'deadbeef', verifiedAt: Date.now(),\n * };\n * ```\n */\nexport interface ManifestCacheEntry {\n pubkey: string;\n dTag: string;\n aggregateHash: string;\n verifiedAt: number;\n}\n\nconst STORAGE_KEY = 'napplet:manifest-cache';\nconst cache = new Map<string, ManifestCacheEntry>();\n\nfunction cacheKey(pubkey: string, dTag: string): string {\n return `${pubkey}:${dTag}`;\n}\n\n/**\n * Cache for verified napplet manifest entries. Persists to localStorage.\n * Used to detect napplet updates (aggregateHash changes) across sessions.\n *\n * @example\n * ```ts\n * import { manifestCache } from '@kehto/shell';\n *\n * manifestCache.set({ pubkey: 'abc...', dTag: 'chat', aggregateHash: 'dead', verifiedAt: Date.now() });\n * const entry = manifestCache.get('abc...', 'chat');\n * ```\n */\nexport interface ManifestCache {\n get(pubkey: string, dTag: string): ManifestCacheEntry | undefined;\n set(entry: ManifestCacheEntry): void;\n has(pubkey: string, dTag: string, hash: string): boolean;\n remove(pubkey: string, dTag: string): void;\n load(): void;\n persist(): void;\n clear(): void;\n}\n\n/** Shell-wide manifest verification cache singleton. */\nexport const manifestCache: ManifestCache = {\n /**\n * Get a cached manifest entry by pubkey and dTag.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @returns The cached entry, or undefined if not found\n */\n get(pubkey: string, dTag: string): ManifestCacheEntry | undefined {\n return cache.get(cacheKey(pubkey, dTag));\n },\n\n /**\n * Set (upsert) a manifest cache entry and persist to localStorage.\n *\n * @param entry - The manifest entry to cache\n */\n set(entry: ManifestCacheEntry): void {\n cache.set(cacheKey(entry.pubkey, entry.dTag), entry);\n manifestCache.persist();\n },\n\n /**\n * Check if a specific hash is cached for a pubkey/dTag combination.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n * @param hash - The aggregateHash to check\n * @returns True if the exact hash matches the cached entry\n */\n has(pubkey: string, dTag: string, hash: string): boolean {\n const entry = cache.get(cacheKey(pubkey, dTag));\n return !!entry && entry.aggregateHash === hash;\n },\n\n /**\n * Remove a cached entry for a pubkey/dTag and persist.\n *\n * @param pubkey - The napp's pubkey\n * @param dTag - The napp's dTag\n */\n remove(pubkey: string, dTag: string): void {\n cache.delete(cacheKey(pubkey, dTag));\n manifestCache.persist();\n },\n\n /** Load the cache from localStorage. */\n load(): void {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n const entries = JSON.parse(raw) as Array<[string, ManifestCacheEntry]>;\n cache.clear();\n for (const [key, val] of entries) cache.set(key, val);\n } catch { /* Corrupted cache data — clear and start fresh */ cache.clear(); }\n },\n\n /** Persist the cache to localStorage. */\n persist(): void {\n try {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(Array.from(cache.entries())));\n } catch { /* localStorage unavailable in sandboxed contexts — persist is best-effort */ }\n },\n\n /** Clear all cached entries and remove from localStorage. */\n clear(): void {\n cache.clear();\n try { localStorage.removeItem(STORAGE_KEY); } catch { /* localStorage unavailable — cleanup is best-effort */ }\n },\n};\n","/**\n * audio-manager.ts — Shell-side registry of active audio sources.\n *\n * Tracks which windows are producing audio. UI components read the registry\n * reactively via the version counter and CustomEvent pattern.\n */\n\nimport { originRegistry } from './origin-registry.js';\n\n/**\n * An active audio source registered by a napplet.\n * @example\n * ```ts\n * const source: AudioSource = {\n * windowId: 'win-1', nappletClass: 'music-player',\n * title: 'Now Playing', muted: false,\n * };\n * ```\n */\nexport interface AudioSource {\n windowId: string;\n nappletClass: string;\n title: string;\n muted: boolean;\n}\n\nconst sources: Map<string, AudioSource> = new Map<string, AudioSource>();\nlet version = 0;\n\nfunction bump(): void {\n version++;\n if (typeof window !== 'undefined') {\n window.dispatchEvent(new CustomEvent('napplet:audio-changed'));\n }\n}\n\n/**\n * Registry of active audio sources across all napplet windows.\n * Emits 'napplet:audio-changed' CustomEvents when the registry changes.\n *\n * @example\n * ```ts\n * import { audioManager } from '@kehto/shell';\n *\n * audioManager.register('win-1', 'music', 'My Song');\n * audioManager.mute('win-1', true);\n * ```\n */\nexport interface AudioManager {\n register(windowId: string, nappletClass: string, title: string): void;\n unregister(windowId: string): void;\n updateState(windowId: string, update: { title?: string }): void;\n mute(windowId: string, muted: boolean): void;\n has(windowId: string): boolean;\n get(windowId: string): AudioSource | undefined;\n getSources(): Map<string, AudioSource>;\n readonly version: number;\n readonly count: number;\n clear(): void;\n}\n\n/** Shell-wide audio source registry singleton. */\nexport const audioManager: AudioManager = {\n /**\n * Register a new audio source for a window.\n *\n * @param windowId - The window identifier\n * @param nappletClass - The napplet class/type (e.g., 'music-player')\n * @param title - Human-readable title for the audio source\n */\n register(windowId: string, nappletClass: string, title: string): void {\n sources.set(windowId, { windowId, nappletClass, title, muted: false });\n bump();\n },\n\n /**\n * Unregister an audio source for a window.\n *\n * @param windowId - The window identifier to remove\n */\n unregister(windowId: string): void {\n if (sources.delete(windowId)) bump();\n },\n\n /**\n * Update the state of an audio source (e.g., change title).\n *\n * @param windowId - The window identifier\n * @param update - Partial update with optional title\n */\n updateState(windowId: string, update: { title?: string }): void {\n const src = sources.get(windowId);\n if (!src) return;\n if (update.title !== undefined) src.title = update.title;\n bump();\n },\n\n /**\n * Mute or unmute an audio source and notify the napplet via postMessage.\n *\n * @param windowId - The window identifier\n * @param muted - True to mute, false to unmute\n * @example\n * ```ts\n * audioManager.mute('win-1', true); // mute\n * audioManager.mute('win-1', false); // unmute\n * ```\n */\n mute(windowId: string, muted: boolean): void {\n const src = sources.get(windowId);\n if (src) { src.muted = muted; bump(); }\n const iframeWindow = originRegistry.getIframeWindow(windowId);\n if (iframeWindow) {\n const muteEvent = {\n kind: 29000, // INC_PEER — inlined numeric after Phase 24 DRIFT-01 shim removal\n created_at: Math.floor(Date.now() / 1000),\n tags: [['t', 'napplet:audio-muted']],\n content: JSON.stringify({ muted }),\n pubkey: '__shell__',\n id: `audio-mute-${windowId}-${Date.now()}`,\n sig: '',\n };\n iframeWindow.postMessage(['EVENT', '__shell__', muteEvent], '*');\n }\n },\n\n /**\n * Check if a window has a registered audio source.\n *\n * @param windowId - The window identifier\n * @returns True if the window has an active audio source\n */\n has(windowId: string): boolean { return sources.has(windowId); },\n\n /**\n * Get the audio source for a window.\n *\n * @param windowId - The window identifier\n * @returns The AudioSource, or undefined if not found\n */\n get(windowId: string): AudioSource | undefined { return sources.get(windowId); },\n\n /**\n * Get a snapshot of all audio sources.\n *\n * @returns A new Map of all active audio sources\n */\n getSources(): Map<string, AudioSource> { return new Map(sources); },\n\n /** Current version counter (incremented on every change). */\n get version(): number { return version; },\n\n /** Number of active audio sources. */\n get count(): number { return sources.size; },\n\n /** Clear all audio sources and reset version counter. */\n clear(): void { sources.clear(); version = 0; },\n};\n","import type { OriginIdentity } from './origin-registry.js';\nimport type { ShellAdapter, ShellCapabilities, ShellEnvironment } from './types.js';\n\nconst RUNTIME_NATIVE_DOMAINS = [\n 'relay', 'identity', 'storage', 'inc', 'theme', 'keys', 'media', 'notify',\n] as const;\n\nconst SERVICE_ONLY_DOMAINS = [\n 'outbox', 'config', 'resource', 'cvm', 'upload', 'intent', 'link', 'common',\n 'lists', 'serial', 'ble', 'webrtc', 'dm', 'count',\n 'fs',\n] as const;\n\n/**\n * Build the shell's immutable live capability snapshot from adapter wiring.\n *\n * @param hooks - The ShellAdapter provided by the host app.\n * @returns Domain-only ShellCapabilities for the current live wiring.\n * @example\n * ```ts\n * const caps = buildShellCapabilities(hooks);\n * // caps.domains => ['relay', 'identity', 'storage', 'inc', 'theme', 'keys', 'media', 'notify']\n * ```\n */\nexport function buildShellCapabilities(hooks: ShellAdapter): ShellCapabilities {\n const disabled = new Set(hooks.capabilities?.disabledDomains ?? []);\n const domains: string[] = RUNTIME_NATIVE_DOMAINS.filter((domain) => !disabled.has(domain));\n\n for (const domain of SERVICE_ONLY_DOMAINS) {\n if (!disabled.has(domain) && isServiceDomainLive(hooks, domain)) domains.push(domain);\n }\n\n return Object.freeze({ domains: freezeList(domains) });\n}\n\n/**\n * Resolve a trusted creation identity's immutable NAP-SHELL environment.\n *\n * This host-adapter API is intentionally not part of `window.napplet`: it\n * bounds host policy to current runtime wiring before `shell.init` crosses into\n * an untrusted iframe.\n *\n * @param hooks - Shell host wiring and optional per-identity grant policy.\n * @param identity - The source's creation-time identity.\n * @returns A fresh immutable environment whose entries are exact live subsets.\n */\nexport function resolveShellEnvironment(\n hooks: ShellAdapter,\n identity: OriginIdentity,\n): ShellEnvironment {\n const capabilities = buildShellCapabilities(hooks);\n const disabled = new Set(hooks.capabilities?.disabledDomains ?? []);\n const services = getLiveServices(hooks, capabilities.domains, disabled);\n const available = Object.freeze({\n domains: freezeList(capabilities.domains),\n services: freezeList(services),\n });\n const granted = hooks.capabilities?.resolveEnvironment?.(identity, available) ?? available;\n\n return Object.freeze({\n capabilities: Object.freeze({\n domains: freezeList(intersectInOrder(available.domains, granted.domains)),\n }),\n services: freezeList(intersectInOrder(available.services, granted.services)),\n });\n}\n\nfunction isServiceDomainLive(hooks: ShellAdapter, domain: string): boolean {\n if (!hooks.services?.[domain]) return false;\n\n switch (domain) {\n case 'outbox': return Boolean(hooks.relayPool);\n case 'upload': return hooks.upload?.getUploader() !== null && hooks.upload?.getUploader() !== undefined;\n case 'intent': return hooks.intent?.isAvailable() === true;\n case 'link': return hooks.link?.isAvailable() === true;\n case 'common': return hooks.common?.isAvailable() === true;\n case 'lists': return hooks.lists?.isAvailable() === true;\n case 'serial': return hooks.serial?.isAvailable() === true;\n case 'ble': return hooks.ble?.isAvailable() === true;\n case 'webrtc': return hooks.webrtc?.isAvailable() === true;\n default: return true;\n }\n}\n\nfunction getLiveServices(\n hooks: ShellAdapter,\n domains: readonly string[],\n disabled: ReadonlySet<string>,\n): string[] {\n const liveDomains = new Set(domains);\n return Object.keys(hooks.services ?? {}).filter((name) => {\n if (disabled.has(name)) return false;\n return !SERVICE_ONLY_DOMAINS.includes(name as typeof SERVICE_ONLY_DOMAINS[number]) || liveDomains.has(name);\n });\n}\n\nfunction intersectInOrder(available: readonly string[], requested: readonly string[]): string[] {\n const requestedSet = new Set(requested);\n return available.filter((entry) => requestedSet.has(entry));\n}\n\nfunction freezeList(values: readonly string[]): readonly string[] {\n return Object.freeze([...values]);\n}\n","import type { Runtime, SessionEntry } from '@kehto/runtime';\nimport { originRegistry, type OriginIdentity } from './origin-registry.js';\nimport { resolveShellEnvironment } from './shell-init.js';\nimport type { ShellAdapter, ShellEnvironment } from './types.js';\n\ninterface ShellReadyOptions {\n hooks: ShellAdapter;\n origin: string;\n runtime: Runtime;\n state: ShellReadyState;\n sourceRegistrationId: number;\n sourceWindow: Window;\n windowId: string;\n}\n\n/** State owned by one ShellBridge instance for its NAP-SHELL lifecycles. */\nexport interface ShellReadyState {\n isDomainAllowed(windowId: string, domain: string): boolean;\n clear(): void;\n readonly initSent: WeakMap<Window, number>;\n readonly sessionRegistration: Map<string, number>;\n readonly environments: Map<string, ShellEnvironment>;\n}\n\n/** Create isolated handshake state for one bridge/runtime pair. */\nexport function createShellReadyState(): ShellReadyState {\n const initSent = new WeakMap<Window, number>();\n const sessionRegistration = new Map<string, number>();\n const environments = new Map<string, ShellEnvironment>();\n return {\n initSent,\n sessionRegistration,\n environments,\n isDomainAllowed(windowId, domain): boolean {\n return environments.get(windowId)?.capabilities.domains.includes(domain) ?? false;\n },\n clear(): void {\n sessionRegistration.clear();\n environments.clear();\n },\n };\n}\n\nexport function handleShellReady({\n hooks,\n origin,\n runtime,\n state,\n sourceRegistrationId,\n sourceWindow,\n windowId,\n}: ShellReadyOptions): void {\n // SHELL-01: exactly-once shell.init per registered Window lifecycle.\n if (state.initSent.get(sourceWindow) === sourceRegistrationId) {\n return;\n }\n\n const identity = resolveNip5dIdentity(hooks, windowId, sourceWindow);\n if (!identity) return;\n\n registerNip5dSessionIfNeeded({ origin, runtime, state, sourceRegistrationId, windowId, identity });\n const environment = originRegistry.getEnvironment(sourceWindow) ?? resolveShellEnvironment(hooks, identity);\n state.environments.set(windowId, environment);\n postShellInit(sourceWindow, environment);\n state.initSent.set(sourceWindow, sourceRegistrationId);\n}\n\nfunction registerNip5dSessionIfNeeded({\n origin,\n runtime,\n state,\n sourceRegistrationId,\n windowId,\n identity,\n}: Pick<ShellReadyOptions, 'origin' | 'runtime' | 'state' | 'sourceRegistrationId' | 'windowId'> & {\n identity: OriginIdentity;\n}): void {\n // NIP-5D: register a source-identity session entry in runtime.sessionRegistry\n // if one does not already exist for this windowId. This wires the originRegistry\n // identity into the runtime so domain handlers (storage/state, inc, etc.) can\n // resolve the napplet via getEntryByWindowId(windowId).\n const existing = runtime.sessionRegistry.getEntryByWindowId(windowId);\n const previousRegistration = state.sessionRegistration.get(windowId);\n if (existing && previousRegistration === sourceRegistrationId) {\n return;\n }\n if (existing && previousRegistration !== undefined) {\n runtime.sessionRegistry.unregister(windowId);\n }\n if (existing && previousRegistration === undefined) return;\n\n const entry: SessionEntry = {\n pubkey: '',\n windowId,\n origin,\n type: 'nip5d',\n dTag: identity.dTag,\n aggregateHash: identity.aggregateHash,\n registeredAt: Date.now(),\n instanceId: crypto.randomUUID(),\n provenance: 'nip-5d',\n };\n runtime.sessionRegistry.register(windowId, entry);\n state.sessionRegistration.set(windowId, sourceRegistrationId);\n}\n\nfunction resolveNip5dIdentity(\n hooks: ShellAdapter,\n windowId: string,\n sourceWindow: Window,\n): { dTag: string; aggregateHash: string } | null {\n // Identity resolution order:\n // 1. hooks.onNip5dIframeCreate?.(windowId) — preferred.\n // 2. originRegistry.getIdentity(win) — fallback for hosts that register\n // identity directly via originRegistry.register(win, windowId, identity).\n const hookIdentity = hooks.onNip5dIframeCreate?.(windowId);\n if (hookIdentity !== null && hookIdentity !== undefined) {\n return Object.freeze({\n dTag: hookIdentity.dTag,\n aggregateHash: hookIdentity.aggregateHash,\n });\n }\n\n const originIdentity = originRegistry.getIdentity(sourceWindow);\n if (!originIdentity) {\n return null;\n }\n\n return Object.freeze({\n dTag: originIdentity.dTag,\n aggregateHash: originIdentity.aggregateHash,\n });\n}\n\nfunction postShellInit(\n win: Window,\n environment: ShellEnvironment,\n): void {\n const initMsg = {\n type: 'shell.init',\n capabilities: environment.capabilities,\n services: environment.services,\n };\n win.postMessage(initMsg, '*');\n}\n","/** Canonical request fields produced from a NAP-INTENT convention URI. */\nexport interface NormalizedIntentUri {\n archetype: string;\n action: string;\n convention: string;\n payload?: unknown;\n handlerHint?: { address: string; relays?: string[] };\n handler?: string;\n behavior?: { focus?: boolean; reuse?: boolean };\n}\n\n/**\n * Create an isolated NAP-INTENT normalizer for host code or an injected prelude.\n *\n * @returns A canonical URI normalizer whose parsing helpers are self-contained.\n * @example\n * ```ts\n * const normalize = createIntentUriNormalizer();\n * normalize('napplet:profile/open');\n * ```\n */\nexport function createIntentUriNormalizer(): (uri: unknown, options?: unknown) => NormalizedIntentUri {\n type RecordValue = Record<string, unknown>;\n const hasOwn = (value: RecordValue, key: string): boolean => Object.prototype.hasOwnProperty.call(value, key);\n const fail = (message: string): never => { throw new TypeError(message); };\n const decode = (value: string, label: string): string => {\n try {\n return decodeURIComponent(value);\n } catch {\n return fail(`Intent URI has malformed percent-encoding in ${label}`);\n }\n };\n const decodeUtf8 = (bytes: number[]): string => {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(new Uint8Array(bytes));\n } catch {\n return fail('Intent URI fragment contains invalid UTF-8');\n }\n };\n const decodeHint = (fragment: string): { address: string; relays?: string[] } => {\n if (!fragment.startsWith('naddr') || fragment !== fragment.toLowerCase()) {\n return fail('Intent URI fragment must be a bare lowercase naddr');\n }\n const separator = fragment.lastIndexOf('1');\n if (separator <= 0 || separator + 7 > fragment.length) fail('Intent URI fragment is not a valid naddr');\n const alphabet = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\n const values: number[] = [];\n for (const character of fragment.slice(separator + 1)) {\n const value = alphabet.indexOf(character);\n if (value < 0) fail('Intent URI fragment is not a valid naddr');\n values.push(value);\n }\n const polymod = (input: number[]): number => {\n let checksum = 1;\n for (const value of input) {\n const top = checksum >>> 25;\n checksum = ((checksum & 0x1ffffff) << 5) ^ value;\n if (top & 1) checksum ^= 0x3b6a57b2;\n if (top & 2) checksum ^= 0x26508e6d;\n if (top & 4) checksum ^= 0x1ea119fa;\n if (top & 8) checksum ^= 0x3d4233dd;\n if (top & 16) checksum ^= 0x2a1462b3;\n }\n return checksum;\n };\n const hrp = fragment.slice(0, separator);\n const hrpValues = [...hrp].map((character) => character.charCodeAt(0) >>> 5)\n .concat([0], [...hrp].map((character) => character.charCodeAt(0) & 31));\n if (hrp !== 'naddr' || polymod(hrpValues.concat(values)) !== 1) fail('Intent URI fragment is not a valid naddr');\n const words = values.slice(0, -6);\n const bytes: number[] = [];\n let accumulator = 0;\n let bits = 0;\n for (const word of words) {\n accumulator = (accumulator << 5) | word;\n bits += 5;\n while (bits >= 8) {\n bits -= 8;\n bytes.push((accumulator >>> bits) & 0xff);\n }\n }\n if (bits >= 5 || ((accumulator << (8 - bits)) & 0xff) !== 0) fail('Intent URI fragment is not a valid naddr');\n\n let index = 0;\n let identifier: string | undefined;\n let pubkey: string | undefined;\n let kind: number | undefined;\n const relays: string[] = [];\n while (index < bytes.length) {\n if (index + 2 > bytes.length) fail('Intent URI fragment is not a valid naddr');\n const type = bytes[index++];\n const length = bytes[index++];\n if (index + length > bytes.length) fail('Intent URI fragment is not a valid naddr');\n const value = bytes.slice(index, index + length);\n index += length;\n if (type === 0) {\n if (identifier !== undefined) fail('Intent URI fragment repeats its identifier');\n identifier = decodeUtf8(value);\n } else if (type === 1) {\n const relay = decodeUtf8(value);\n if (!relay) fail('Intent URI fragment has an empty relay hint');\n relays.push(relay);\n } else if (type === 2) {\n if (pubkey !== undefined || value.length !== 32) fail('Intent URI fragment has an invalid pubkey');\n pubkey = value.map((part) => part.toString(16).padStart(2, '0')).join('');\n } else if (type === 3) {\n if (kind !== undefined || value.length !== 4) fail('Intent URI fragment has an invalid kind');\n kind = (((value[0] << 24) >>> 0) | (value[1] << 16) | (value[2] << 8) | value[3]) >>> 0;\n } else {\n fail('Intent URI fragment has unsupported naddr data');\n }\n }\n if (!identifier || !pubkey || kind !== 35129) fail('Intent URI fragment must recommend a named 35129 napplet');\n return { address: `${kind}:${pubkey}:${identifier}`, ...(relays.length > 0 ? { relays } : {}) };\n };\n const normalizeHint = (value: unknown): { address: string; relays?: string[] } => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) fail('Intent handlerHint must be an object');\n const hint = value as RecordValue;\n if (Object.keys(hint).some((key) => key !== 'address' && key !== 'relays')) fail('Intent handlerHint contains unsupported fields');\n const address = hint.address;\n if (typeof address !== 'string' || !/^35129:[0-9a-f]{64}:.+$/u.test(address)) {\n fail('Intent handlerHint address must be a named 35129 coordinate');\n }\n const relays = hint.relays;\n if (relays !== undefined && (!Array.isArray(relays) || relays.some((relay) => typeof relay !== 'string' || relay.length === 0))) {\n fail('Intent handlerHint relays must be non-empty text');\n }\n return { address: address as string, ...(relays === undefined ? {} : { relays: [...(relays as string[])] }) };\n };\n\n return function normalizeIntentUri(uri: unknown, options?: unknown): NormalizedIntentUri {\n if (typeof uri !== 'string') throw new TypeError('Intent URI must be text');\n const match = /^napplet:([^/?#\\s]+)\\/([^/?#\\s]+)(?:\\?([^#]*))?(?:#(.*))?$/u.exec(uri);\n if (match === null) return fail('Intent URI must be napplet:<archetype>/<action>');\n const archetype = match[1]!;\n const action = match[2]!;\n if (!/^[a-z0-9][a-z0-9-]*$/u.test(archetype) || !/^[a-z0-9][a-z0-9-]*$/u.test(action)) {\n fail('Intent URI archetype and action must be lowercase slugs');\n }\n const query = match[3];\n const fragment = match[4];\n const supplied = options === undefined ? {} : options;\n if (!supplied || typeof supplied !== 'object' || Array.isArray(supplied)) fail('Intent options must be an object');\n const parsedOptions = supplied as RecordValue;\n if (Object.keys(parsedOptions).some((key) => key !== 'payload' && key !== 'handler' && key !== 'handlerHint' && key !== 'behavior')) {\n fail('Intent options contain unsupported fields');\n }\n const handler = parsedOptions.handler;\n if (handler !== undefined && (typeof handler !== 'string' || handler.length === 0)) {\n fail('Intent handler must be non-empty text');\n }\n let behavior: { focus?: boolean; reuse?: boolean } | undefined;\n if (parsedOptions.behavior !== undefined) {\n if (!parsedOptions.behavior || typeof parsedOptions.behavior !== 'object' || Array.isArray(parsedOptions.behavior)) fail('Intent behavior must be an object');\n const value = parsedOptions.behavior as RecordValue;\n if (Object.keys(value).some((key) => key !== 'focus' && key !== 'reuse')\n || (hasOwn(value, 'focus') && typeof value.focus !== 'boolean')\n || (hasOwn(value, 'reuse') && typeof value.reuse !== 'boolean')) fail('Intent behavior contains unsupported fields');\n behavior = {\n ...(hasOwn(value, 'focus') ? { focus: value.focus as boolean } : {}),\n ...(hasOwn(value, 'reuse') ? { reuse: value.reuse as boolean } : {}),\n };\n }\n let payload: unknown;\n if (query !== undefined) {\n if (hasOwn(parsedOptions, 'payload')) fail('Intent URI query cannot accompany options.payload');\n if (query.length > 0) {\n const fields = Object.create(null) as RecordValue;\n for (const field of query.split('&')) {\n const equal = field.indexOf('=');\n if (equal <= 0 || field.indexOf('=', equal + 1) >= 0) fail('Intent URI query fields must be name=value');\n const name = decode(field.slice(0, equal), 'a query name');\n const value = decode(field.slice(equal + 1), 'a query value');\n if (!name || hasOwn(fields, name)) fail('Intent URI query names must be unique after decoding');\n Object.defineProperty(fields, name, { value, enumerable: true, writable: true, configurable: true });\n }\n payload = fields;\n }\n } else if (hasOwn(parsedOptions, 'payload')) {\n payload = parsedOptions.payload;\n }\n if (fragment !== undefined) {\n if (!fragment) fail('Intent URI fragment must be a bare naddr');\n if (parsedOptions.handlerHint !== undefined) fail('Intent URI fragment cannot accompany options.handlerHint');\n }\n const handlerHint = fragment === undefined\n ? (parsedOptions.handlerHint === undefined ? undefined : normalizeHint(parsedOptions.handlerHint))\n : decodeHint(fragment);\n return {\n archetype,\n action,\n convention: `napplet:${archetype}/${action}`,\n ...(payload === undefined ? {} : { payload }),\n ...(handlerHint === undefined ? {} : { handlerHint }),\n ...(handler === undefined ? {} : { handler: handler as string }),\n ...(behavior === undefined ? {} : { behavior }),\n };\n };\n}\n\n/**\n * Normalize a NAP-INTENT convention URI.\n *\n * The host and injected NIP-5D binding use the same normalizer factory.\n *\n * @param uri - Complete NAP-INTENT convention URI.\n * @param options - Optional payload, handler, recommendation, and behavior hints.\n * @returns The canonical request fields for `intent.invoke`.\n * @example\n * ```ts\n * normalizeIntentUri('napplet:profile/open?pubkey=abc%2B123');\n * // { archetype: 'profile', action: 'open', convention: 'napplet:profile/open', payload: { pubkey: 'abc+123' } }\n * ```\n */\nexport const normalizeIntentUri = createIntentUriNormalizer();\n","/**\n * The injected implementation must remain one self-contained function: the\n * renderer serializes it ahead of verified artifact scripts without changing\n * the signed artifact bytes. Splitting it into imported helpers would leave\n * unresolved closures in the generated `srcdoc`.\n *\n * aislop-ignore-file complexity/file-too-large complexity/function-too-long\n */\n\nimport { createIntentUriNormalizer } from './intent-uri.js';\n\n/**\n * Options for rendering the host-owned NIP-5D `window.napplet` namespace prelude.\n *\n * @example\n * ```ts\n * const options: NappletNamespacePreludeOptions = {\n * domains: ['shell', 'relay', 'identity'],\n * };\n * ```\n */\nexport interface NappletNamespacePreludeOptions {\n /**\n * Optional bare NAP domain names the shell exposes to this napplet.\n * Mandatory `shell` is injected even when omitted here.\n */\n domains: readonly string[];\n}\n\nfunction uniqueBareDomains(domains: readonly string[]): string[] {\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const domain of domains) {\n const value = domain.trim();\n if (!value || value.includes(':') || value.startsWith('perm:') || seen.has(value)) {\n continue;\n }\n seen.add(value);\n normalized.push(value);\n }\n return normalized;\n}\n\nfunction scriptJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/**\n * Render the host-owned NIP-5D bootstrap that exposes available NAP domains\n * under `window.napplet` before napplet artifact code runs.\n *\n * @param options - Domain availability to inject.\n * @returns An inline script tag suitable for `srcdoc` prelude insertion.\n * @example\n * ```ts\n * const prelude = renderNappletNamespacePrelude({\n * domains: ['shell', 'relay', 'identity'],\n * });\n * ```\n */\nexport function renderNappletNamespacePrelude(options: NappletNamespacePreludeOptions): string {\n const domains = uniqueBareDomains(['shell', ...options.domains]);\n return `<script data-kehto-nip5d-injection>(${nappletNamespacePrelude.toString()})(${scriptJson(domains)}, (${createIntentUriNormalizer.toString()})());</script>`;\n}\n\n/**\n * Insert the NIP-5D namespace prelude into HTML before authored scripts.\n *\n * @param html - Verified napplet artifact HTML.\n * @param options - Domain availability to inject.\n * @returns HTML with the prelude inside `<head>` when possible.\n * @example\n * ```ts\n * const srcdoc = injectNappletNamespacePrelude(verifiedHtml, {\n * domains: ['shell', 'relay', 'identity'],\n * });\n * iframe.srcdoc = srcdoc;\n * ```\n */\nexport function injectNappletNamespacePrelude(\n html: string,\n options: NappletNamespacePreludeOptions,\n): string {\n const prelude = renderNappletNamespacePrelude(options);\n const cspMeta = /(<meta\\s+http-equiv=[\"']Content-Security-Policy[\"'][^>]*>)/i;\n if (cspMeta.test(html)) {\n return html.replace(cspMeta, (match) => `${match}${prelude}`);\n }\n if (/<head[^>]*>/i.test(html)) {\n return html.replace(/<head[^>]*>/i, (open) => `${open}${prelude}`);\n }\n if (/<html[^>]*>/i.test(html)) {\n return html.replace(/<html[^>]*>/i, (open) => `${open}<head>${prelude}</head>`);\n }\n return `${prelude}${html}`;\n}\n\nfunction nappletNamespacePrelude(\n domains: string[],\n normalizeIntentUri: (uri: unknown, options?: unknown) => Record<string, unknown>,\n): void {\n const target = window as Window & { napplet?: Record<string, unknown> };\n const allowed = new Set(domains);\n const requestTimeoutMs = 30_000;\n\n type RuntimeMessage = { type: string; id?: string; [key: string]: unknown };\n type Listener = (event: MessageEvent) => void;\n\n function id(): string {\n if (target.crypto?.randomUUID) return target.crypto.randomUUID();\n return `napplet-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n }\n\n function post(message: RuntimeMessage): void {\n target.parent.postMessage(message, '*');\n }\n\n function listen(listener: Listener): () => void {\n target.addEventListener('message', listener);\n return () => target.removeEventListener('message', listener);\n }\n\n function isParentMessage(event: MessageEvent): boolean {\n return event.source === target.parent;\n }\n\n function request<T>(\n message: RuntimeMessage,\n resultType: string,\n map: (message: RuntimeMessage) => T,\n options: {\n rejectOnError?: boolean;\n timeoutMs?: number | null;\n signal?: AbortSignal;\n cancelOnAbort?: boolean;\n } = {},\n ): Promise<T> {\n const requestId = message.id ?? id();\n const outbound = { ...message, id: requestId };\n const timeoutMs = options.timeoutMs === undefined ? requestTimeoutMs : options.timeoutMs;\n if (options.signal?.aborted) return Promise.reject(new DOMException('Aborted', 'AbortError'));\n return new Promise<T>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let off: (() => void) | undefined;\n const cleanup = (): void => {\n off?.();\n if (timer !== undefined) clearTimeout(timer);\n options.signal?.removeEventListener('abort', abort);\n };\n const abort = (): void => {\n cleanup();\n if (options.cancelOnAbort) post({ type: 'resource.cancel', id: requestId });\n reject(new DOMException('Aborted', 'AbortError'));\n };\n off = listen((event) => {\n if (!isParentMessage(event)) return;\n const incoming = event.data;\n if (typeof incoming !== 'object' || incoming === null) return;\n const msg = incoming as RuntimeMessage;\n if (msg.type !== resultType && msg.type !== `${message.type}.error`) return;\n if (msg.id !== requestId) return;\n cleanup();\n const error = typeof msg.error === 'string' ? msg.error : '';\n if (error && options.rejectOnError !== false) {\n reject(new Error(error));\n return;\n }\n try {\n resolve(map(msg));\n } catch (err) {\n reject(err);\n }\n });\n if (timeoutMs !== null) {\n timer = setTimeout(() => {\n cleanup();\n reject(new Error(`${message.type} timed out`));\n }, timeoutMs);\n }\n options.signal?.addEventListener('abort', abort, { once: true });\n post(outbound);\n });\n }\n\n function fire(message: RuntimeMessage): void {\n post(message);\n }\n\n function isConventionTopic(topic: string): boolean {\n const pathEnd = topic.search(/[?#]/);\n const path = pathEnd === -1 ? topic : topic.slice(0, pathEnd);\n return /^napplet:[^/?#]+\\/[^/?#]+$/.test(path);\n }\n\n function normalizeConventionUri(\n topic: unknown,\n hasExplicitPayload: boolean,\n ): { topic: string; payload?: Record<string, string> } {\n if (typeof topic !== 'string') throw new TypeError('INC topic must be text');\n if (!isConventionTopic(topic)) return { topic };\n if (topic.includes('#')) throw new TypeError('Convention topics cannot contain fragments');\n const queryStart = topic.indexOf('?');\n if (queryStart === -1) {\n return { topic };\n }\n if (hasExplicitPayload) {\n throw new TypeError('Convention queries cannot be combined with an explicit payload');\n }\n\n const entries: Array<[string, string]> = [];\n const names = new Set<string>();\n const query = topic.slice(queryStart + 1);\n if (query) {\n for (const pair of query.split('&')) {\n const separator = pair.indexOf('=');\n if (separator < 0) {\n throw new TypeError('Convention query parameters must use name=value form');\n }\n let name: string;\n let value: string;\n try {\n name = decodeURIComponent(pair.slice(0, separator));\n value = decodeURIComponent(pair.slice(separator + 1));\n } catch {\n throw new TypeError('Convention query contains malformed percent encoding');\n }\n if (names.has(name)) throw new TypeError('Convention query names must be unique');\n names.add(name);\n entries.push([name, value]);\n }\n }\n return { topic: topic.slice(0, queryStart), payload: Object.fromEntries(entries) };\n }\n\n function resultOrError(msg: RuntimeMessage): Record<string, unknown> {\n return msg;\n }\n\n function withoutEnvelope(msg: Record<string, unknown>): Record<string, unknown> {\n const { type: _type, id: _id, ...result } = msg;\n return result;\n }\n\n function fieldOrThrow<T>(msg: RuntimeMessage, field: string, fallback: string): T {\n if (Object.prototype.hasOwnProperty.call(msg, field)) return msg[field] as T;\n throw new Error(typeof msg.error === 'string' ? msg.error : fallback);\n }\n\n function voidResult(msg: RuntimeMessage, fallback: string): void {\n if (typeof msg.error === 'string' && msg.error) throw new Error(msg.error);\n if (msg.ok === false) throw new Error(fallback);\n }\n\n function subscriptionHandle(close: () => void): { close(): void } {\n let closed = false;\n return {\n close() {\n if (closed) return;\n closed = true;\n close();\n },\n };\n }\n\n function makeShell(): Record<string, unknown> {\n type ShellEnvironment = {\n capabilities: Readonly<{ domains: readonly string[] }>;\n services: readonly string[];\n };\n type ReadyHandler = (environment: ShellEnvironment) => void;\n\n const emptyServices = Object.freeze([] as string[]);\n const readyHandlers = new Set<ReadyHandler>();\n let environment: ShellEnvironment | undefined;\n let resolveReady: (environment: ShellEnvironment) => void = () => undefined;\n const ready = new Promise<ShellEnvironment>((resolve) => {\n resolveReady = resolve;\n });\n\n const off = listen((event) => {\n if (!isParentMessage(event) || environment) return;\n const incoming = event.data;\n if (typeof incoming !== 'object' || incoming === null) return;\n const message = incoming as RuntimeMessage;\n if (message.type !== 'shell.init') return;\n\n const rawCapabilities = message.capabilities;\n const rawDomains = typeof rawCapabilities === 'object' && rawCapabilities !== null\n ? (rawCapabilities as Record<string, unknown>).domains\n : undefined;\n if (!Array.isArray(rawDomains)) return;\n\n const domains = freezeStrings(rawDomains);\n const services = freezeStrings(Array.isArray(message.services) ? message.services : []);\n environment = Object.freeze({\n capabilities: Object.freeze({ domains }),\n services,\n });\n off();\n resolveReady(environment);\n for (const handler of readyHandlers) handler(environment);\n readyHandlers.clear();\n });\n\n function freezeStrings(values: readonly unknown[]): readonly string[] {\n const seen = new Set<string>();\n const strings: string[] = [];\n for (const value of values) {\n if (typeof value !== 'string' || value.length === 0 || seen.has(value)) continue;\n seen.add(value);\n strings.push(value);\n }\n return Object.freeze(strings);\n }\n\n function supports(domain: string): boolean {\n return typeof domain === 'string' && environment?.capabilities.domains.includes(domain) === true;\n }\n\n const shell = {\n ready: () => ready,\n supports,\n get services(): readonly string[] {\n return environment?.services ?? emptyServices;\n },\n set services(_services: readonly string[]) {\n // Ignore napplet/shim reassignment; NAP-SHELL services stay runtime-owned.\n },\n onReady(handler: ReadyHandler) {\n if (environment) {\n handler(environment);\n return subscriptionHandle(() => undefined);\n }\n readyHandlers.add(handler);\n return subscriptionHandle(() => readyHandlers.delete(handler));\n },\n };\n\n post({ type: 'shell.ready' });\n return shell;\n }\n\n function domainEventHandle(\n eventType: string,\n callback: (event: unknown) => void,\n select: (message: RuntimeMessage) => unknown = (message) => message.event,\n ): { close(): void } {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === eventType) callback(select(msg));\n });\n return subscriptionHandle(off);\n }\n\n function makeRelay(): Record<string, unknown> {\n return {\n subscribe(filters: unknown, onEvent: (result: unknown) => void, onEose: () => void, options?: { relay?: string }) {\n const subId = id();\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.subId !== subId) return;\n if (msg.type === 'relay.event') onEvent(msg.result);\n else if (msg.type === 'relay.eose') onEose();\n else if (msg.type === 'relay.closed') off();\n });\n fire({\n type: 'relay.subscribe',\n id: id(),\n subId,\n filters: Array.isArray(filters) ? filters : [filters],\n ...(options?.relay ? { relay: options.relay } : {}),\n });\n return subscriptionHandle(() => {\n fire({ type: 'relay.close', id: id(), subId });\n off();\n });\n },\n publish(template: unknown) {\n return request(\n { type: 'relay.publish', event: template },\n 'relay.publish.result',\n (msg) => {\n if (!msg.event) throw new Error('relay.publish.result missing event');\n return msg.event;\n },\n );\n },\n publishEncrypted(template: unknown, recipient: string, encryption = 'nip44') {\n return request(\n { type: 'relay.publishEncrypted', event: template, recipient, encryption },\n 'relay.publishEncrypted.result',\n (msg) => {\n if (!msg.event) throw new Error('relay.publishEncrypted.result missing event');\n return msg.event;\n },\n );\n },\n query(filters: unknown) {\n return request(\n { type: 'relay.query', filters: Array.isArray(filters) ? filters : [filters] },\n 'relay.query.result',\n (msg) => Array.isArray(msg.events) ? msg.events : [],\n );\n },\n };\n }\n\n function makeInc(): Record<string, unknown> {\n type IncEvent = { topic: string; sender: string; payload?: unknown };\n type TopicState = {\n handlers: Set<(event: IncEvent) => void>;\n offEvent: () => void;\n offResult: () => void;\n };\n const topicStates = new Map<string, TopicState>();\n type ChannelEvent = { channelId: string; sender: string; payload?: unknown };\n type ChannelClosed = { channelId: string; reason?: string };\n type ChannelState = {\n channelId: string;\n peer: string;\n eventHandlers: Set<(event: ChannelEvent) => void>;\n closedHandlers: Set<(closed: ChannelClosed) => void>;\n pendingEvents: ChannelEvent[];\n closed?: ChannelClosed;\n };\n const maxRetainedEvents = 32;\n const channelStates = new Map<string, ChannelState>();\n const openedHandlers = new Set<(handle: Record<string, unknown>) => void>();\n const pendingOpened: ChannelState[] = [];\n const unopenedEvents = new Map<string, ChannelEvent[]>();\n const unopenedClosed = new Map<string, ChannelClosed>();\n\n function stableSubscriptionTopic(topic: unknown): string {\n if (typeof topic !== 'string') throw new TypeError('INC topic must be text');\n if (isConventionTopic(topic) && (topic.includes('?') || topic.includes('#'))) {\n throw new TypeError('INC subscriptions require a queryless topic identity');\n }\n return topic;\n }\n\n function closeChannelState(state: ChannelState, closed: ChannelClosed, notifyShell: boolean): void {\n if (state.closed) return;\n state.closed = closed;\n if (notifyShell) fire({ type: 'inc.channel.close', channelId: state.channelId });\n for (const handler of state.closedHandlers) handler(closed);\n }\n\n function makeChannelHandle(state: ChannelState): Record<string, unknown> {\n return {\n id: state.channelId,\n peer: state.peer,\n emit(payload?: unknown) {\n if (state.closed) return;\n fire({ type: 'inc.channel.emit', channelId: state.channelId, ...(payload === undefined ? {} : { payload }) });\n },\n on(handler: (event: ChannelEvent) => void) {\n if (typeof handler !== 'function') throw new TypeError('INC channel event handler must be a function');\n state.eventHandlers.add(handler);\n const pending = state.pendingEvents.splice(0);\n for (const event of pending) handler(event);\n return subscriptionHandle(() => state.eventHandlers.delete(handler));\n },\n onClosed(handler: (closed: ChannelClosed) => void) {\n if (typeof handler !== 'function') throw new TypeError('INC channel close handler must be a function');\n state.closedHandlers.add(handler);\n if (state.closed) handler(state.closed);\n return subscriptionHandle(() => state.closedHandlers.delete(handler));\n },\n close() {\n closeChannelState(state, { channelId: state.channelId }, true);\n },\n };\n }\n\n function materializeChannel(channelId: string, peer: string): ChannelState {\n const existing = channelStates.get(channelId);\n if (existing) return existing;\n const state: ChannelState = {\n channelId,\n peer,\n eventHandlers: new Set(),\n closedHandlers: new Set(),\n pendingEvents: unopenedEvents.get(channelId) ?? [],\n };\n unopenedEvents.delete(channelId);\n channelStates.set(channelId, state);\n const closed = unopenedClosed.get(channelId);\n unopenedClosed.delete(channelId);\n if (closed) closeChannelState(state, closed, false);\n return state;\n }\n\n function deliverOpened(state: ChannelState): void {\n const handle = makeChannelHandle(state);\n if (openedHandlers.size > 0) {\n for (const handler of openedHandlers) handler(handle);\n return;\n }\n pendingOpened.push(state);\n }\n\n function receiveChannelEvent(channelId: string, sender: string, payloadPresent: boolean, payload: unknown): void {\n const event: ChannelEvent = payloadPresent ? { channelId, sender, payload } : { channelId, sender };\n const state = channelStates.get(channelId);\n if (!state) {\n const pending = unopenedEvents.get(channelId) ?? [];\n if (pending.length >= maxRetainedEvents) {\n unopenedEvents.delete(channelId);\n unopenedClosed.set(channelId, { channelId, reason: 'buffer overflow' });\n fire({ type: 'inc.channel.close', channelId });\n return;\n }\n pending.push(event);\n unopenedEvents.set(channelId, pending);\n return;\n }\n if (state.closed) return;\n if (state.eventHandlers.size > 0) {\n for (const handler of state.eventHandlers) handler(event);\n return;\n }\n if (state.pendingEvents.length >= maxRetainedEvents) {\n closeChannelState(state, { channelId, reason: 'buffer overflow' }, true);\n return;\n }\n state.pendingEvents.push(event);\n }\n\n listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || typeof msg.type !== 'string') return;\n if (msg.type === 'inc.channel.opened' && typeof msg.channelId === 'string' && typeof msg.peer === 'string') {\n deliverOpened(materializeChannel(msg.channelId, msg.peer));\n return;\n }\n if (msg.type === 'inc.channel.event' && typeof msg.channelId === 'string' && typeof msg.sender === 'string') {\n receiveChannelEvent(msg.channelId, msg.sender, Object.prototype.hasOwnProperty.call(msg, 'payload'), msg.payload);\n return;\n }\n if (msg.type === 'inc.channel.closed' && typeof msg.channelId === 'string') {\n const closed: ChannelClosed = typeof msg.reason === 'string'\n ? { channelId: msg.channelId, reason: msg.reason }\n : { channelId: msg.channelId };\n const state = channelStates.get(msg.channelId);\n if (state) closeChannelState(state, closed, false);\n else unopenedClosed.set(msg.channelId, closed);\n }\n });\n\n return {\n emit(topic: string, payload?: unknown) {\n const transposed = normalizeConventionUri(topic, arguments.length > 1);\n fire({\n type: 'inc.emit',\n topic: transposed.topic,\n ...(transposed.payload === undefined && payload === undefined ? {} : { payload: transposed.payload ?? payload }),\n });\n },\n on(topic: string, callback: (event: IncEvent) => void) {\n const stableTopic = stableSubscriptionTopic(topic);\n if (typeof callback !== 'function') throw new TypeError('INC subscription handler must be a function');\n let state = topicStates.get(stableTopic);\n if (!state) {\n const handlers = new Set<(event: IncEvent) => void>();\n const subscriptionId = id();\n const offEvent = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (\n typeof msg !== 'object'\n || msg === null\n || msg.type !== 'inc.event'\n || msg.topic !== stableTopic\n || typeof msg.sender !== 'string'\n ) return;\n const delivered: IncEvent = Object.prototype.hasOwnProperty.call(msg, 'payload')\n ? { topic: stableTopic, sender: msg.sender, payload: msg.payload }\n : { topic: stableTopic, sender: msg.sender };\n for (const handler of handlers) handler(delivered);\n });\n const offResult = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.type !== 'inc.subscribe.result' || msg.id !== subscriptionId) return;\n offResult();\n if (typeof msg.error === 'string' && msg.error) {\n offEvent();\n topicStates.delete(stableTopic);\n }\n });\n state = { handlers, offEvent, offResult };\n topicStates.set(stableTopic, state);\n fire({ type: 'inc.subscribe', id: subscriptionId, topic: stableTopic });\n }\n state.handlers.add(callback);\n const offLegacy = intentDelivery?.onLegacy(stableTopic, (delivery) => callback({\n topic: delivery.convention,\n sender: delivery.sender,\n ...(Object.prototype.hasOwnProperty.call(delivery, 'payload') ? { payload: delivery.payload } : {}),\n }));\n return subscriptionHandle(() => {\n offLegacy?.();\n const current = topicStates.get(stableTopic);\n if (!current) return;\n current.handlers.delete(callback);\n if (current.handlers.size !== 0) return;\n current.offEvent();\n current.offResult();\n topicStates.delete(stableTopic);\n fire({ type: 'inc.unsubscribe', topic: stableTopic });\n });\n },\n channel: {\n open(targetDTag: string) {\n return request(\n { type: 'inc.channel.open', target: targetDTag },\n 'inc.channel.open.result',\n (msg) => {\n if (typeof msg.channelId !== 'string' || typeof msg.peer !== 'string') {\n throw new Error('inc.channel.open.result missing channel identity');\n }\n return makeChannelHandle(materializeChannel(msg.channelId, msg.peer));\n },\n );\n },\n onOpened(handler: (handle: Record<string, unknown>) => void) {\n if (typeof handler !== 'function') throw new TypeError('INC opened handler must be a function');\n openedHandlers.add(handler);\n const pending = pendingOpened.splice(0);\n for (const state of pending) handler(makeChannelHandle(state));\n return subscriptionHandle(() => openedHandlers.delete(handler));\n },\n list() {\n return request(\n { type: 'inc.channel.list' },\n 'inc.channel.list.result',\n (msg) => Object.freeze((Array.isArray(msg.channels) ? msg.channels : []).flatMap((channel) => (\n channel\n && typeof channel === 'object'\n && typeof (channel as Record<string, unknown>).id === 'string'\n && typeof (channel as Record<string, unknown>).peer === 'string'\n ? [Object.freeze({\n id: (channel as Record<string, unknown>).id as string,\n peer: (channel as Record<string, unknown>).peer as string,\n })]\n : []\n ))),\n );\n },\n broadcast(payload?: unknown) {\n fire({ type: 'inc.channel.broadcast', ...(payload === undefined ? {} : { payload }) });\n },\n },\n };\n }\n\n function makeStorage(): Record<string, unknown> {\n const makeScope = (scope?: string) => ({\n getItem(key: string) {\n return request(\n { type: 'storage.get', key, ...(scope ? { scope } : {}) },\n 'storage.get.result',\n (msg) => msg.value ?? null,\n );\n },\n setItem(key: string, value: string) {\n return request(\n { type: 'storage.set', key, value, ...(scope ? { scope } : {}) },\n 'storage.set.result',\n () => undefined,\n );\n },\n removeItem(key: string) {\n return request(\n { type: 'storage.remove', key, ...(scope ? { scope } : {}) },\n 'storage.remove.result',\n () => undefined,\n );\n },\n keys() {\n return request(\n { type: 'storage.keys', ...(scope ? { scope } : {}) },\n 'storage.keys.result',\n (msg) => Array.isArray(msg.keys) ? msg.keys : [],\n );\n },\n });\n return { ...makeScope(), instance: makeScope('instance') };\n }\n\n function makeIdentity(): Record<string, unknown> {\n const read = <T>(type: string, field: string, fallback: T, payload: Record<string, unknown> = {}) => request(\n { type, ...payload },\n `${type}.result`,\n (msg) => (Object.prototype.hasOwnProperty.call(msg, field) ? msg[field] : fallback) as T,\n { rejectOnError: type !== 'identity.getPublicKey' },\n );\n return Object.freeze({\n getPublicKey: () => read('identity.getPublicKey', 'pubkey', ''),\n getRelays: () => read('identity.getRelays', 'relays', {}),\n getProfile: () => read('identity.getProfile', 'profile', null),\n getFollows: () => read('identity.getFollows', 'pubkeys', []),\n getList: (listType: string) => read('identity.getList', 'entries', [], { listType }),\n getZaps: () => read('identity.getZaps', 'zaps', []),\n getMutes: () => read('identity.getMutes', 'pubkeys', []),\n getBlocked: () => read('identity.getBlocked', 'pubkeys', []),\n getBadges: () => read('identity.getBadges', 'badges', []),\n onChanged(handler: (pubkey: string) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.type !== 'identity.changed') return;\n if (typeof msg.pubkey === 'string') handler(msg.pubkey);\n });\n return subscriptionHandle(off);\n },\n });\n }\n\n function makeTheme(): Record<string, unknown> {\n return {\n get: () => request({ type: 'theme.get' }, 'theme.get.result', (msg) => msg.theme),\n onChanged(handler: (theme: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'theme.changed') handler(msg.theme);\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n const keyActionCallbacks = new Map<string, Set<() => void>>();\n const keyBindingActions = new Map<string, string>();\n const modifierKeys = new Set(['Control', 'Alt', 'Shift', 'Meta']);\n const reservedKeyNames = new Set(['Tab', 'Escape']);\n const nonTextInputTypes = new Set([\n 'button',\n 'checkbox',\n 'color',\n 'file',\n 'hidden',\n 'image',\n 'radio',\n 'range',\n 'reset',\n 'submit',\n ]);\n let keysSmartForwardingInstalled = false;\n\n function normalizeKeyName(key: unknown): string {\n if (typeof key !== 'string') return '';\n return key.length === 1 ? key.toUpperCase() : key;\n }\n\n function keyComboKey(value: {\n ctrl: boolean;\n alt: boolean;\n shift: boolean;\n meta: boolean;\n key: string;\n }): string {\n return `${value.ctrl}|${value.alt}|${value.shift}|${value.meta}|${normalizeKeyName(value.key)}`;\n }\n\n function bindingComboKey(binding: unknown): string | null {\n if (typeof binding !== 'string' || binding.trim() === '') return null;\n const parts = binding.split('+');\n const key = parts.pop()?.trim();\n if (!key) return null;\n const combo = { ctrl: false, alt: false, shift: false, meta: false, key };\n for (const raw of parts) {\n const token = raw.trim().toLowerCase();\n if (!token) continue;\n if (token === 'ctrl' || token === 'control') combo.ctrl = true;\n else if (token === 'alt' || token === 'option') combo.alt = true;\n else if (token === 'shift') combo.shift = true;\n else if (token === 'meta' || token === 'cmd' || token === 'command' || token === 'win' || token === 'super') combo.meta = true;\n else return null;\n }\n return keyComboKey(combo);\n }\n\n function eventComboKey(event: {\n key?: unknown;\n ctrlKey?: unknown;\n altKey?: unknown;\n shiftKey?: unknown;\n metaKey?: unknown;\n }): string | null {\n const key = typeof event.key === 'string' ? event.key : '';\n if (!key) return null;\n return keyComboKey({\n ctrl: Boolean(event.ctrlKey),\n alt: Boolean(event.altKey),\n shift: Boolean(event.shiftKey),\n meta: Boolean(event.metaKey),\n key,\n });\n }\n\n function isTextEntryTarget(value: unknown): boolean {\n if (!value || typeof value !== 'object') return false;\n const targetNode = value as {\n tagName?: unknown;\n type?: unknown;\n isContentEditable?: unknown;\n closest?: (selector: string) => unknown;\n };\n if (targetNode.isContentEditable === true) return true;\n const tagName = typeof targetNode.tagName === 'string' ? targetNode.tagName.toLowerCase() : '';\n if (tagName === 'textarea' || tagName === 'select') return true;\n if (tagName === 'input') {\n const type = typeof targetNode.type === 'string' && targetNode.type ? targetNode.type.toLowerCase() : 'text';\n return !nonTextInputTypes.has(type);\n }\n if (typeof targetNode.closest === 'function') {\n try {\n return Boolean(targetNode.closest('[contenteditable=\"\"],[contenteditable=\"true\"],[contenteditable=\"plaintext-only\"]'));\n } catch {\n return false;\n }\n }\n return false;\n }\n\n function rememberKeyBinding(actionId: unknown, binding: unknown): void {\n if (typeof actionId !== 'string') return;\n const combo = bindingComboKey(binding);\n if (combo) keyBindingActions.set(combo, actionId);\n }\n\n function removeKeyBindingsForAction(actionId: string): void {\n for (const [combo, boundActionId] of keyBindingActions) {\n if (boundActionId === actionId) keyBindingActions.delete(combo);\n }\n }\n\n function replaceKeyBindings(bindings: unknown): void {\n keyBindingActions.clear();\n if (!Array.isArray(bindings)) return;\n for (const binding of bindings) {\n if (!binding || typeof binding !== 'object') continue;\n const entry = binding as { actionId?: unknown; key?: unknown };\n rememberKeyBinding(entry.actionId, entry.key);\n }\n }\n\n function notifyKeyAction(actionId: string): void {\n for (const callback of keyActionCallbacks.get(actionId) ?? []) callback();\n }\n\n function forwardKeyEvent(event: {\n key?: unknown;\n code?: unknown;\n ctrl?: unknown;\n alt?: unknown;\n shift?: unknown;\n meta?: unknown;\n ctrlKey?: unknown;\n altKey?: unknown;\n shiftKey?: unknown;\n metaKey?: unknown;\n } = {}): void {\n fire({\n type: 'keys.forward',\n key: typeof event.key === 'string' ? event.key : '',\n code: typeof event.code === 'string' ? event.code : '',\n ctrl: Boolean(event.ctrl ?? event.ctrlKey),\n alt: Boolean(event.alt ?? event.altKey),\n shift: Boolean(event.shift ?? event.shiftKey),\n meta: Boolean(event.meta ?? event.metaKey),\n });\n }\n\n function installKeysSmartForwarding(): void {\n if (keysSmartForwardingInstalled) return;\n keysSmartForwardingInstalled = true;\n\n listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'keys.bindings') {\n replaceKeyBindings(msg.bindings);\n }\n });\n\n const documentLike = target.document as {\n activeElement?: unknown;\n addEventListener?: (type: string, listener: (event: Event) => void) => void;\n } | undefined;\n const listenerTarget = typeof documentLike?.addEventListener === 'function' ? documentLike : target;\n if (typeof listenerTarget.addEventListener !== 'function') return;\n\n listenerTarget.addEventListener('keydown', (event: Event) => {\n const keyEvent = event as Event & {\n key?: string;\n code?: string;\n ctrlKey?: boolean;\n altKey?: boolean;\n shiftKey?: boolean;\n metaKey?: boolean;\n isComposing?: boolean;\n target?: unknown;\n preventDefault?: () => void;\n };\n if (keyEvent.isComposing) return;\n if (typeof keyEvent.key === 'string' && modifierKeys.has(keyEvent.key)) return;\n if (isTextEntryTarget(keyEvent.target ?? documentLike?.activeElement)) return;\n\n const combo = eventComboKey(keyEvent);\n const actionId = combo ? keyBindingActions.get(combo) : undefined;\n const isReserved = typeof keyEvent.key === 'string' && reservedKeyNames.has(keyEvent.key);\n if (actionId && !isReserved) {\n keyEvent.preventDefault?.();\n notifyKeyAction(actionId);\n return;\n }\n\n forwardKeyEvent(keyEvent);\n });\n }\n\n function makeKeys(): Record<string, unknown> {\n installKeysSmartForwarding();\n return {\n forward: forwardKeyEvent,\n registerAction: (action: unknown) => request(\n { type: 'keys.registerAction', action },\n 'keys.registerAction.result',\n resultOrError,\n ).then((result) => {\n const actionRecord = action && typeof action === 'object' ? action as { id?: unknown } : {};\n const resultRecord = result as { actionId?: unknown; binding?: unknown };\n rememberKeyBinding(\n typeof resultRecord.actionId === 'string' ? resultRecord.actionId : actionRecord.id,\n resultRecord.binding,\n );\n return result;\n }),\n unregisterAction: (actionId: string) => {\n removeKeyBindingsForAction(actionId);\n fire({ type: 'keys.unregisterAction', actionId });\n },\n onAction(actionId: string, callback: () => void) {\n let callbacks = keyActionCallbacks.get(actionId);\n if (!callbacks) {\n callbacks = new Set();\n keyActionCallbacks.set(actionId, callbacks);\n }\n callbacks.add(callback);\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'keys.action' && msg.actionId === actionId) callback();\n });\n return subscriptionHandle(() => {\n off();\n callbacks.delete(callback);\n if (callbacks.size === 0) keyActionCallbacks.delete(actionId);\n });\n },\n };\n }\n\n function makeMedia(): Record<string, unknown> {\n const on = (type: string, sessionId: string, callback: (msg: RuntimeMessage) => void) => {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === type && msg.sessionId === sessionId) callback(msg);\n });\n return subscriptionHandle(off);\n };\n return {\n createSession: (options: unknown) => request(\n { type: 'media.session.create', ...((options && typeof options === 'object') ? options as Record<string, unknown> : {}) },\n 'media.session.create.result',\n withoutEnvelope,\n { rejectOnError: false },\n ),\n updateSession: (sessionId: string, metadata: unknown) => fire({ type: 'media.session.update', sessionId, metadata }),\n destroySession: (sessionId: string) => fire({ type: 'media.session.destroy', sessionId }),\n reportState: (sessionId: string, state: unknown) => fire({ type: 'media.state', sessionId, ...((state && typeof state === 'object') ? state as Record<string, unknown> : {}) }),\n reportCapabilities: (sessionId: string, actions: unknown) => fire({ type: 'media.capabilities', sessionId, actions }),\n sendCommand: (sessionId: string, action: string, value?: unknown) => fire({ type: 'media.command', sessionId, action, ...(value === undefined ? {} : { value }) }),\n onCommand: (sessionId: string, callback: (action: unknown, value?: unknown) => void) => on('media.command', sessionId, (msg) => callback(msg.action, msg.value)),\n onState: (sessionId: string, callback: (state: Record<string, unknown>) => void) => on('media.state', sessionId, (msg) => callback({\n status: msg.status,\n position: msg.position,\n duration: msg.duration,\n volume: msg.volume,\n })),\n onCapabilities: (sessionId: string, callback: (actions: unknown) => void) => on('media.capabilities', sessionId, (msg) => callback(msg.actions)),\n onControls: (sessionId: string, callback: (controls: unknown) => void) => on('media.controls', sessionId, (msg) => callback(msg.controls)),\n };\n }\n\n function makeNotify(): Record<string, unknown> {\n const on = (type: string, callback: (msg: RuntimeMessage) => void) => {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === type) callback(msg);\n });\n return subscriptionHandle(off);\n };\n return {\n send: (notification: Record<string, unknown>) => request(\n { type: 'notify.send', ...notification },\n 'notify.send.result',\n (msg) => ({ notificationId: fieldOrThrow(msg, 'notificationId', 'notify.send.result missing notificationId') }),\n ),\n dismiss: (notificationId: string) => fire({ type: 'notify.dismiss', notificationId }),\n badge: (count: number) => fire({ type: 'notify.badge', count }),\n registerChannel: (channel: Record<string, unknown>) => fire({ type: 'notify.channel.register', ...channel }),\n requestPermission: (channel?: string) => request(\n { type: 'notify.permission.request', ...(channel ? { channel } : {}) },\n 'notify.permission.result',\n (msg) => ({ granted: msg.granted }),\n ),\n onAction: (callback: (notificationId: unknown, actionId: unknown) => void) => on('notify.action', (msg) => callback(msg.notificationId, msg.actionId)),\n onClicked: (callback: (notificationId: unknown) => void) => on('notify.clicked', (msg) => callback(msg.notificationId)),\n onDismissed: (callback: (notificationId: unknown, reason: unknown) => void) => on('notify.dismissed', (msg) => callback(msg.notificationId, msg.reason)),\n onControls: (callback: (controls: unknown) => void) => on('notify.controls', (msg) => callback(msg.controls)),\n };\n }\n\n function makeConfig(): Record<string, unknown> {\n let schema: unknown = null;\n return {\n registerSchema: (nextSchema: unknown, version?: number) => request(\n { type: 'config.registerSchema', schema: nextSchema, ...(version === undefined ? {} : { version }) },\n 'config.registerSchema.result',\n (msg) => {\n if (!msg.error) schema = nextSchema;\n return undefined;\n },\n ),\n get: () => request({ type: 'config.get' }, 'config.values', (msg) => msg.values ?? {}),\n subscribe(callback: (values: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'config.values') callback(msg.values ?? {});\n });\n fire({ type: 'config.subscribe' });\n return subscriptionHandle(() => {\n fire({ type: 'config.unsubscribe' });\n off();\n });\n },\n openSettings: (options?: unknown) => fire({ type: 'config.openSettings', ...((options && typeof options === 'object') ? options as Record<string, unknown> : {}) }),\n onSchemaError(callback: (error: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'config.schemaError') callback(msg);\n });\n return off;\n },\n get schema() {\n return schema;\n },\n };\n }\n\n function makeResource(): Record<string, unknown> {\n const objectUrls = new Set<string>();\n const bytes = (url: string, options?: { servers?: string[]; signal?: AbortSignal }) => request({\n type: 'resource.bytes',\n url,\n ...(Array.isArray(options?.servers) ? { servers: Array.from(options.servers) } : {}),\n }, 'resource.bytes.result', (msg) => msg.blob, {\n timeoutMs: null,\n signal: options?.signal,\n cancelOnAbort: true,\n });\n return {\n info: () => request({ type: 'resource.info' }, 'resource.info.result', (msg) => msg.info),\n bytes,\n bytesMany: (\n requests: Array<{ url: string; servers?: string[] }>,\n options?: { signal?: AbortSignal },\n ) => request({\n type: 'resource.bytesMany',\n requests: Array.from(requests || [], (entry) => ({\n url: entry.url,\n ...(Array.isArray(entry.servers) ? { servers: Array.from(entry.servers) } : {}),\n })),\n }, 'resource.bytesMany.result', (msg) => Array.isArray(msg.items) ? msg.items : [], {\n timeoutMs: null,\n signal: options?.signal,\n cancelOnAbort: true,\n }),\n bytesAsObjectURL(url: string) {\n let objectUrl = '';\n const handle = {\n get url() {\n return objectUrl;\n },\n revoke() {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrls.delete(objectUrl);\n objectUrl = '';\n }\n },\n };\n void bytes(url).then((blob) => {\n objectUrl = URL.createObjectURL(blob as Blob);\n objectUrls.add(objectUrl);\n });\n return handle;\n },\n hydrateResourceCache: () => undefined,\n revokeAllObjectURLs() {\n for (const url of objectUrls) URL.revokeObjectURL(url);\n objectUrls.clear();\n },\n };\n }\n\n function makeCvm(): Record<string, unknown> {\n const req = <T>(type: string, payload: Record<string, unknown>, map: (msg: RuntimeMessage) => T) => request(\n { type, ...payload },\n `${type}.result`,\n map,\n );\n const cvmRequest = (server: unknown, message: unknown, options?: Record<string, unknown>) => req(\n 'cvm.request',\n { server, message, ...(options === undefined ? {} : { options }) },\n (msg) => fieldOrThrow(msg, 'message', 'cvm.request.result missing message'),\n );\n const mcpCall = async (\n server: unknown,\n method: string,\n params?: Record<string, unknown>,\n options?: Record<string, unknown>,\n ) => {\n const reply = await cvmRequest(server, {\n jsonrpc: '2.0',\n id: id(),\n method,\n ...(params === undefined ? {} : { params }),\n }, options) as { result?: unknown; error?: { message?: string } | string };\n if (reply.error !== undefined) {\n const error = reply.error;\n throw new Error(typeof error === 'object' && error !== null && typeof error.message === 'string'\n ? `${method}: ${error.message}`\n : `${method} failed`);\n }\n return reply.result;\n };\n return {\n discover: (query?: unknown) => req('cvm.discover', query === undefined ? {} : { query }, (msg) => Array.isArray(msg.servers) ? msg.servers : []),\n request: cvmRequest,\n listTools: async (server: unknown, options?: Record<string, unknown>) => {\n const result = await mcpCall(server, 'tools/list', undefined, options) as { tools?: unknown[] } | undefined;\n return result?.tools ?? [];\n },\n callTool: (server: unknown, name: string, args?: unknown, options?: Record<string, unknown>) => mcpCall(\n server,\n 'tools/call',\n { name, ...(args === undefined ? {} : { arguments: args }) },\n options,\n ),\n listResources: async (server: unknown, options?: Record<string, unknown>) => {\n const result = await mcpCall(server, 'resources/list', undefined, options) as { resources?: unknown[] } | undefined;\n return result?.resources ?? [];\n },\n readResource: async (server: unknown, uri: string, options?: Record<string, unknown>) => {\n const result = await mcpCall(server, 'resources/read', { uri }, options) as { contents?: unknown[] } | undefined;\n const first = result?.contents?.[0];\n if (!first) throw new Error(`resources/read returned no contents for ${uri}`);\n return first;\n },\n close: (server: unknown) => req('cvm.close', { server }, (msg) => voidResult(msg, 'cvm close failed')),\n onEvent(callback: (server: unknown, message: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (\n typeof msg === 'object'\n && msg !== null\n && msg.type === 'cvm.event'\n && msg.server !== undefined\n && msg.message !== undefined\n ) {\n callback(msg.server, msg.message);\n }\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n function makeOutbox(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>, resultType = `${type}.result`) => request(\n { type, ...payload },\n resultType,\n resultOrError,\n { rejectOnError: false },\n );\n return {\n getEvent: (eventId: string, options?: Record<string, unknown>) => req('outbox.getEvent', { eventId, ...(options ? { options } : {}) }),\n query: (filters: unknown, options?: Record<string, unknown>) => req('outbox.query', { filters: Array.isArray(filters) ? filters : [filters], ...(options ? { options } : {}) }),\n subscribe(filters: unknown, options?: Record<string, unknown>) {\n const subId = id();\n const handlers = { event: new Set<(result: unknown) => void>(), closed: new Set<(reason?: unknown) => void>() };\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg !== 'object' || msg === null || msg.subId !== subId) return;\n if (msg.type === 'outbox.event') for (const handler of handlers.event) handler(msg.result);\n if (msg.type === 'outbox.closed') {\n for (const handler of handlers.closed) handler(msg.reason);\n off();\n }\n });\n fire({ type: 'outbox.subscribe', id: id(), subId, filters: Array.isArray(filters) ? filters : [filters], ...(options ? { options } : {}) });\n return {\n on(event: 'event' | 'closed', handler: (value?: unknown) => void) {\n handlers[event].add(handler);\n return { close: () => handlers[event].delete(handler) };\n },\n close() {\n fire({ type: 'outbox.close', id: id(), subId });\n off();\n handlers.event.clear();\n handlers.closed.clear();\n },\n };\n },\n publish: (event: unknown, options?: Record<string, unknown>) => req('outbox.publish', { event, ...(options ? { options } : {}) }),\n resolveRelays: (targetValue: unknown) => req('outbox.resolveRelays', { target: targetValue }).then((msg) => msg.plan ?? msg),\n };\n }\n\n function makeUpload(): Record<string, unknown> {\n return {\n info: () => request({ type: 'upload.info' }, 'upload.info.result', (msg) => fieldOrThrow(msg, 'info', 'upload info unavailable')),\n upload: (requestPayload: unknown) => request({ type: 'upload.upload', request: requestPayload }, 'upload.upload.result', (msg) => fieldOrThrow(msg, 'result', 'upload failed')),\n status: (uploadId: string) => request({ type: 'upload.status', uploadId }, 'upload.status.result', (msg) => fieldOrThrow(msg, 'status', 'upload status unavailable')),\n onStatus(callback: (status: unknown) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (typeof msg === 'object' && msg !== null && msg.type === 'upload.status.changed' && msg.status !== undefined) callback(msg.status);\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n // NAP-INTENT@25b29ee: the packaged 0.32 binding lacks delivery support.\n // Keep this receiver live before shell.ready, independently of listener timing.\n function makeIntentDelivery() {\n type Delivery = Readonly<{\n sender: string; archetype: string; action: string; convention: string; payload?: unknown;\n }>;\n type Handler = (delivery: Delivery) => void;\n const handlers = new Set<Handler>();\n const legacy = new Map<Handler, string>();\n const pending: Delivery[] = [];\n let draining = false;\n let warned = false;\n\n function drain(): void {\n if (draining) return;\n draining = true;\n try {\n while (pending.length > 0) {\n const index = handlers.size > 0 ? 0 : pending.findIndex((delivery) =>\n [...legacy.values()].includes(delivery.convention));\n if (index < 0) break;\n const [delivery] = pending.splice(index, 1);\n const canonical = handlers.size > 0;\n const recipients = canonical ? [...handlers] : [...legacy.entries()]\n .filter(([, topic]) => topic === delivery.convention).map(([handler]) => handler);\n if (!canonical && !warned) {\n warned = true;\n console.warn('[KEHTO_COMPAT_INTENT_INC] Intent delivered to a legacy INC listener. Migrate to window.napplet.intent.onDelivery. See docs/compatibility.md.');\n }\n for (const handler of recipients) {\n try { handler(delivery); } catch (error) { console.error('Intent delivery handler failed', error); }\n }\n }\n } finally {\n draining = false;\n }\n }\n\n listen((event) => {\n if (!isParentMessage(event)) return;\n const message = event.data as RuntimeMessage | null;\n if (!message || message.type !== 'intent.deliver') return;\n const value = message.delivery;\n if (!value || typeof value !== 'object' || Array.isArray(value)) return;\n const delivery = value as Record<string, unknown>;\n if (typeof delivery.sender !== 'string' || typeof delivery.archetype !== 'string'\n || typeof delivery.action !== 'string' || typeof delivery.convention !== 'string') return;\n pending.push(Object.freeze({\n sender: delivery.sender, archetype: delivery.archetype,\n action: delivery.action, convention: delivery.convention,\n ...(Object.prototype.hasOwnProperty.call(delivery, 'payload') ? { payload: delivery.payload } : {}),\n }));\n drain();\n });\n return {\n onDelivery(handler: Handler) {\n if (typeof handler !== 'function') throw new TypeError('Intent delivery handler must be a function');\n handlers.add(handler);\n drain();\n return subscriptionHandle(() => handlers.delete(handler));\n },\n onLegacy(topic: string, handler: Handler) {\n legacy.set(handler, topic);\n drain();\n return () => legacy.delete(handler);\n },\n };\n }\n\n function makeIntent(): Record<string, unknown> {\n const hasOwn = (value: Record<string, unknown>, key: string): boolean => (\n Object.prototype.hasOwnProperty.call(value, key)\n );\n let warnedLegacyObject = false;\n const warnLegacyObject = (): void => {\n if (warnedLegacyObject) return;\n warnedLegacyObject = true;\n console.warn('[KEHTO_COMPAT_INTENT_OBJECT_INVOKE] Object-form intent.invoke/open is deprecated; use intent.invoke(uri, options) or intent.open(uri, options). Warns once per napplet. See docs/compatibility.md.');\n };\n const normalizeLegacyRequest = (value: unknown): Record<string, unknown> => {\n warnLegacyObject();\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError('Intent request must be an object');\n }\n const supplied = value as Record<string, unknown>;\n if (hasOwn(supplied, 'sender')) {\n throw new TypeError('Intent callers cannot supply sender');\n }\n const allowed = ['archetype', 'action', 'convention', 'payload', 'handler', 'handlerHint', 'behavior'];\n if (Object.keys(supplied).some((field) => !allowed.includes(field))) {\n throw new TypeError('Intent request contains unsupported fields');\n }\n if (typeof supplied.archetype !== 'string' || supplied.archetype.length === 0) {\n throw new TypeError('Intent request requires an archetype');\n }\n const action = supplied.action === undefined ? 'open' : supplied.action;\n if (typeof action !== 'string' || action.length === 0) {\n throw new TypeError('Intent action must be a non-empty string');\n }\n const uri = supplied.convention === undefined\n ? `napplet:${supplied.archetype}/${action}`\n : supplied.convention;\n if (typeof uri !== 'string') throw new TypeError('Intent convention must be text');\n if (uri.includes('?') || uri.includes('#')) throw new TypeError('Legacy intent convention must be queryless');\n return normalizeIntentUri(uri, {\n ...(hasOwn(supplied, 'payload') ? { payload: supplied.payload } : {}),\n ...(hasOwn(supplied, 'handler') ? { handler: supplied.handler } : {}),\n ...(hasOwn(supplied, 'handlerHint') ? { handlerHint: supplied.handlerHint } : {}),\n ...(hasOwn(supplied, 'behavior') ? { behavior: supplied.behavior } : {}),\n });\n };\n const requestInvoke = (normalized: Record<string, unknown>) => request(\n {\n type: 'intent.invoke',\n request: normalized,\n },\n 'intent.invoke.result',\n (msg) => fieldOrThrow(msg, 'result', 'intent.invoke.result missing result'),\n );\n const invoke = (uri: unknown, options?: unknown) => {\n const normalized = typeof uri === 'string'\n ? normalizeIntentUri(uri, options)\n : normalizeLegacyRequest(uri);\n return requestInvoke(normalized);\n };\n const open = (uri: unknown, options?: unknown, legacyOptions?: unknown) => {\n if (typeof uri === 'string' && uri.startsWith('napplet:') && legacyOptions === undefined) {\n const normalized = normalizeIntentUri(uri, options);\n if (normalized.action !== 'open') throw new TypeError('intent.open requires a /open URI');\n return requestInvoke(normalized);\n }\n if (typeof uri !== 'string' || !uri) throw new TypeError('Intent archetype must be non-empty text');\n warnLegacyObject();\n if (legacyOptions !== undefined && (!legacyOptions || typeof legacyOptions !== 'object' || Array.isArray(legacyOptions))) {\n throw new TypeError('Intent options must be an object');\n }\n const legacy = legacyOptions as Record<string, unknown> | undefined;\n const convention = legacy?.convention === undefined ? `napplet:${uri}/open` : legacy.convention;\n if (typeof convention !== 'string' || convention.includes('?') || convention.includes('#')) {\n throw new TypeError('Legacy intent convention must be queryless');\n }\n const normalized = normalizeIntentUri(`napplet:${uri}/open`, {\n ...(options === undefined ? {} : { payload: options }),\n ...(legacy === undefined ? {} : Object.fromEntries(\n Object.entries(legacy).filter(([key]) => key !== 'convention'),\n )),\n });\n const legacyNormalized = convention === `napplet:${uri}/open`\n ? normalized\n : normalizeIntentUri(convention, {\n ...(options === undefined ? {} : { payload: options }),\n ...(legacy === undefined ? {} : Object.fromEntries(\n Object.entries(legacy).filter(([key]) => key !== 'convention'),\n )),\n });\n if (legacyNormalized.action !== 'open') throw new TypeError('intent.open requires a /open URI');\n return requestInvoke(legacyNormalized);\n };\n return {\n onDelivery: intentDelivery!.onDelivery,\n invoke,\n open,\n available: (archetype: string) => request(\n { type: 'intent.available', archetype },\n 'intent.available.result',\n (msg) => fieldOrThrow(msg, 'availability', 'intent.available.result missing availability'),\n ),\n handlers: () => request(\n { type: 'intent.handlers' },\n 'intent.handlers.result',\n (msg) => fieldOrThrow(msg, 'handlers', 'intent.handlers.result missing handlers'),\n ),\n onChanged: (callback: (availability: unknown) => void) => domainEventHandle(\n 'intent.changed',\n callback,\n (msg) => msg.availability,\n ),\n };\n }\n\n function makeWebrtc(): Record<string, unknown> {\n return {\n open: (requestPayload?: unknown) => request(\n { type: 'webrtc.open', request: requestPayload },\n 'webrtc.open.result',\n (msg) => ({ session: fieldOrThrow(msg, 'session', 'webrtc.open.result missing session') }),\n ),\n send: (sessionId: string, payload: unknown) => request(\n { type: 'webrtc.send', sessionId, payload },\n 'webrtc.send.result',\n (msg) => voidResult(msg, 'webrtc send failed'),\n ),\n close: (sessionId: string, reason?: string) => request(\n { type: 'webrtc.close', sessionId, ...(reason ? { reason } : {}) },\n 'webrtc.close.result',\n (msg) => voidResult(msg, 'webrtc close failed'),\n ),\n onEvent: (callback: (event: unknown) => void) => domainEventHandle('webrtc.event', callback),\n };\n }\n\n function makeBle(): Record<string, unknown> {\n const req = (action: string, payload: Record<string, unknown>, map: (msg: RuntimeMessage) => unknown) => request(\n { type: `ble.${action}`, ...payload },\n `ble.${action}.result`,\n map,\n );\n return {\n open: (requestPayload?: unknown) => req('open', { request: requestPayload }, (msg) => ({ session: fieldOrThrow(msg, 'session', 'ble.open.result missing session') })),\n services: (sessionId: string) => req('services', { sessionId }, (msg) => fieldOrThrow(msg, 'services', 'ble.services.result missing services')),\n read: (sessionId: string, targetValue: unknown) => req('read', { sessionId, target: targetValue }, (msg) => fieldOrThrow(msg, 'data', 'ble.read.result missing data')),\n write: (sessionId: string, targetValue: unknown, data: unknown, options?: Record<string, unknown>) => req(\n 'write',\n { sessionId, target: targetValue, data, ...(options ? { options } : {}) },\n (msg) => voidResult(msg, 'ble write failed'),\n ),\n subscribe: (sessionId: string, targetValue: unknown) => req('subscribe', { sessionId, target: targetValue }, (msg) => voidResult(msg, 'ble subscribe failed')),\n unsubscribe: (sessionId: string, targetValue: unknown) => req('unsubscribe', { sessionId, target: targetValue }, (msg) => voidResult(msg, 'ble unsubscribe failed')),\n close: (sessionId: string, reason?: string) => req('close', { sessionId, ...(reason ? { reason } : {}) }, (msg) => voidResult(msg, 'ble close failed')),\n onEvent: (callback: (event: unknown) => void) => domainEventHandle('ble.event', callback),\n };\n }\n\n function makeSerial(): Record<string, unknown> {\n return {\n open: (requestPayload?: unknown) => request(\n { type: 'serial.open', request: requestPayload },\n 'serial.open.result',\n (msg) => ({ session: fieldOrThrow(msg, 'session', 'serial.open.result missing session') }),\n ),\n write: (sessionId: string, data: Uint8Array | number[]) => request(\n { type: 'serial.write', sessionId, data: Array.from(data) },\n 'serial.write.result',\n (msg) => voidResult(msg, 'serial write failed'),\n ),\n close: (sessionId: string, reason?: string) => request(\n { type: 'serial.close', sessionId, ...(reason === undefined ? {} : { reason }) },\n 'serial.close.result',\n (msg) => voidResult(msg, 'serial close failed'),\n ),\n onEvent: (callback: (event: unknown) => void) => domainEventHandle('serial.event', callback),\n };\n }\n\n function makeLink(): Record<string, unknown> {\n return {\n open: (url: string, options?: Record<string, unknown>) => request(\n { type: 'link.open', url, ...(options ? { options } : {}) },\n 'link.open.result',\n resultOrError,\n { rejectOnError: false },\n ),\n };\n }\n\n function makeCount(): Record<string, unknown> {\n return {\n query: (filters: unknown, options?: Record<string, unknown>) => request(\n { type: 'count.query', filters: Array.isArray(filters) ? filters : [filters], ...(options ? { options } : {}) },\n 'count.query.result',\n resultOrError,\n { rejectOnError: false },\n ),\n };\n }\n\n function makeLists(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>) => request({ type, ...payload }, `${type}.result`, resultOrError, { rejectOnError: false });\n return {\n supported: () => req('lists.supported', {}),\n add: (list: unknown, items: unknown, options?: unknown) => req('lists.add', { list, items, ...(options ? { options } : {}) }),\n remove: (list: unknown, items: unknown, options?: unknown) => req('lists.remove', { list, items, ...(options ? { options } : {}) }),\n };\n }\n\n function makeCommon(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>) => request({ type, ...payload }, `${type}.result`, withoutEnvelope, { rejectOnError: false });\n return {\n encodeNip19: (input: unknown) => req('common.encodeNip19', { input }),\n decodeNip19: (value: string) => req('common.decodeNip19', { value }),\n getProfile: (targetValue: unknown) => req('common.getProfile', { target: targetValue }),\n follows: () => req('common.follows', {}),\n follow: (...pubkeys: string[]) => req('common.follow', { pubkeys }),\n unfollow: (...pubkeys: string[]) => req('common.unfollow', { pubkeys }),\n react: (targetEventId: string, reaction?: string, customEmojiHref?: string) => req('common.react', {\n targetEventId,\n reaction,\n ...(customEmojiHref === undefined ? {} : { customEmojiHref }),\n }),\n report: (targetValue: unknown, reason?: string, text?: string) => req('common.report', {\n target: targetValue,\n reason,\n text,\n }),\n };\n }\n\n function makeDm(): Record<string, unknown> {\n const req = (type: string, payload: Record<string, unknown>) => request({ type, ...payload }, `${type}.result`, withoutEnvelope, { rejectOnError: false });\n return {\n status: () => req('dm.status', {}),\n conversations: (query?: Record<string, unknown>) => req('dm.conversations', query ?? {}),\n messages: (query: Record<string, unknown>) => req('dm.messages', query ?? {}),\n send: (requestPayload: Record<string, unknown>) => req('dm.send', requestPayload ?? {}),\n subscribe: (requestPayload?: Record<string, unknown>) => req('dm.subscribe', requestPayload ?? {}),\n unsubscribe: (subscriptionId: string) => req('dm.unsubscribe', { subscriptionId }),\n onMessage(callback: (message: unknown, subscriptionId: string) => void) {\n const off = listen((event) => {\n if (!isParentMessage(event)) return;\n const msg = event.data as RuntimeMessage;\n if (\n typeof msg === 'object'\n && msg !== null\n && msg.type === 'dm.message'\n && typeof msg.subscriptionId === 'string'\n ) {\n callback(msg.message, msg.subscriptionId);\n }\n });\n return subscriptionHandle(off);\n },\n };\n }\n\n function makeFs(): Record<string, unknown> {\n const withOptions = (payload: Record<string, unknown>, options: unknown) => {\n if (options !== undefined) payload.options = options;\n return payload;\n };\n const req = (\n action: string,\n payload: Record<string, unknown>,\n map: (msg: RuntimeMessage) => unknown,\n ) => request({ type: `fs.${action}`, ...payload }, `fs.${action}.result`, map);\n return {\n info: () => req('info', {}, (msg) => fieldOrThrow(msg, 'info', 'fs.info.result missing info')),\n pickFile: (options?: unknown) => req('pickFile', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickFile.result missing result')),\n pickFiles: (options?: unknown) => req('pickFiles', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickFiles.result missing result')),\n pickDirectory: (options?: unknown) => req('pickDirectory', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickDirectory.result missing result')),\n pickSaveFile: (options?: unknown) => req('pickSaveFile', withOptions({}, options), (msg) => fieldOrThrow(msg, 'result', 'fs.pickSaveFile.result missing result')),\n stat: (path: string) => req('stat', { path }, (msg) => fieldOrThrow(msg, 'metadata', 'fs.stat.result missing metadata')),\n list: (path: string) => req('list', { path }, (msg) => fieldOrThrow(msg, 'entries', 'fs.list.result missing entries')),\n read: (path: string, options?: unknown) => req('read', withOptions({ path }, options), (msg) => fieldOrThrow(msg, 'result', 'fs.read.result missing result')),\n write: (path: string, data: string, options?: unknown) => req('write', withOptions({ path, data }, options), (msg) => fieldOrThrow(msg, 'result', 'fs.write.result missing result')),\n mkdir: (path: string, options?: unknown) => req('mkdir', withOptions({ path }, options), (msg) => voidResult(msg, 'fs mkdir failed')),\n remove: (path: string, recursive?: boolean) => req('remove', { path, ...(recursive === undefined ? {} : { recursive }) }, (msg) => voidResult(msg, 'fs remove failed')),\n move: (fromPath: string, toPath: string) => req('move', { fromPath, toPath }, (msg) => voidResult(msg, 'fs move failed')),\n watch: (path: string, options?: unknown) => req('watch', withOptions({ path }, options), (msg) => fieldOrThrow(msg, 'watchId', 'fs.watch.result missing watchId')),\n unwatch: (watchId: string) => req('unwatch', { watchId }, (msg) => voidResult(msg, 'fs unwatch failed')),\n onChanged: (callback: (change: unknown) => void) => domainEventHandle('fs.changed', callback, (msg) => msg.change),\n };\n }\n\n const intentDelivery = allowed.has('intent') ? makeIntentDelivery() : undefined;\n const shell = makeShell();\n let inc: Record<string, unknown> | undefined;\n let identity: Record<string, unknown> | undefined;\n let theme: Record<string, unknown> | undefined;\n let intent: Record<string, unknown> | undefined;\n\n function makeProtectedInc(existing: unknown): Record<string, unknown> {\n const extensions = existing && typeof existing === 'object'\n ? existing as Record<string, unknown>\n : {};\n inc ??= makeInc();\n return { ...extensions, ...inc };\n }\n\n function makeProtectedIdentity(): Record<string, unknown> {\n identity ??= makeIdentity();\n return identity;\n }\n\n function makeProtectedTheme(): Record<string, unknown> {\n theme ??= Object.freeze(makeTheme());\n return theme;\n }\n\n function makeProtectedIntent(): Record<string, unknown> {\n intent ??= Object.freeze(makeIntent());\n return intent;\n }\n\n function isProtectedDomain(domain: string): boolean {\n return domain === 'shell'\n || domain === 'inc'\n || domain === 'identity'\n || domain === 'theme'\n || domain === 'intent';\n }\n\n function makeDomain(domain: string, existing: unknown): unknown {\n if (domain === 'shell') return shell;\n if (domain === 'inc') return makeProtectedInc(existing);\n if (domain === 'identity') return makeProtectedIdentity();\n if (domain === 'theme') return makeProtectedTheme();\n if (domain === 'intent') return makeProtectedIntent();\n if (existing && typeof existing === 'object' && Object.keys(existing).length > 0) return existing;\n switch (domain) {\n case 'relay': return makeRelay();\n case 'storage': return makeStorage();\n case 'keys': return makeKeys();\n case 'media': return makeMedia();\n case 'notify': return makeNotify();\n case 'config': return makeConfig();\n case 'resource': return makeResource();\n case 'cvm': return makeCvm();\n case 'outbox': return makeOutbox();\n case 'upload': return makeUpload();\n case 'webrtc': return makeWebrtc();\n case 'ble': return makeBle();\n case 'link': return makeLink();\n case 'count': return makeCount();\n case 'lists': return makeLists();\n case 'common': return makeCommon();\n case 'serial': return makeSerial();\n case 'dm': return makeDm();\n case 'fs': return makeFs();\n default: return {};\n }\n }\n\n function guardNappletNamespace(namespace: Record<string, unknown>): Record<string, unknown> {\n return new Proxy(namespace, {\n set(obj, prop, value) {\n if (typeof prop !== 'string' || !allowed.has(prop)) return true;\n obj[prop] = makeDomain(prop, value);\n return true;\n },\n defineProperty(obj, prop, descriptor) {\n if (typeof prop !== 'string' || !allowed.has(prop)) return true;\n if (isProtectedDomain(prop)) {\n return Reflect.defineProperty(obj, prop, {\n value: makeDomain(prop, descriptor.value),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return Reflect.defineProperty(obj, prop, {\n ...descriptor,\n value: makeDomain(prop, descriptor.value),\n });\n },\n deleteProperty(obj, prop) {\n if (typeof prop === 'string' && allowed.has(prop) && isProtectedDomain(prop)) return true;\n return Reflect.deleteProperty(obj, prop);\n },\n });\n }\n\n function buildNappletNamespace(value: unknown): Record<string, unknown> {\n const candidate = typeof value === 'object' && value !== null\n ? value as Record<string, unknown>\n : {};\n const next: Record<string, unknown> = {};\n for (const domain of domains) {\n if (!allowed.has(domain)) continue;\n Object.defineProperty(next, domain, {\n value: makeDomain(\n domain,\n Object.prototype.hasOwnProperty.call(candidate, domain) ? candidate[domain] : undefined,\n ),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return guardNappletNamespace(next);\n }\n\n let root = buildNappletNamespace(target.napplet);\n Object.defineProperty(target, 'napplet', {\n get() {\n return root;\n },\n set(value) {\n root = buildNappletNamespace(value);\n },\n enumerable: false,\n configurable: false,\n });\n}\n","/** Insert trusted head content before any authored resource can be parsed. */\nexport function insertNappletHead(html: string, content: string): string {\n // Only consume a harmless prolog and bare container tags. Never search inside\n // authored comments, attributes, templates or scripts for a head/CSP marker.\n // For other HTML, an explicit head precedes it; the HTML parser merges later\n // html/body attributes and ignores duplicate head openings.\n const opening = /^([\\t\\n\\f\\r ]*(?:<!doctype[\\t\\n\\f\\r ]+html[\\t\\n\\f\\r ]*>[\\t\\n\\f\\r ]*)?(?:<html>[\\t\\n\\f\\r ]*)?)(<head>)?/i.exec(html)!;\n const prefix = opening[0];\n const insertion = opening[2] ? content : `<head>${content}</head>`;\n return `${prefix}${insertion}${html.slice(prefix.length)}`;\n}\n","import { insertNappletHead } from './napplet-head.js';\n\n/** Source-list directives supported by the shell's meta-delivered CSP. */\nexport type NappletCspDirective =\n | 'default-src' | 'script-src' | 'script-src-elem' | 'script-src-attr'\n | 'style-src' | 'style-src-elem' | 'style-src-attr' | 'img-src' | 'font-src'\n | 'connect-src' | 'worker-src' | 'child-src' | 'frame-src' | 'media-src'\n | 'object-src' | 'manifest-src' | 'base-uri' | 'form-action';\n\n/** Host replacements for individual CSP source lists; omitted directives retain defaults. */\nexport type NappletCspDirectives = Readonly<Partial<Record<NappletCspDirective, readonly string[]>>>;\n\n/** Host policy for a verified napplet's CSP, separate from its signed manifest. */\nexport interface NappletCspOptions {\n /** Explicit HTTP(S)/WS(S) origins granted direct connections; defaults to none. */\n readonly connectOrigins?: readonly string[];\n /** Source-list replacements. connect-src may only narrow the explicit grants. */\n readonly directives?: NappletCspDirectives;\n}\n\n// NIP-5D 24711d9c47bbdd07908bf1d52bf677d9cbc530f0: the example is a\n// default, not an immutable policy. Kehto enforces its CSP placement and\n// exact-connect-origin SHOULDs, and rejects broad JavaScript string evaluation.\nconst DEFAULT_DIRECTIVES: Readonly<Record<string, readonly string[]>> = {\n 'default-src': [\"'none'\"],\n 'script-src': [\"'unsafe-inline'\", \"'wasm-unsafe-eval'\"],\n 'style-src': [\"'unsafe-inline'\"],\n 'img-src': ['data:', 'blob:'],\n 'font-src': ['data:'],\n 'connect-src': [\"'none'\"],\n 'worker-src': [\"'none'\"],\n 'child-src': [\"'none'\"],\n 'frame-src': [\"'none'\"],\n 'media-src': [\"'none'\"],\n 'object-src': [\"'none'\"],\n 'manifest-src': [\"'none'\"],\n 'base-uri': [\"'none'\"],\n 'form-action': [\"'none'\"],\n};\n\nconst OPTIONAL_DIRECTIVES = new Set([\n 'script-src-elem', 'script-src-attr', 'style-src-elem', 'style-src-attr',\n]);\nconst KEYWORDS = new Set([\n \"'none'\", \"'self'\", \"'unsafe-inline'\", \"'wasm-unsafe-eval'\",\n \"'unsafe-hashes'\", \"'strict-dynamic'\", \"'report-sample'\",\n]);\n\nfunction connectionOrigin(source: string): string {\n let url: URL;\n try {\n url = new URL(source);\n } catch {\n throw new Error(`CSP connection grant must be an exact HTTP(S)/WS(S) origin: ${source}`);\n }\n if (!/^(https?|wss?):$/.test(url.protocol) || url.username || url.password\n || url.pathname !== '/' && url.pathname !== '' || url.search || url.hash\n || /[\\s*\\\\;,\"<>'`]/.test(source + url.origin) || !source.startsWith(`${url.protocol}//`)) {\n throw new Error(`CSP connection grant must be an exact HTTP(S)/WS(S) origin: ${source}`);\n }\n return url.origin;\n}\n\nfunction validateSources(directive: string, sources: readonly string[]): string[] {\n if (!Array.isArray(sources) || sources.length === 0) {\n throw new Error(`CSP ${directive} needs a nonempty source list; use 'none' to deny it`);\n }\n const result = [...new Set(sources)];\n for (const source of result) {\n if (typeof source !== 'string' || !/^[\\x21-\\x7e]+$/.test(source)\n || /[;,\"<>\\\\]/.test(source)) {\n throw new Error(`Invalid CSP source in ${directive}`);\n }\n if (source.toLowerCase() === \"'unsafe-eval'\") {\n throw new Error(\"NIP-5D CSP forbids 'unsafe-eval'; use 'wasm-unsafe-eval' for WebAssembly\");\n }\n if (source.includes(\"'\") && !KEYWORDS.has(source)\n && !/^'(?:nonce-|sha(?:256|384|512)-)[A-Za-z0-9+/_-]+=*'$/.test(source)) {\n throw new Error(`Invalid CSP keyword in ${directive}: ${source}`);\n }\n }\n if (result.includes(\"'none'\") && result.length !== 1) {\n throw new Error(`CSP ${directive} cannot combine 'none' with other sources`);\n }\n return result;\n}\n\nfunction requireBootstrapScripts(directive: string, sources: readonly string[]): void {\n if (!sources.includes(\"'unsafe-inline'\") || sources.some(\n (source) => /^'(?:nonce-|sha(?:256|384|512)-|strict-dynamic')/.test(source),\n )) {\n throw new Error(`CSP ${directive} must allow the shell's inline namespace bootstrap`);\n }\n}\n\n/**\n * Build the default NIP-5D CSP with validated host source-list replacements.\n * Meta-unsupported directives must be configured on the host HTTP response.\n *\n * @param options - Explicit connection grants and directive replacements.\n * @returns A serialized policy. Invalid or conflicting overrides throw.\n * @example\n * ```ts\n * const policy = buildNappletCsp({\n * connectOrigins: ['https://api.example'],\n * directives: { 'media-src': ['blob:'] },\n * });\n * ```\n */\nexport function buildNappletCsp(options: NappletCspOptions = {}): string {\n const grants = [...new Set((options.connectOrigins ?? []).map(connectionOrigin))].sort();\n const policy: Record<string, readonly string[]> = {\n ...DEFAULT_DIRECTIVES,\n 'connect-src': grants.length ? grants : [\"'none'\"],\n };\n for (const [directive, sources] of Object.entries(options.directives ?? {})) {\n if (!Object.hasOwn(DEFAULT_DIRECTIVES, directive) && !OPTIONAL_DIRECTIVES.has(directive)) {\n throw new Error(`Unsupported meta CSP directive: ${directive}`);\n }\n policy[directive] = validateSources(directive, sources);\n }\n const connect = policy['connect-src'];\n if (!(connect.length === 1 && connect[0] === \"'none'\")) {\n policy['connect-src'] = [...new Set(connect.map((source) => {\n const origin = connectionOrigin(source);\n if (!grants.includes(origin)) throw new Error(`CSP connection origin was not granted: ${origin}`);\n return origin;\n }))].sort();\n }\n requireBootstrapScripts('script-src', policy['script-src']);\n if (policy['script-src-elem']) requireBootstrapScripts('script-src-elem', policy['script-src-elem']);\n return Object.entries(policy).map(([name, sources]) => `${name} ${sources.join(' ')}`).join('; ');\n}\n\n/**\n * Render the shell's validated CSP meta element.\n *\n * @param options - Explicit connection grants and directive replacements.\n * @returns An attribute-escaped CSP meta element for the first position in head.\n * @example\n * ```ts\n * const meta = renderNappletCspMeta({ directives: { 'img-src': ['data:'] } });\n * ```\n */\nexport function renderNappletCspMeta(options: NappletCspOptions = {}): string {\n const policy = buildNappletCsp(options).replace(/&/g, '&').replace(/\"/g, '"');\n return `<meta http-equiv=\"Content-Security-Policy\" content=\"${policy}\">`;\n}\n\n/**\n * Insert CSP before authored content. The caller must verify the artifact first.\n * Existing authored CSP remains in place and can only further restrict execution.\n *\n * @param html - Already-verified artifact HTML; never use the result for its hash.\n * @param options - Explicit connection grants and directive replacements.\n * @returns A srcdoc copy with the CSP first in head.\n * @example\n * ```ts\n * const protectedHtml = injectNappletCsp(verifiedHtml);\n * ```\n */\nexport function injectNappletCsp(html: string, options: NappletCspOptions = {}): string {\n return insertNappletHead(html, renderNappletCspMeta(options));\n}\n","import { renderNappletCspMeta, type NappletCspOptions } from './napplet-csp.js';\nimport { insertNappletHead } from './napplet-head.js';\nimport { renderNappletNamespacePrelude, type NappletNamespacePreludeOptions } from './napplet-namespace.js';\n\n/** Shell bootstrap availability and host CSP for a verified napplet document. */\nexport interface NappletSrcdocOptions extends NappletNamespacePreludeOptions {\n /** Validated host policy changes. Omission uses the NIP-5D baseline. */\n readonly csp?: NappletCspOptions;\n}\n\n/**\n * Prepare verified artifact HTML with CSP first, then the mandatory namespace.\n * There is no CSP opt-out. Resolve and verify the artifact before calling this;\n * bind its identity to the sandboxed iframe before assigning the returned srcdoc.\n * Keep the original verified bytes for hashing and caching.\n *\n * @param html - Already-verified napplet artifact HTML.\n * @param options - Exposed domains and validated host CSP changes.\n * @returns Srcdoc HTML with policy and bootstrap preceding authored content.\n * @example\n * ```ts\n * iframe.sandbox.value = 'allow-scripts';\n * iframe.srcdoc = prepareNappletSrcdoc(verifiedHtml, {\n * domains: ['shell', 'theme'],\n * csp: { directives: { 'media-src': ['blob:'] } },\n * });\n * ```\n */\nexport function prepareNappletSrcdoc(html: string, options: NappletSrcdocOptions): string {\n const meta = renderNappletCspMeta(options.csp);\n return insertNappletHead(html, meta + renderNappletNamespacePrelude(options));\n}\n","\n// Factory function — main entry point\nexport { createShellBridge } from './shell-bridge.js';\nexport type { ShellBridge } from './shell-bridge.js';\nexport {\n injectNappletNamespacePrelude,\n renderNappletNamespacePrelude,\n} from './napplet-namespace.js';\nexport type { NappletNamespacePreludeOptions } from './napplet-namespace.js';\nexport { normalizeIntentUri } from './intent-uri.js';\nexport type { NormalizedIntentUri } from './intent-uri.js';\nexport { buildNappletCsp, injectNappletCsp, renderNappletCspMeta } from './napplet-csp.js';\nexport type { NappletCspDirective, NappletCspDirectives, NappletCspOptions } from './napplet-csp.js';\nexport { prepareNappletSrcdoc } from './napplet-srcdoc.js';\nexport type { NappletSrcdocOptions } from './napplet-srcdoc.js';\n\n// Hooks adapter — for advanced integrators who need to customize the adapter\nexport { adaptHooks } from './hooks-adapter.js';\nexport type { BrowserDeps } from './hooks-adapter.js';\n\n// Protocol types (re-exported from @napplet/core + @kehto/runtime).\n// Phase 24 DRIFT-01: former @napplet/core compatibility shim deleted; legacy\n// NIP-01 constants no longer re-exported. Shell consumers import Capability +\n// ALL_CAPABILITIES from @kehto/runtime (sourced from @kehto/acl/capabilities).\nexport type { NostrEvent, NostrFilter, NappletMessage } from '@napplet/core';\nexport type { Capability } from '@kehto/runtime';\nexport { ALL_CAPABILITIES } from '@kehto/runtime';\n\n// Types for host app integration (shell-specific)\nexport type {\n ShellAdapter,\n ShellCapabilities,\n ShellEnvironment,\n RelayPoolHooks,\n RelayPoolLike,\n RelayConfigHooks,\n WindowManagerHooks,\n AuthHooks,\n ConfigHooks,\n HotkeyHooks,\n WorkerRelayHooks,\n WorkerRelayLike,\n CryptoHooks,\n DmHooks,\n UploadHooks,\n UploadBackendLike,\n IntentHooks,\n LinkHooks,\n CommonHooks,\n ListsHooks,\n SerialHooks,\n BleHooks,\n WebrtcHooks,\n CapabilityHooks,\n SessionEntry,\n NappKeyEntry, // @deprecated — use SessionEntry\n AclEntry,\n AclCheckEvent,\n UnroutedMessageInfo,\n ServiceDescriptor,\n ServiceHandler,\n ServiceRegistry,\n} from './types.js';\n\n// Shell initialization — capability construction for shell.ready / shell.init handshake\nexport { buildShellCapabilities, resolveShellEnvironment } from './shell-init.js';\n\nexport { sessionRegistry, nappKeyRegistry } from './session-registry.js';\nexport type { PendingUpdate, SessionRegistry } from './session-registry.js';\n\n// Standalone utilities (usable without full shell)\nexport { originRegistry } from './origin-registry.js';\nexport type { OriginIdentity, OriginRegistry } from './origin-registry.js';\nexport { audioManager } from './audio-manager.js';\nexport type { AudioManager, AudioSource } from './audio-manager.js';\nexport { manifestCache } from './manifest-cache.js';\nexport type { ManifestCache, ManifestCacheEntry } from './manifest-cache.js';\nexport type { AclStore } from './acl-store.js';\n\n// Enforcement gate (re-exported from @kehto/runtime for backwards compatibility)\nexport { createEnforceGate, createNapEnforceGate, formatDenialReason } from '@kehto/runtime';\nexport type { EnforceResult, EnforceConfig, NapEnforceConfig, IdentityResolver, AclChecker, NapMessage } from '@kehto/runtime';\n// ConsentRequest canonical definition re-exported from @kehto/runtime\nexport type { ConsentRequest } from '@kehto/runtime';\n\n// Topic constants for shell command routing\nexport { TOPICS } from './topics.js';\nexport type { TopicKey, TopicValue } from './topics.js';\n\nexport { createIdentityProxy } from './identity-proxy.js';\nexport type { IdentityProxy, IdentityProxyDeps, ProxyOriginRegistry } from './identity-proxy.js';\nexport { createThemeProxy } from './theme-proxy.js';\nexport type { ThemeProxy, ThemeProxyDeps } from './theme-proxy.js';\nexport { createKeysProxy } from './keys-proxy.js';\nexport type { KeysProxy, KeysProxyDeps } from './keys-proxy.js';\nexport { createMediaProxy } from './media-proxy.js';\nexport type { MediaProxy, MediaProxyDeps } from './media-proxy.js';\nexport { createNotifyProxy } from './notify-proxy.js';\nexport type { NotifyProxy, NotifyProxyDeps } from './notify-proxy.js';\n\nexport type {\n ResourceBytesRequest,\n ResourceInfo,\n ResourceInfoError,\n ResourceInfoRequest,\n ResourceInfoResult,\n ResourceBytesManyRequest,\n ResourceBytesManyItem,\n ResourceCancelRequest,\n ResourceBytesResult,\n ResourceBytesManyResult,\n ResourceBytesError,\n ResourceBytesManyError,\n ResourceErrorCode,\n ResourceRequestId,\n ResourceInbound,\n ResourceOutbound,\n} from './types/internal-resource.js';\n","/**\n * topics.ts — Re-exports topic constants from @napplet/core.\n *\n * Shell previously owned these constants. They now live in @napplet/core\n * so all packages share a single source of truth.\n */\nexport { TOPICS } from '@napplet/core';\nexport type { TopicKey, TopicValue } from '@napplet/core';\n","/**\n * identity-proxy.ts — Shell-side per-domain proxy for identity.* envelopes.\n *\n * Establishes the canonical proxy shape for @kehto/shell (Plan 12-11): each\n * per-domain proxy exposes a `dispatch` method that delegates napplet→shell\n * requests to the runtime.\n *\n * By default, `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime already owns identity.* dispatch per Plan\n * 12-03 (see @kehto/services identity-service). This module exists as an\n * optional composition point for host apps that want to intercept or\n * augment identity dispatch (e.g. custom logging, sandboxed rewrites, test\n * doubles).\n *\n * Identity changes are deliberately not emitted through this proxy. Hosts\n * must use `ShellBridge.publishIdentityChanged()`, which enforces the live\n * session, granted-domain, and current recipient-capability checks.\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\n\n/**\n * Minimal origin-registry contract used by per-domain proxies.\n *\n * Accepts the `@kehto/shell` singleton `originRegistry` as well as any test\n * double with a matching `getIframeWindow` method.\n */\nexport interface ProxyOriginRegistry {\n /** Resolve a registered napplet windowId to its iframe Window, or null. */\n getIframeWindow(windowId: string): Window | null;\n}\n\n/**\n * Dependencies for `createIdentityProxy`.\n *\n * @example\n * ```ts\n * const proxy = createIdentityProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface IdentityProxyDeps {\n /** The runtime engine that owns identity.* dispatch (Plan 12-03). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `identity.*` envelopes.\n *\n * `dispatch` routes napplet→shell requests into the runtime. The deprecated\n * `emit` member remains only as a fail-closed compatibility trap.\n */\nexport interface IdentityProxy {\n /**\n * Route a napplet-originated identity.* envelope into the runtime.\n *\n * Delegation only — the runtime already owns identity.* dispatch after\n * Plan 12-03. Override by wrapping or replacing this method.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Direct identity delivery is prohibited.\n *\n * @deprecated Use `ShellBridge.publishIdentityChanged()` so delivery is\n * filtered by live session, granted domain, and current ACL.\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical identity-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns An {@link IdentityProxy} ready to route identity.* envelopes\n * @example\n * ```ts\n * import { createIdentityProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const identityProxy = createIdentityProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Optional composition: intercept napplet->shell identity requests\n * const originalDispatch = identityProxy.dispatch;\n * identityProxy.dispatch = (windowId, envelope) => {\n * console.log('identity dispatch', windowId, envelope.type);\n * originalDispatch(windowId, envelope);\n * };\n * ```\n */\nexport function createIdentityProxy(deps: IdentityProxyDeps): IdentityProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(_windowId: string, _envelope: NappletMessage): void {\n throw new Error(\n 'Direct identity proxy emit is prohibited; use ShellBridge.publishIdentityChanged()',\n );\n },\n };\n}\n","/**\n * theme-proxy.ts — Shell-side per-domain proxy for theme.* envelopes.\n *\n * Establishes the shell-side shape that Phase 13 composes into. Phase 13 is\n * expected to add `theme-service.ts` (runtime) + the shell-side `theme.set`\n * API that emits `theme.changed` push envelopes to registered napplets;\n * this proxy is the canonical seam those pieces plug into.\n *\n * `dispatch(windowId, envelope)` routes napplet→shell `theme.get` into the\n * runtime. Theme changes must use `ShellBridge.publishTheme()` so the host\n * projection enforces live-session, granted-domain, and current-ACL checks.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns theme.* dispatch. This module is an\n * optional composition point for host apps or Phase 13 wiring.\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createThemeProxy`.\n *\n * @example\n * ```ts\n * const proxy = createThemeProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface ThemeProxyDeps {\n /** The runtime engine that will own theme.* dispatch (Phase 13). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `theme.*` envelopes.\n *\n * `dispatch` routes napplet→shell requests into the runtime. The deprecated\n * `emit` member remains only as a fail-closed compatibility trap.\n */\nexport interface ThemeProxy {\n /**\n * Route a napplet-originated theme.* envelope (e.g. `theme.get`) into\n * the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Direct theme delivery is prohibited.\n *\n * @deprecated Use `ShellBridge.publishTheme()` so delivery is filtered by\n * live session, granted domain, and current ACL.\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical theme-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link ThemeProxy} ready to route theme.* envelopes\n * @example\n * ```ts\n * import { createThemeProxy, originRegistry } from '@kehto/shell';\n *\n * const themeProxy = createThemeProxy({\n * runtime,\n * originRegistry,\n * });\n * themeProxy.dispatch(windowId, { type: 'theme.get', id: requestId });\n * ```\n */\nexport function createThemeProxy(deps: ThemeProxyDeps): ThemeProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(_windowId: string, _envelope: NappletMessage): void {\n throw new Error(\n 'Direct theme proxy emit is prohibited; use ShellBridge.publishTheme()',\n );\n },\n };\n}\n","/**\n * keys-proxy.ts — Shell-side per-domain proxy for keys.* envelopes.\n *\n * The runtime already dispatches napplet-originated `keys.*` (forward,\n * registerAction, unregisterAction) to the keys service. This proxy is the\n * shell-side composition point for host apps that want to observe requests or\n * inject shell-originated keys envelopes such as `keys.action` and\n * `keys.bindings`.\n *\n * Shape mirrors identity-proxy (Plan 12-11):\n *\n * - `dispatch(windowId, envelope)` routes napplet→shell keys requests\n * into the runtime.\n * - `emit(windowId, envelope)` posts shell→napplet pushes (`keys.action`,\n * `keys.bindings`, `keys.registerAction.result`) through the origin\n * registry.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns keys.* dispatch. This module is an\n * optional composition point for host apps (e.g. global hotkey UIs).\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createKeysProxy`.\n *\n * @example\n * ```ts\n * const proxy = createKeysProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface KeysProxyDeps {\n /** The runtime engine that owns keys.* dispatch (Plan 12-05). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `keys.*` envelopes.\n *\n * Shape: `dispatch` routes napplet→shell requests into the runtime; `emit`\n * pushes shell→napplet envelopes through the iframe's Window.\n */\nexport interface KeysProxy {\n /**\n * Route a napplet-originated keys.* envelope (e.g. `keys.forward`,\n * `keys.registerAction`) into the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Push a shell-initiated keys-domain envelope (e.g. `keys.action`,\n * `keys.bindings`) into a napplet iframe.\n *\n * No-op when the originRegistry cannot resolve the windowId (unknown or\n * unregistered napplet). Never throws.\n *\n * @param windowId - The target napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope to deliver\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical keys-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link KeysProxy} ready to route keys.* envelopes\n * @example\n * ```ts\n * import { createKeysProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const keysProxy = createKeysProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Host-app-initiated action trigger:\n * keysProxy.emit('win-editor', { type: 'keys.action', actionId: 'editor.save' });\n * ```\n */\nexport function createKeysProxy(deps: KeysProxyDeps): KeysProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(windowId: string, envelope: NappletMessage): void {\n const win = deps.originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(envelope, '*');\n },\n };\n}\n","/**\n * media-proxy.ts — Shell-side per-domain proxy for media.* envelopes.\n *\n * Establishes the shell-side composition seam for `@napplet/nap/media`\n * session-control envelopes. Shape mirrors identity-proxy (Plan 12-11):\n *\n * - `dispatch(windowId, envelope)` routes napplet→shell media requests\n * (`media.session.create`, `media.session.update`, `media.session.destroy`,\n * `media.state`, `media.capabilities`) into the runtime (Plan 12-06).\n * - `emit(windowId, envelope)` posts shell→napplet pushes (`media.command`,\n * `media.controls`, `media.session.create.result`) through the origin\n * registry.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns media.* dispatch. This module is an\n * optional composition point for host apps (e.g. shell-rendered playback\n * UIs that want to send `media.command` pushes).\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createMediaProxy`.\n *\n * @example\n * ```ts\n * const proxy = createMediaProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface MediaProxyDeps {\n /** The runtime engine that owns media.* dispatch (Plan 12-06). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `media.*` envelopes.\n *\n * Shape: `dispatch` routes napplet→shell requests into the runtime; `emit`\n * pushes shell→napplet envelopes through the iframe's Window.\n */\nexport interface MediaProxy {\n /**\n * Route a napplet-originated media.* envelope into the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Push a shell-initiated media-domain envelope (e.g. `media.command`,\n * `media.controls`) into a napplet iframe.\n *\n * No-op when the originRegistry cannot resolve the windowId (unknown or\n * unregistered napplet). Never throws.\n *\n * @param windowId - The target napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope to deliver\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical media-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link MediaProxy} ready to route media.* envelopes\n * @example\n * ```ts\n * import { createMediaProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const mediaProxy = createMediaProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Shell-UI-initiated media command:\n * mediaProxy.emit('win-player', {\n * type: 'media.command',\n * sessionId: 's1',\n * action: 'seek',\n * value: 120,\n * });\n * ```\n */\nexport function createMediaProxy(deps: MediaProxyDeps): MediaProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(windowId: string, envelope: NappletMessage): void {\n const win = deps.originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(envelope, '*');\n },\n };\n}\n","/**\n * notify-proxy.ts — Shell-side per-domain proxy for notify.* envelopes.\n *\n * Establishes the shell-side composition seam for `@napplet/nap/notify`\n * notification envelopes. Shape mirrors identity-proxy (Plan 12-11):\n *\n * - `dispatch(windowId, envelope)` routes napplet→shell notify requests\n * (`notify.send`, `notify.dismiss`, `notify.badge`,\n * `notify.channel.register`, `notify.permission.request`) into the\n * runtime (Plan 12-07).\n * - `emit(windowId, envelope)` posts shell→napplet pushes\n * (`notify.send.result`, `notify.permission.result`, `notify.action`,\n * `notify.clicked`, `notify.dismissed`, `notify.controls`) through the\n * origin registry.\n *\n * By default `createShellBridge()` does NOT compose this proxy into its\n * dispatch path — the runtime owns notify.* dispatch. This module is an\n * optional composition point for host apps (e.g. custom notification UIs\n * that need to emit `notify.clicked` / `notify.action` pushes).\n */\n\nimport type { Runtime } from '@kehto/runtime';\nimport type { NappletMessage } from '@napplet/core';\nimport type { ProxyOriginRegistry } from './identity-proxy.js';\n\n/**\n * Dependencies for `createNotifyProxy`.\n *\n * @example\n * ```ts\n * const proxy = createNotifyProxy({\n * runtime: shellBridge.runtime,\n * originRegistry,\n * });\n * ```\n */\nexport interface NotifyProxyDeps {\n /** The runtime engine that owns notify.* dispatch (Plan 12-07). */\n runtime: Runtime;\n /** Origin registry for resolving windowId → iframe Window. */\n originRegistry: ProxyOriginRegistry;\n}\n\n/**\n * Per-domain proxy for `notify.*` envelopes.\n *\n * Shape: `dispatch` routes napplet→shell requests into the runtime; `emit`\n * pushes shell→napplet envelopes through the iframe's Window.\n */\nexport interface NotifyProxy {\n /**\n * Route a napplet-originated notify.* envelope into the runtime.\n *\n * @param windowId - The source napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope\n */\n dispatch(windowId: string, envelope: NappletMessage): void;\n /**\n * Push a shell-initiated notify-domain envelope (e.g. `notify.action`,\n * `notify.clicked`) into a napplet iframe.\n *\n * No-op when the originRegistry cannot resolve the windowId (unknown or\n * unregistered napplet). Never throws.\n *\n * @param windowId - The target napplet's windowId\n * @param envelope - The NIP-5D NappletMessage envelope to deliver\n */\n emit(windowId: string, envelope: NappletMessage): void;\n}\n\n/**\n * Factory for the canonical notify-domain proxy.\n *\n * @param deps - Runtime + origin registry\n * @returns A {@link NotifyProxy} ready to route notify.* envelopes\n * @example\n * ```ts\n * import { createNotifyProxy, originRegistry, createShellBridge } from '@kehto/shell';\n *\n * const bridge = createShellBridge(hooks);\n * const notifyProxy = createNotifyProxy({\n * runtime: bridge.runtime,\n * originRegistry,\n * });\n *\n * // Shell-UI notifies napplet that user clicked its toast:\n * notifyProxy.emit('win-chat', {\n * type: 'notify.clicked',\n * notificationId: 'shell-42',\n * });\n * ```\n */\nexport function createNotifyProxy(deps: NotifyProxyDeps): NotifyProxy {\n return {\n dispatch(windowId: string, envelope: NappletMessage): void {\n deps.runtime.handleMessage(windowId, envelope);\n },\n emit(windowId: string, envelope: NappletMessage): void {\n const win = deps.originRegistry.getIframeWindow(windowId);\n if (win) win.postMessage(envelope, '*');\n },\n };\n}\n"],"mappings":";AACA,SAAS,qBAAwD;;;AC6BjE,SAAS,WAAW,OAA2B;AAC7C,SAAO,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC1E;AAEA,SAAS,WAAW,KAAyB;AAC3C,QAAM,QAAQ,IAAI,WAAW,IAAI,SAAS,CAAC;AAC3C,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;AACtC,UAAM,IAAI,CAAC,IAAI,SAAS,IAAI,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE;AAAA,EACrD;AACA,SAAO;AACT;AAqBA,SAAS,oBAAoBA,iBAA8D;AACzF,S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AAAA,IACA,KAAK,WAAmB,WAAiC;AACvD,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AChCO,SAAS,iBAAiB,MAAkC;AACjE,SAAO;AAAA,IACL,SAAS,UAAkB,UAAgC;AACzD,WAAK,QAAQ,cAAc,UAAU,QAAQ;AAAA,IAC/C;AAAA,IACA,KAAK,WAAmB,WAAiC;AACvD,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACCO,SAAS,gBAAgB,MAAgC;AAC9D,SAAO;AAAA,IACL,SAAS,UAAkB,UAAgC;AACzD,WAAK,QAAQ,cAAc,UAAU,QAAQ;AAAA,IAC/C;AAAA,IACA,KAAK,UAAkB,UAAgC;AACrD,YAAM,MAAM,KAAK,eAAe,gBAAgB,QAAQ;AACxD,UAAI,IAAK,KAAI,YAAY,UAAU,GAAG;AAAA,IACxC;AAAA,EACF;AACF;;;ACTO,SAAS,iBAAiB,MAAkC;AACjE,SAAO;AAAA,IACL,SAAS,UAAkB,UAAgC;AACzD,WAAK,QAAQ,cAAc,UAAU,QAAQ;AAAA,IAC/C;AAAA,IACA,KAAK,UAAkB,UAAgC;AACrD,YAAM,MAAM,KAAK,eAAe,gBAAgB,QAAQ;AACxD,UAAI,IAAK,KAAI,YAAY,UAAU,GAAG;AAAA,IACxC;AAAA,EACF;AACF;;;ACVO,SAAS,kBAAkB,MAAoC;AACpE,SAAO;AAAA,IACL,SAAS,UAAkB,UAAgC;AACzD,WAAK,QAAQ,cAAc,UAAU,QAAQ;AAAA,IAC/C;AAAA,IACA,KAAK,UAAkB,UAAgC;AACrD,YAAM,MAAM,KAAK,eAAe,gBAAgB,QAAQ;AACxD,UAAI,IAAK,KAAI,YAAY,UAAU,GAAG;AAAA,IACxC;AAAA,EACF;AACF;","names":["originRegistry","STORAGE_KEY","normalizeIntentUri","normalizeIntentUri","domains","shell","version","delivery","allowed","normalized","sources","ALL_CAPABILITIES"]}
|