@napplet/conformance-cli 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,149 +1,13 @@
1
- (function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))t(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&t(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function t(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();var Ce=["shell","relay","identity","storage","inc","theme","keys","media","notify","config","resource","cvm","outbox","upload","intent","ble","webrtc","link","count","lists","serial","fs","common","dm","gamepad"],c={id:"string"},Rt={"gamepad.subscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.unsubscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.state":{dir:"in",fields:{available:"boolean",focused:"boolean",pads:"array"}},"shell.ready":{dir:"out"},"shell.init":{dir:"in",fields:{capabilities:"object",services:"array"}},"relay.subscribe":{dir:"out",fields:{...c,subId:"string",filters:"array"}},"relay.close":{dir:"out",fields:{...c,subId:"string"}},"relay.publish":{dir:"out",fields:{...c,event:"object"}},"relay.publishEncrypted":{dir:"out",fields:{...c,event:"object",recipient:"string"}},"relay.query":{dir:"out",fields:{...c,filters:"array"}},"relay.event":{dir:"in"},"relay.eose":{dir:"in"},"relay.closed":{dir:"in"},"relay.publish.result":{dir:"in"},"relay.publishEncrypted.result":{dir:"in"},"relay.query.result":{dir:"in"},"identity.getPublicKey":{dir:"out",fields:{...c}},"identity.getRelays":{dir:"out",fields:{...c}},"identity.getProfile":{dir:"out",fields:{...c}},"identity.getFollows":{dir:"out",fields:{...c}},"identity.getList":{dir:"out",fields:{...c,listType:"string"}},"identity.getZaps":{dir:"out",fields:{...c}},"identity.getMutes":{dir:"out",fields:{...c}},"identity.getBlocked":{dir:"out",fields:{...c}},"identity.getBadges":{dir:"out",fields:{...c}},"identity.changed":{dir:"in"},"identity.getPublicKey.result":{dir:"in"},"identity.getRelays.result":{dir:"in"},"identity.getProfile.result":{dir:"in"},"identity.getFollows.result":{dir:"in"},"identity.getList.result":{dir:"in"},"identity.getZaps.result":{dir:"in"},"identity.getMutes.result":{dir:"in"},"identity.getBlocked.result":{dir:"in"},"identity.getBadges.result":{dir:"in"},"storage.get":{dir:"out",fields:{...c,key:"string"}},"storage.set":{dir:"out",fields:{...c,key:"string",value:"string"}},"storage.remove":{dir:"out",fields:{...c,key:"string"}},"storage.keys":{dir:"out",fields:{...c}},"storage.get.result":{dir:"in"},"storage.set.result":{dir:"in"},"storage.remove.result":{dir:"in"},"storage.keys.result":{dir:"in"},"inc.emit":{dir:"out",fields:{topic:"string"},forbiddenFields:["sender"]},"inc.subscribe":{dir:"out",fields:{...c,topic:"string"}},"inc.unsubscribe":{dir:"out",fields:{topic:"string"}},"inc.channel.open":{dir:"out",fields:{...c,target:"string"}},"inc.channel.emit":{dir:"out",fields:{channelId:"string"}},"inc.channel.broadcast":{dir:"out"},"inc.channel.list":{dir:"out",fields:{...c}},"inc.channel.close":{dir:"out",fields:{channelId:"string"}},"inc.subscribe.result":{dir:"in"},"inc.event":{dir:"in",fields:{topic:"string",sender:"string"}},"inc.channel.open.result":{dir:"in"},"inc.channel.opened":{dir:"in",fields:{channelId:"string",peer:"string"}},"inc.channel.event":{dir:"in"},"inc.channel.list.result":{dir:"in"},"inc.channel.closed":{dir:"in"},"theme.get":{dir:"out",fields:{...c}},"theme.get.result":{dir:"in"},"theme.changed":{dir:"in"},"keys.forward":{dir:"out",fields:{key:"string",code:"string",ctrl:"boolean",alt:"boolean",shift:"boolean",meta:"boolean"}},"keys.registerAction":{dir:"out",fields:{...c,action:"object"}},"keys.unregisterAction":{dir:"out",fields:{actionId:"string"}},"keys.registerAction.result":{dir:"in"},"keys.bindings":{dir:"in"},"keys.action":{dir:"in"},"media.session.create":{dir:"out",fields:{...c,owner:"object"}},"media.session.update":{dir:"out",fields:{sessionId:"string",metadata:"object"}},"media.session.destroy":{dir:"out",fields:{sessionId:"string"}},"media.state":{dir:"out",fields:{sessionId:"string",status:"string"}},"media.capabilities":{dir:"out",fields:{sessionId:"string",actions:"array"}},"media.session.create.result":{dir:"in"},"media.command":{dir:"in"},"media.controls":{dir:"in"},"notify.send":{dir:"out",fields:{...c,title:"string"}},"notify.dismiss":{dir:"out",fields:{notificationId:"string"}},"notify.badge":{dir:"out",fields:{count:"number"}},"notify.channel.register":{dir:"out",fields:{channelId:"string",label:"string"}},"notify.permission.request":{dir:"out",fields:{...c}},"notify.send.result":{dir:"in"},"notify.permission.result":{dir:"in"},"notify.action":{dir:"in"},"notify.clicked":{dir:"in"},"notify.dismissed":{dir:"in"},"notify.controls":{dir:"in"},"config.registerSchema":{dir:"out",fields:{...c,schema:"object"}},"config.get":{dir:"out",fields:{...c}},"config.subscribe":{dir:"out"},"config.unsubscribe":{dir:"out"},"config.openSettings":{dir:"out"},"config.registerSchema.result":{dir:"in"},"config.values":{dir:"in"},"config.schemaError":{dir:"in"},"resource.info":{dir:"out",fields:{...c}},"resource.bytes":{dir:"out",fields:{...c,url:"string"}},"resource.bytesMany":{dir:"out",fields:{...c,requests:"array"}},"resource.cancel":{dir:"out",fields:{...c}},"resource.info.result":{dir:"in"},"resource.info.error":{dir:"in"},"resource.bytes.result":{dir:"in"},"resource.bytes.error":{dir:"in"},"resource.bytesMany.result":{dir:"in"},"resource.bytesMany.error":{dir:"in"},"cvm.discover":{dir:"out",fields:{...c}},"cvm.request":{dir:"out",fields:{...c,server:"object",message:"object"}},"cvm.close":{dir:"out",fields:{...c,server:"object"}},"cvm.registry.list":{dir:"out",fields:{...c}},"cvm.registry.has":{dir:"out",fields:{...c,family:"string"}},"cvm.registry.describe":{dir:"out",fields:{...c,family:"string"}},"cvm.registry.call":{dir:"out",fields:{...c,family:"string",tool:"string"}},"cvm.discover.result":{dir:"in"},"cvm.request.result":{dir:"in"},"cvm.close.result":{dir:"in"},"cvm.event":{dir:"in"},"cvm.registry.list.result":{dir:"in"},"cvm.registry.has.result":{dir:"in"},"cvm.registry.describe.result":{dir:"in"},"cvm.registry.call.result":{dir:"in"},"outbox.getEvent":{dir:"out",fields:{...c,eventId:"string"}},"outbox.query":{dir:"out",fields:{...c,filters:"present"}},"outbox.subscribe":{dir:"out",fields:{...c,subId:"string",filters:"present"}},"outbox.close":{dir:"out",fields:{...c,subId:"string"}},"outbox.publish":{dir:"out",fields:{...c,event:"object"}},"outbox.resolveRelays":{dir:"out",fields:{...c,target:"present"}},"outbox.getEvent.result":{dir:"in"},"outbox.query.result":{dir:"in"},"outbox.event":{dir:"in"},"outbox.closed":{dir:"in"},"outbox.publish.result":{dir:"in"},"outbox.resolveRelays.result":{dir:"in"},"upload.info":{dir:"out",fields:{...c}},"upload.upload":{dir:"out",fields:{...c,request:"object"}},"upload.status":{dir:"out",fields:{...c,uploadId:"string"}},"upload.info.result":{dir:"in"},"upload.upload.result":{dir:"in"},"upload.status.result":{dir:"in"},"upload.status.changed":{dir:"in"},"intent.invoke":{dir:"out",fields:{...c,request:"object"}},"intent.available":{dir:"out",fields:{...c,archetype:"string"}},"intent.handlers":{dir:"out",fields:{...c}},"intent.invoke.result":{dir:"in",fields:{...c,result:"object"}},"intent.available.result":{dir:"in"},"intent.handlers.result":{dir:"in"},"intent.deliver":{dir:"in",fields:{delivery:"object"}},"intent.changed":{dir:"in"},"ble.open":{dir:"out",fields:{...c,request:"object"}},"ble.services":{dir:"out",fields:{...c,sessionId:"string"}},"ble.read":{dir:"out",fields:{...c,sessionId:"string",target:"object"}},"ble.write":{dir:"out",fields:{...c,sessionId:"string",target:"object",data:"array"}},"ble.subscribe":{dir:"out",fields:{...c,sessionId:"string",target:"object"}},"ble.unsubscribe":{dir:"out",fields:{...c,sessionId:"string",target:"object"}},"ble.close":{dir:"out",fields:{...c,sessionId:"string"}},"ble.open.result":{dir:"in"},"ble.services.result":{dir:"in"},"ble.read.result":{dir:"in"},"ble.write.result":{dir:"in"},"ble.subscribe.result":{dir:"in"},"ble.unsubscribe.result":{dir:"in"},"ble.close.result":{dir:"in"},"ble.event":{dir:"in"},"common.encodeNip19":{dir:"out",fields:{...c,input:"object"}},"common.decodeNip19":{dir:"out",fields:{...c,value:"string"}},"common.getProfile":{dir:"out",fields:{...c,target:"string"}},"common.follows":{dir:"out",fields:{...c}},"common.follow":{dir:"out",fields:{...c,pubkeys:"array"}},"common.unfollow":{dir:"out",fields:{...c,pubkeys:"array"}},"common.react":{dir:"out",fields:{...c,targetEventId:"string",reaction:"string"}},"common.report":{dir:"out",fields:{...c,target:"object",reason:"string",text:"string"}},"common.encodeNip19.result":{dir:"in"},"common.decodeNip19.result":{dir:"in"},"common.getProfile.result":{dir:"in"},"common.follows.result":{dir:"in"},"common.follow.result":{dir:"in"},"common.unfollow.result":{dir:"in"},"common.react.result":{dir:"in"},"common.report.result":{dir:"in"},"webrtc.open":{dir:"out",fields:{...c,request:"object"}},"webrtc.send":{dir:"out",fields:{...c,sessionId:"string",payload:"present"}},"webrtc.close":{dir:"out",fields:{...c,sessionId:"string"}},"webrtc.open.result":{dir:"in"},"webrtc.send.result":{dir:"in"},"webrtc.close.result":{dir:"in"},"webrtc.event":{dir:"in"},"link.open":{dir:"out",fields:{...c,url:"string"}},"link.open.result":{dir:"in"},"count.query":{dir:"out",fields:{...c,filters:"array"}},"count.query.result":{dir:"in"},"lists.supported":{dir:"out",fields:{...c}},"lists.add":{dir:"out",fields:{...c,list:"object",items:"array"}},"lists.remove":{dir:"out",fields:{...c,list:"object",items:"array"}},"lists.supported.result":{dir:"in"},"lists.add.result":{dir:"in"},"lists.remove.result":{dir:"in"},"serial.open":{dir:"out",fields:{...c,request:"object"}},"serial.write":{dir:"out",fields:{...c,sessionId:"string",data:"array"}},"serial.close":{dir:"out",fields:{...c,sessionId:"string"}},"serial.open.result":{dir:"in"},"serial.write.result":{dir:"in"},"serial.close.result":{dir:"in"},"serial.event":{dir:"in"},"fs.info":{dir:"out",fields:{...c}},"fs.pickFile":{dir:"out",fields:{...c}},"fs.pickFiles":{dir:"out",fields:{...c}},"fs.pickDirectory":{dir:"out",fields:{...c}},"fs.pickSaveFile":{dir:"out",fields:{...c}},"fs.stat":{dir:"out",fields:{...c,path:"string"}},"fs.list":{dir:"out",fields:{...c,path:"string"}},"fs.read":{dir:"out",fields:{...c,path:"string"}},"fs.write":{dir:"out",fields:{...c,path:"string",data:"string"}},"fs.mkdir":{dir:"out",fields:{...c,path:"string"}},"fs.remove":{dir:"out",fields:{...c,path:"string"}},"fs.move":{dir:"out",fields:{...c,fromPath:"string",toPath:"string"}},"fs.watch":{dir:"out",fields:{...c,path:"string"}},"fs.unwatch":{dir:"out",fields:{...c,watchId:"string"}},"fs.info.result":{dir:"in"},"fs.pickFile.result":{dir:"in"},"fs.pickFiles.result":{dir:"in"},"fs.pickDirectory.result":{dir:"in"},"fs.pickSaveFile.result":{dir:"in"},"fs.stat.result":{dir:"in"},"fs.list.result":{dir:"in"},"fs.read.result":{dir:"in"},"fs.write.result":{dir:"in"},"fs.mkdir.result":{dir:"in"},"fs.remove.result":{dir:"in"},"fs.move.result":{dir:"in"},"fs.watch.result":{dir:"in"},"fs.unwatch.result":{dir:"in"},"fs.changed":{dir:"in"},"dm.status":{dir:"out",fields:{...c}},"dm.conversations":{dir:"out",fields:{...c}},"dm.messages":{dir:"out",fields:{...c,conversationId:"string"}},"dm.send":{dir:"out",fields:{...c,recipients:"array",content:"string"}},"dm.subscribe":{dir:"out",fields:{...c}},"dm.unsubscribe":{dir:"out",fields:{...c,subscriptionId:"string"}},"dm.status.result":{dir:"in"},"dm.conversations.result":{dir:"in"},"dm.messages.result":{dir:"in"},"dm.send.result":{dir:"in"},"dm.subscribe.result":{dir:"in"},"dm.unsubscribe.result":{dir:"in"},"dm.message":{dir:"in"}};function He(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return"array";const n=typeof e;return n==="string"||n==="number"||n==="boolean"?n:n==="object"?"object":"present"}function It(e,n){return n==="present"?e!=null:He(e)===n}function kt(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return;const s=e;typeof s.archetype!="string"&&n.push({code:s.archetype===void 0?"missing-field":"wrong-type",message:'Intent request requires a string "archetype" field',field:"request.archetype"});for(const r of["action","convention"])typeof s[r]!="string"&&n.push({code:s[r]===void 0?"missing-field":"wrong-type",message:`Intent request field "${r}" must be a string`,field:`request.${r}`});const t=typeof s.convention=="string"?/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(s.convention):null;(!t||t[1]!==s.archetype||t[2]!==s.action)&&n.push({code:"wrong-type",message:"Intent convention must be stable and match archetype and action",field:"request.convention"}),s.handler!==void 0&&typeof s.handler!="string"&&n.push({code:"wrong-type",message:'Intent request field "handler" must be a string',field:"request.handler"}),s.behavior!==void 0&&He(s.behavior)!=="object"&&n.push({code:"wrong-type",message:'Intent request field "behavior" must be an object',field:"request.behavior"}),s.handlerHint!==void 0&&xt(s.handlerHint,n),"sender"in s&&n.push({code:"forbidden-field",message:"Intent request does not define a caller-supplied sender field",field:"request.sender"})}function xt(e,n){if(He(e)!=="object"){n.push({code:"wrong-type",message:'Intent request field "handlerHint" must be an object',field:"request.handlerHint"});return}const{address:s,relays:t}=e;(typeof s!="string"||!/^35129:[0-9a-f]{64}:.+$/s.test(s))&&n.push({code:s===void 0?"missing-field":"wrong-type",message:'Intent handler hint "address" must be a 35129:<pubkey>:<d> coordinate',field:"request.handlerHint.address"}),t!==void 0&&!(Array.isArray(t)&&t.every(r=>typeof r=="string"))&&n.push({code:"wrong-type",message:'Intent handler hint "relays" must be an array of strings',field:"request.handlerHint.relays"})}function Dn(e,n,s){Array.isArray(e)&&e.every(t=>typeof t=="string")||s.push({code:"wrong-type",message:`Field "${n}" must be an array of strings`,field:n})}function Ut(e,n){e.servers!==void 0&&Dn(e.servers,"servers",n)}function Mt(e,n){if(Array.isArray(e)){if(e.length===0){n.push({code:"invalid-resource-request",message:'Field "requests" must contain at least one resource request',field:"requests"});return}for(const[s,t]of e.entries()){const r=`requests[${s}]`;if(typeof t!="object"||t===null||Array.isArray(t)){n.push({code:"invalid-resource-request",message:`Field "${r}" must be a resource request object`,field:r});continue}const i=t;typeof i.url!="string"&&n.push({code:i.url===void 0?"missing-field":"wrong-type",message:`Field "${r}.url" must be a string`,field:`${r}.url`}),i.servers!==void 0&&Dn(i.servers,`${r}.servers`,n)}}}function Pt(e){const n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{ok:!1,errors:[{code:"not-an-object",message:"Envelope must be a non-null object"}]};const s=e,t=s.type;if(typeof t!="string")return{ok:!1,errors:[{code:"missing-type",message:"Envelope is missing a string `type` field"}]};const r=t.indexOf(".");if(r<=0)return{ok:!1,type:t,errors:[{code:"malformed-type",message:`Envelope type "${t}" is not in domain.action form`}]};const i=t.slice(0,r);if(!Ce.includes(i))return{ok:!1,type:t,domain:i,errors:[{code:"unknown-domain",message:`"${i}" is not a known NAP domain`}]};const l=Rt[t];if(!l)return{ok:!1,type:t,domain:i,errors:[{code:"unknown-type",message:`"${t}" is not a known ${i} message type`}]};for(const[a,d]of Object.entries(l.fields??{})){if(!(a in s)||s[a]===void 0){n.push({code:"missing-field",message:`Required field "${a}" is missing`,field:a});continue}It(s[a],d)||n.push({code:"wrong-type",message:`Field "${a}" should be ${d} but is ${He(s[a])}`,field:a})}if(l.dir==="in")return{ok:!1,type:t,domain:i,direction:"in",errors:[{code:"inbound-type-emitted",message:`"${t}" is a shell→napplet message; a napplet must not emit it`},...n]};for(const a of l.forbiddenFields??[])a in s&&n.push({code:"forbidden-field",message:`Field "${a}" cannot be emitted by a napplet: ${l.forbiddenReason??"it must be runtime-derived"}`,field:a});return t==="intent.invoke"&&kt(s.request,n),t==="resource.bytes"&&Ut(s,n),t==="resource.bytesMany"&&Mt(s.requests,n),{ok:n.length===0,type:t,domain:i,direction:"out",errors:n}}var Nn=5129,At=15129,ce=35129,dn=[Nn,At,ce];function $n(e,n){return e.tags.find(s=>s[0]===n)}function jt(e){return dn.includes(e)}function Ln(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function Fn(e){return $n(e,"d")?.[1]||void 0}function Ot(e){return e.tags.filter(n=>n[0]==="R").map(n=>n[1]?.trim()??"").filter(Boolean)}function Gn(e){return Fn(e)??$n(e,"title")?.[1]??e.id}function Be(e){const n=[],s=[];if(!e)return{ok:!1,requires:[],optional:[],errors:[{code:"missing-manifest-event",message:"No NIP-5D manifest event was resolved"}],warnings:s};const t=Fn(e),r=Ot(e);jt(e.kind)||n.push({code:"invalid-napplet-kind",message:`Manifest event kind ${e.kind} is not a NIP-5D napplet kind`});const i=e.tags.filter(l=>l[0]==="d");e.kind===ce&&(i.length!==1||!t)?n.push({code:"missing-d-tag",message:"Named manifests require exactly one non-empty d tag"}):e.kind!==ce&&i.length>0&&n.push({code:"unexpected-d-tag",message:"Only named manifests carry a d tag"});const o=e.tags.filter(l=>l[0]==="x");return(o.length!==1||o[0].length!==2||!Ln(o[0][1]))&&n.push({code:"invalid-artifact-hash",message:"Manifest requires exactly one x tag with the lowercase sha256 of /index.html"}),(typeof e.content!="string"||!e.content.trim())&&n.push({code:"missing-description",message:"Manifest content must contain a non-empty plain-text description"}),qt(e,n,s),Ct(e,n,s),{ok:n.length===0,kind:e.kind,dTag:t,requires:r,optional:e.tags.filter(l=>l[0]==="O").map(l=>l[1]).filter(Boolean),errors:n,warnings:s}}function qt(e,n,s){for(const t of e.tags.filter(r=>r[0]==="R"||r[0]==="O")){const r=t[1];t.length!==2||!r||/[.:\s]/.test(r)||r.startsWith("NAP-")?n.push({code:t[0]==="R"?"invalid-required-nap":"invalid-optional-nap",message:`${t[0]} must name one bare NAP domain`}):Ce.includes(r)||s.push({code:"unknown-required-nap",message:`Domain "${r}" is not in this tool's registry; check its NAP and runtime availability`})}}function Ct(e,n,s){for(const r of["title","source","a","A"]){const i=e.tags.filter(o=>o[0]===r);(i.length>1||i.length&&(r==="a"||r==="A")&&e.kind!==Nn)&&n.push({code:"invalid-metadata",message:`Invalid ${r} tag cardinality for kind ${e.kind}`})}for(const r of e.tags.filter(i=>i[0]==="source"))(r.length!==2||!Ht(r[1]))&&n.push({code:"invalid-metadata",message:"source must contain one HTTP(S), SSH, Git, or SCP repository location"});for(const r of e.tags.filter(i=>i[0]==="i"))(!r[1]?.trim()||r[1].includes("?"))&&n.push({code:"invalid-metadata",message:"Intent advertisements must be non-empty queryless identities"});const t=e.tags.filter(r=>r[0]==="icon");(t.length>1||t.some(r=>r.length!==3||!Ln(r[1])||!["image/png","image/jpeg","image/webp"].includes(r[2])))&&s.push({code:"invalid-icon",message:"Ignore invalid icon metadata and use generic artwork (NIP-5D §Icon)"})}function Ht(e){if(!e||/^[a-z]:[\\/]/i.test(e))return!1;try{const{protocol:n}=new URL(e);if(["http:","https:","ssh:","git:"].includes(n))return!0;if(n==="file:")return!1}catch{}return!e.includes("://")&&/^(?:[^@\s/:]+@)?[^:\s/]+:[^\s]+$/.test(e)}var de="f".repeat(64),Bt={id:"reference-source-endpoint",catalogId:"reference-source"},Dt="https://reference.invalid/blob",Nt=`named:${de}:reference-handler`,$t={kind:35129,pubkey:de,id:"0".repeat(64),tags:[["d","reference-handler"],["z","note"],["i","napplet:note/open","event"]]},Lt="reference-subscriber",Ft="napplet:note/open";function _e(e,n,s){return p({type:e,id:n,result:{entries:[s]}})}var p=e=>[e],A=()=>[];function vn(e){if(typeof e!="string"||!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return{blob:new Blob([],{type:"text/plain"}),mime:"text/plain"};const s=e.slice(5,n),t=e.slice(n+1),r=s.split(";").filter(Boolean),i=r.includes("base64"),o=r.find(l=>l.includes("/"))??"text/plain";try{if(i){const l=globalThis.atob(t),a=Uint8Array.from(l,d=>d.charCodeAt(0));return{blob:new Blob([a],{type:o}),mime:o}}return{blob:new Blob([decodeURIComponent(t)],{type:o}),mime:o}}catch{return null}}var Gt={"gamepad.subscribe":()=>p({type:"gamepad.state",available:!1,reason:"unavailable",focused:!1,pads:[]}),"gamepad.unsubscribe":A,"relay.subscribe":e=>p({type:"relay.eose",subId:e.subId}),"relay.close":A,"relay.publish":e=>p({type:"relay.publish.result",id:e.id,ok:!0,event:e.event}),"relay.publishEncrypted":e=>p({type:"relay.publishEncrypted.result",id:e.id,ok:!0,event:e.event}),"relay.query":e=>p({type:"relay.query.result",id:e.id,events:[]}),"identity.getPublicKey":e=>p({type:"identity.getPublicKey.result",id:e.id,pubkey:de}),"identity.getRelays":e=>p({type:"identity.getRelays.result",id:e.id,relays:{}}),"identity.getProfile":e=>p({type:"identity.getProfile.result",id:e.id,profile:null}),"identity.getFollows":e=>p({type:"identity.getFollows.result",id:e.id,pubkeys:[]}),"identity.getList":e=>p({type:"identity.getList.result",id:e.id,entries:[]}),"identity.getZaps":e=>p({type:"identity.getZaps.result",id:e.id,zaps:[]}),"identity.getMutes":e=>p({type:"identity.getMutes.result",id:e.id,pubkeys:[]}),"identity.getBlocked":e=>p({type:"identity.getBlocked.result",id:e.id,pubkeys:[]}),"identity.getBadges":e=>p({type:"identity.getBadges.result",id:e.id,badges:[]}),"storage.get":e=>p({type:"storage.get.result",id:e.id,value:null}),"storage.set":e=>p({type:"storage.set.result",id:e.id}),"storage.remove":e=>p({type:"storage.remove.result",id:e.id}),"storage.keys":e=>p({type:"storage.keys.result",id:e.id,keys:[]}),"inc.emit":A,"inc.subscribe":e=>p({type:"inc.subscribe.result",id:e.id}),"inc.unsubscribe":A,"inc.channel.open":e=>p({type:"inc.channel.open.result",id:e.id,channelId:`chan-${String(e.id)}`,peer:"reference-peer"}),"inc.channel.emit":A,"inc.channel.broadcast":A,"inc.channel.list":e=>p({type:"inc.channel.list.result",id:e.id,channels:[]}),"inc.channel.close":A,"theme.get":e=>p({type:"theme.get.result",id:e.id,theme:{colors:{background:"#000000",text:"#ffffff",primary:"#663399"}}}),"keys.forward":A,"keys.registerAction":e=>p({type:"keys.registerAction.result",id:e.id,actionId:`action-${String(e.id)}`}),"keys.unregisterAction":A,"media.session.create":e=>p({type:"media.session.create.result",id:e.id,sessionId:`session-${String(e.id)}`,owner:e.owner}),"media.session.update":A,"media.session.destroy":A,"media.state":A,"media.capabilities":A,"notify.send":e=>p({type:"notify.send.result",id:e.id,notificationId:`notif-${String(e.id)}`}),"notify.dismiss":A,"notify.badge":A,"notify.channel.register":A,"notify.permission.request":e=>p({type:"notify.permission.result",id:e.id,granted:!0}),"config.registerSchema":e=>p({type:"config.registerSchema.result",id:e.id,ok:!0}),"config.get":e=>p({type:"config.values",id:e.id,values:{}}),"config.subscribe":()=>p({type:"config.values",values:{}}),"config.unsubscribe":A,"config.openSettings":A,"resource.bytes":e=>{const n=vn(e.url);return p(n?{type:"resource.bytes.result",id:e.id,blob:n.blob,mime:n.mime}:{type:"resource.bytes.result",id:e.id,blob:new Blob([]),mime:"application/octet-stream"})},"resource.bytesMany":e=>p({type:"resource.bytesMany.result",id:e.id,items:Array.isArray(e.requests)?e.requests.map(n=>{const s=typeof n=="object"&&n!==null&&!Array.isArray(n)?n.url:void 0,t=vn(s);return{url:typeof s=="string"?s:"",ok:!0,blob:t?.blob??new Blob([]),mime:t?.mime??"application/octet-stream"}}):[]}),"resource.info":e=>p({type:"resource.info.result",id:e.id,info:{schemes:[{scheme:"data",enabled:!0},{scheme:"https",enabled:!0}],maxServers:8}}),"resource.cancel":A,"cvm.discover":e=>p({type:"cvm.discover.result",id:e.id,servers:[]}),"cvm.request":e=>p({type:"cvm.request.result",id:e.id,message:{}}),"cvm.close":e=>p({type:"cvm.close.result",id:e.id}),"outbox.getEvent":e=>p({type:"outbox.getEvent.result",id:e.id}),"outbox.query":e=>p({type:"outbox.query.result",id:e.id,events:[]}),"outbox.subscribe":e=>p({type:"outbox.closed",subId:e.subId,reason:"reference shell complete"}),"outbox.close":A,"outbox.publish":e=>p({type:"outbox.publish.result",id:e.id,ok:!0}),"outbox.resolveRelays":e=>p({type:"outbox.resolveRelays.result",id:e.id,plan:{}}),"upload.info":e=>p({type:"upload.info.result",id:e.id,info:{rails:[{rail:"nip96",enabled:!0,returns:["https"]},{rail:"blossom",enabled:!0,returns:["https","blossom"]}]}}),"upload.upload":e=>p({type:"upload.upload.result",id:e.id,result:{url:Dt}}),"upload.status":e=>p({type:"upload.status.result",id:e.id,status:{}}),"ble.open":e=>p({type:"ble.open.result",id:e.id,session:{id:"ble-reference",state:"open",device:{id:"reference-device",name:"Reference BLE"}}}),"ble.services":e=>p({type:"ble.services.result",id:e.id,services:[]}),"ble.read":e=>p({type:"ble.read.result",id:e.id,data:[]}),"ble.write":e=>p({type:"ble.write.result",id:e.id}),"ble.subscribe":e=>p({type:"ble.subscribe.result",id:e.id}),"ble.unsubscribe":e=>p({type:"ble.unsubscribe.result",id:e.id}),"ble.close":e=>p({type:"ble.close.result",id:e.id}),"common.encodeNip19":e=>p({type:"common.encodeNip19.result",id:e.id,ok:!0,value:"npub1reference",nip19Type:"npub"}),"common.decodeNip19":e=>p({type:"common.decodeNip19.result",id:e.id,ok:!0,nip19Type:"npub",hex:de}),"common.getProfile":e=>p({type:"common.getProfile.result",id:e.id,ok:!0,pubkey:de,profile:null}),"common.follows":e=>p({type:"common.follows.result",id:e.id,ok:!0,pubkeys:[]}),"common.follow":e=>p({type:"common.follow.result",id:e.id,ok:!0}),"common.unfollow":e=>p({type:"common.unfollow.result",id:e.id,ok:!0}),"common.react":e=>p({type:"common.react.result",id:e.id,ok:!0,eventId:"0".repeat(64)}),"common.report":e=>p({type:"common.report.result",id:e.id,ok:!0,eventId:"1".repeat(64)}),"webrtc.open":e=>p({type:"webrtc.open.result",id:e.id,session:{id:"webrtc-reference",scope:{type:"direct",pubkey:de},channel:"default",state:"connecting"}}),"webrtc.send":e=>p({type:"webrtc.send.result",id:e.id}),"webrtc.close":e=>p({type:"webrtc.close.result",id:e.id}),"link.open":e=>p({type:"link.open.result",id:e.id,status:"opened"}),"count.query":e=>p({type:"count.query.result",id:e.id,ok:!0,count:0}),"lists.supported":e=>p({type:"lists.supported.result",id:e.id,lists:[]}),"lists.add":e=>p({type:"lists.add.result",id:e.id,ok:!0,added:0,skipped:0}),"lists.remove":e=>p({type:"lists.remove.result",id:e.id,ok:!0,removed:0,skipped:0}),"serial.open":e=>p({type:"serial.open.result",id:e.id,session:{id:`serial-${String(e.id)}`,state:"open"}}),"serial.write":e=>p({type:"serial.write.result",id:e.id}),"serial.close":e=>p({type:"serial.close.result",id:e.id}),"fs.info":e=>p({type:"fs.info.result",id:e.id,info:{roots:[{path:"/shared",name:"Shared files",permissions:["read","list","write","create","delete","watch"]}],limits:{maxReadBytes:1048576,maxWriteBytes:1048576,maxWatchCount:16}}}),"fs.pickFile":e=>_e("fs.pickFile.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickFiles":e=>_e("fs.pickFiles.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickDirectory":e=>_e("fs.pickDirectory.result",e.id,{path:"/picked",kind:"directory",name:"picked",permissions:["read","list"]}),"fs.pickSaveFile":e=>_e("fs.pickSaveFile.result",e.id,{path:"/picked/export.json",kind:"file",name:"export.json",permissions:["write","create"]}),"fs.stat":e=>p({type:"fs.stat.result",id:e.id,metadata:{path:e.path,kind:"file",size:0}}),"fs.list":e=>p({type:"fs.list.result",id:e.id,entries:[]}),"fs.read":e=>p({type:"fs.read.result",id:e.id,result:{data:"",offset:0,bytesRead:0,eof:!0,size:0}}),"fs.write":e=>p({type:"fs.write.result",id:e.id,result:{bytesWritten:0,size:0}}),"fs.mkdir":e=>p({type:"fs.mkdir.result",id:e.id}),"fs.remove":e=>p({type:"fs.remove.result",id:e.id}),"fs.move":e=>p({type:"fs.move.result",id:e.id}),"fs.watch":e=>p({type:"fs.watch.result",id:e.id,watchId:`watch-${String(e.id)}`}),"fs.unwatch":e=>p({type:"fs.unwatch.result",id:e.id})};function Wt(e){const n=new Set;return(s,t)=>{const r=Vt(t),i=Pt(t);if(e.records.push({envelope:t,verdict:i,timestamp:e.now()}),!r||!i.ok)return[];const o=s.domains??Ce;if(!o.includes(r.slice(0,r.indexOf("."))))return[];if(r==="shell.ready")return n.has(s.id)?[]:(n.add(s.id),p({type:"shell.init",capabilities:{domains:[...o]},services:[]}));const l=t;if(r==="intent.invoke")return e.intents.handleInvoke(s,l);if(r==="intent.available")return p({type:"intent.available.result",id:l.id,availability:e.intents.availability(l.archetype)});if(r==="intent.handlers")return p({type:"intent.handlers.result",id:l.id,handlers:e.intents.handlers()});if(r==="inc.emit")return Qt(s,l,e.queueDelivery);const a=Gt[r];return a?a(l):[]}}function Vt(e){if(!e||typeof e!="object")return;const n=e.type;return typeof n=="string"?n:void 0}function Qt(e,n,s){if(n.topic!==Ft)return[];const t={type:"inc.event",topic:n.topic,sender:e.id};return"payload"in n&&(t.payload=n.payload),s(Lt,t),[]}function zt(e){return e.kind===5129?`snapshot:${e.id}`:e.kind===15129?`root:${e.pubkey}`:`named:${e.pubkey}:${e.tags.find(n=>n[0]==="d")?.[1]??""}`}function Kt(e,n){if(!e.tags.some(t=>t[0]==="z"&&t[1]===n))return[];const s=[];for(const t of e.tags)t[0]!=="i"||/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(t[1]??"")?.[1]!==n||s.push({convention:t[1],params:t.slice(2)});return s}function Zt(e,n,s){const t=[];for(const r of e){const i=Kt(r,n);if(!i.length)continue;const o=r.tags.find(a=>a[0]==="title")?.[1],l=zt(r);t.push({id:l,...o?{title:o}:{},actions:[...new Set(i.map(({convention:a})=>a.slice(a.indexOf("/")+1)))],conventions:[...new Set(i.map(({convention:a})=>a))],contracts:i,...l===s?{isDefault:!0}:{}})}return{archetype:n,available:t.length>0,candidates:t,hasDefault:t.some(r=>r.isDefault)}}function Yt(e,n=[$t],s={note:Nt}){const t=r=>Zt(n,String(r),s[String(r)]);return{availability:t,handlers:()=>[...new Set(n.flatMap(r=>r.tags.filter(i=>i[0]==="z").map(i=>i[1])))].map(t),handleInvoke(r,i){const o=i.request,l=t(o.archetype).candidates.filter(g=>g.conventions.includes(o.convention)),a=o.handler&&!["default","choose"].includes(o.handler),d=o.handler==="choose"?void 0:a?l.find(g=>g.id===o.handler):l.find(g=>g.isDefault)??l[0];if(!d)return p({type:"intent.invoke.result",id:i.id,result:{ok:!1,error:"no handler"}});const{archetype:h,action:u,convention:f}=o;return e(d.id,structuredClone({type:"intent.deliver",delivery:{sender:r.catalogId,archetype:h,action:u,convention:f,..."payload"in o?{payload:o.payload}:{}}})),p({type:"intent.invoke.result",id:i.id,result:{ok:!0,archetype:h,action:u,convention:f,handler:d.id}})}}}function Xt(e={}){const n=[],s=Jt(),t=Wt({now:e.now??Date.now,records:n,queueDelivery:s.queue,intents:Yt(s.queue,e.manifests,e.defaults)});return{get records(){return n},handle:r=>t(Bt,r),handleFrom:t,takeDeliveries:s.take,reset(){n.length=0,s.clear()}}}function Jt(){const e=new Map;return{queue(n,s){const t=e.get(n);t?t.push(s):e.set(n,[s])},take(n){const s=e.get(n)??[];return e.delete(n),s},clear(){e.clear()}}}function es(e){return{manifestHtml:e.manifestHtml,manifestEvent:e.manifestEvent??null,sandbox:e.sandbox??{allowScripts:!0,allowSameOrigin:!1},installedGlobal:e.boot.installedGlobal,bootError:e.boot.bootError,emitted:e.boot.emitted,forbiddenGlobals:e.forbiddenGlobals??[],degraded:e.boot.degraded,lifecycle:e.lifecycle??null}}var Wn="__nappletConformance.error",Vn="__nappletConformance.installed";function wn(e){return new Promise(n=>setTimeout(n,e))}function ns(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var ts=`(() => {
2
- const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
3
- const numberIn = (value, min, max) => typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max;
4
- const isGamepadState = (value) => {
5
- if (!record(value) || typeof value.available !== 'boolean' || typeof value.focused !== 'boolean' || !Array.isArray(value.pads)) return false;
6
- if (value.available) {
7
- if (value.reason !== undefined) return false;
8
- } else if (value.focused || (value.reason !== 'blocked' && value.reason !== 'unavailable')) return false;
9
- return Array.from(value.pads).every((pad) => {
10
- if (pad === null) return true;
11
- if (!record(pad) || !Number.isInteger(pad.index) || pad.index < 0 || typeof pad.id !== 'string' || typeof pad.mapping !== 'string' || pad.connected !== true) return false;
12
- if (typeof pad.timestamp !== 'number' || !Number.isFinite(pad.timestamp) || !Array.isArray(pad.axes) || !Array.isArray(pad.buttons)) return false;
13
- if (!value.focused && pad.timestamp !== 0) return false;
14
- if (!Array.from(pad.axes).every((axis) => numberIn(axis, -1, 1) && (value.focused || axis === 0))) return false;
15
- return Array.from(pad.buttons).every((button) => record(button) && numberIn(button.value, 0, 1) && typeof button.pressed === 'boolean' && typeof button.touched === 'boolean' && (value.focused || (button.value === 0 && !button.pressed && !button.touched)));
16
- });
17
- };
18
- const copyGamepadState = (state) => {
19
- const copy = { available: state.available, focused: state.focused };
20
- if (state.reason !== undefined) copy.reason = state.reason;
21
- copy.pads = state.pads.map((pad) => pad === null ? null : {
22
- index: pad.index, id: pad.id, mapping: pad.mapping, connected: pad.connected,
23
- timestamp: pad.timestamp, axes: pad.axes.slice(), buttons: pad.buttons.map((button) => ({ value: button.value, pressed: button.pressed, touched: button.touched })),
24
- });
25
- return copy;
26
- };
27
- return { isGamepadState, copyGamepadState };
28
- })()`;function ss(){return`(() => {
1
+ (function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))t(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&t(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function t(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();var $e=["shell","relay","identity","storage","inc","theme","keys","media","notify","config","resource","cvm","outbox","upload","intent","ble","webrtc","link","count","lists","serial","fs","common","dm","gamepad","llm"],u={id:"string"},Dt={"llm.select":{dir:"out",fields:{...u}},"llm.select.result":{dir:"in",fields:{...u}},"llm.describe":{dir:"out",fields:{...u,handle:"string"}},"llm.describe.result":{dir:"in",fields:{...u}},"llm.generate":{dir:"out",fields:{...u,request:"object"}},"llm.generate.result":{dir:"in",fields:{...u}},"llm.delta":{dir:"in",fields:{requestId:"string",sequence:"number",text:"string"}},"llm.cancel":{dir:"out",fields:{...u,requestId:"string"}},"llm.cancel.result":{dir:"in",fields:{...u}},"gamepad.subscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.unsubscribe":{dir:"out",forbiddenFields:["id"],forbiddenReason:"NAP-GAMEPAD fire-and-forget envelopes do not carry it"},"gamepad.state":{dir:"in",fields:{available:"boolean",focused:"boolean",pads:"array"}},"shell.ready":{dir:"out"},"shell.init":{dir:"in",fields:{capabilities:"object",services:"array"}},"relay.subscribe":{dir:"out",fields:{...u,subId:"string",filters:"array"}},"relay.close":{dir:"out",fields:{...u,subId:"string"}},"relay.publish":{dir:"out",fields:{...u,event:"object"}},"relay.publishEncrypted":{dir:"out",fields:{...u,event:"object",recipient:"string"}},"relay.query":{dir:"out",fields:{...u,filters:"array"}},"relay.event":{dir:"in"},"relay.eose":{dir:"in"},"relay.closed":{dir:"in"},"relay.publish.result":{dir:"in"},"relay.publishEncrypted.result":{dir:"in"},"relay.query.result":{dir:"in"},"identity.getPublicKey":{dir:"out",fields:{...u}},"identity.getRelays":{dir:"out",fields:{...u}},"identity.getProfile":{dir:"out",fields:{...u}},"identity.getFollows":{dir:"out",fields:{...u}},"identity.getList":{dir:"out",fields:{...u,listType:"string"}},"identity.getZaps":{dir:"out",fields:{...u}},"identity.getMutes":{dir:"out",fields:{...u}},"identity.getBlocked":{dir:"out",fields:{...u}},"identity.getBadges":{dir:"out",fields:{...u}},"identity.changed":{dir:"in"},"identity.getPublicKey.result":{dir:"in"},"identity.getRelays.result":{dir:"in"},"identity.getProfile.result":{dir:"in"},"identity.getFollows.result":{dir:"in"},"identity.getList.result":{dir:"in"},"identity.getZaps.result":{dir:"in"},"identity.getMutes.result":{dir:"in"},"identity.getBlocked.result":{dir:"in"},"identity.getBadges.result":{dir:"in"},"storage.get":{dir:"out",fields:{...u,key:"string"}},"storage.set":{dir:"out",fields:{...u,key:"string",value:"string"}},"storage.remove":{dir:"out",fields:{...u,key:"string"}},"storage.keys":{dir:"out",fields:{...u}},"storage.get.result":{dir:"in"},"storage.set.result":{dir:"in"},"storage.remove.result":{dir:"in"},"storage.keys.result":{dir:"in"},"inc.emit":{dir:"out",fields:{topic:"string"},forbiddenFields:["sender"]},"inc.subscribe":{dir:"out",fields:{...u,topic:"string"}},"inc.unsubscribe":{dir:"out",fields:{topic:"string"}},"inc.channel.open":{dir:"out",fields:{...u,target:"string"}},"inc.channel.emit":{dir:"out",fields:{channelId:"string"}},"inc.channel.broadcast":{dir:"out"},"inc.channel.list":{dir:"out",fields:{...u}},"inc.channel.close":{dir:"out",fields:{channelId:"string"}},"inc.subscribe.result":{dir:"in"},"inc.event":{dir:"in",fields:{topic:"string",sender:"string"}},"inc.channel.open.result":{dir:"in"},"inc.channel.opened":{dir:"in",fields:{channelId:"string",peer:"string"}},"inc.channel.event":{dir:"in"},"inc.channel.list.result":{dir:"in"},"inc.channel.closed":{dir:"in"},"theme.get":{dir:"out",fields:{...u}},"theme.get.result":{dir:"in"},"theme.changed":{dir:"in"},"keys.forward":{dir:"out",fields:{key:"string",code:"string",ctrl:"boolean",alt:"boolean",shift:"boolean",meta:"boolean"}},"keys.registerAction":{dir:"out",fields:{...u,action:"object"}},"keys.unregisterAction":{dir:"out",fields:{actionId:"string"}},"keys.registerAction.result":{dir:"in"},"keys.bindings":{dir:"in"},"keys.action":{dir:"in"},"media.session.create":{dir:"out",fields:{...u,owner:"object"}},"media.session.update":{dir:"out",fields:{sessionId:"string",metadata:"object"}},"media.session.destroy":{dir:"out",fields:{sessionId:"string"}},"media.state":{dir:"out",fields:{sessionId:"string",status:"string"}},"media.capabilities":{dir:"out",fields:{sessionId:"string",actions:"array"}},"media.session.create.result":{dir:"in"},"media.command":{dir:"in"},"media.controls":{dir:"in"},"notify.send":{dir:"out",fields:{...u,title:"string"}},"notify.dismiss":{dir:"out",fields:{notificationId:"string"}},"notify.badge":{dir:"out",fields:{count:"number"}},"notify.channel.register":{dir:"out",fields:{channelId:"string",label:"string"}},"notify.permission.request":{dir:"out",fields:{...u}},"notify.send.result":{dir:"in"},"notify.permission.result":{dir:"in"},"notify.action":{dir:"in"},"notify.clicked":{dir:"in"},"notify.dismissed":{dir:"in"},"notify.controls":{dir:"in"},"config.registerSchema":{dir:"out",fields:{...u,schema:"object"}},"config.get":{dir:"out",fields:{...u}},"config.subscribe":{dir:"out"},"config.unsubscribe":{dir:"out"},"config.openSettings":{dir:"out"},"config.registerSchema.result":{dir:"in"},"config.values":{dir:"in"},"config.schemaError":{dir:"in"},"resource.info":{dir:"out",fields:{...u}},"resource.bytes":{dir:"out",fields:{...u,url:"string"}},"resource.bytesMany":{dir:"out",fields:{...u,requests:"array"}},"resource.cancel":{dir:"out",fields:{...u}},"resource.info.result":{dir:"in"},"resource.info.error":{dir:"in"},"resource.bytes.result":{dir:"in"},"resource.bytes.error":{dir:"in"},"resource.bytesMany.result":{dir:"in"},"resource.bytesMany.error":{dir:"in"},"cvm.discover":{dir:"out",fields:{...u}},"cvm.request":{dir:"out",fields:{...u,server:"object",message:"object"}},"cvm.close":{dir:"out",fields:{...u,server:"object"}},"cvm.registry.list":{dir:"out",fields:{...u}},"cvm.registry.has":{dir:"out",fields:{...u,family:"string"}},"cvm.registry.describe":{dir:"out",fields:{...u,family:"string"}},"cvm.registry.call":{dir:"out",fields:{...u,family:"string",tool:"string"}},"cvm.discover.result":{dir:"in"},"cvm.request.result":{dir:"in"},"cvm.close.result":{dir:"in"},"cvm.event":{dir:"in"},"cvm.registry.list.result":{dir:"in"},"cvm.registry.has.result":{dir:"in"},"cvm.registry.describe.result":{dir:"in"},"cvm.registry.call.result":{dir:"in"},"outbox.getEvent":{dir:"out",fields:{...u,eventId:"string"}},"outbox.query":{dir:"out",fields:{...u,filters:"present"}},"outbox.subscribe":{dir:"out",fields:{...u,subId:"string",filters:"present"}},"outbox.close":{dir:"out",fields:{...u,subId:"string"}},"outbox.publish":{dir:"out",fields:{...u,event:"object"}},"outbox.resolveRelays":{dir:"out",fields:{...u,target:"present"}},"outbox.getEvent.result":{dir:"in"},"outbox.query.result":{dir:"in"},"outbox.event":{dir:"in"},"outbox.closed":{dir:"in"},"outbox.publish.result":{dir:"in"},"outbox.resolveRelays.result":{dir:"in"},"upload.info":{dir:"out",fields:{...u}},"upload.upload":{dir:"out",fields:{...u,request:"object"}},"upload.status":{dir:"out",fields:{...u,uploadId:"string"}},"upload.info.result":{dir:"in"},"upload.upload.result":{dir:"in"},"upload.status.result":{dir:"in"},"upload.status.changed":{dir:"in"},"intent.invoke":{dir:"out",fields:{...u,request:"object"}},"intent.available":{dir:"out",fields:{...u,archetype:"string"}},"intent.handlers":{dir:"out",fields:{...u}},"intent.invoke.result":{dir:"in",fields:{...u,result:"object"}},"intent.available.result":{dir:"in"},"intent.handlers.result":{dir:"in"},"intent.deliver":{dir:"in",fields:{delivery:"object"}},"intent.changed":{dir:"in"},"ble.open":{dir:"out",fields:{...u,request:"object"}},"ble.services":{dir:"out",fields:{...u,sessionId:"string"}},"ble.read":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.write":{dir:"out",fields:{...u,sessionId:"string",target:"object",data:"array"}},"ble.subscribe":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.unsubscribe":{dir:"out",fields:{...u,sessionId:"string",target:"object"}},"ble.close":{dir:"out",fields:{...u,sessionId:"string"}},"ble.open.result":{dir:"in"},"ble.services.result":{dir:"in"},"ble.read.result":{dir:"in"},"ble.write.result":{dir:"in"},"ble.subscribe.result":{dir:"in"},"ble.unsubscribe.result":{dir:"in"},"ble.close.result":{dir:"in"},"ble.event":{dir:"in"},"common.encodeNip19":{dir:"out",fields:{...u,input:"object"}},"common.decodeNip19":{dir:"out",fields:{...u,value:"string"}},"common.getProfile":{dir:"out",fields:{...u,target:"string"}},"common.follows":{dir:"out",fields:{...u}},"common.follow":{dir:"out",fields:{...u,pubkeys:"array"}},"common.unfollow":{dir:"out",fields:{...u,pubkeys:"array"}},"common.react":{dir:"out",fields:{...u,targetEventId:"string",reaction:"string"}},"common.report":{dir:"out",fields:{...u,target:"object",reason:"string",text:"string"}},"common.encodeNip19.result":{dir:"in"},"common.decodeNip19.result":{dir:"in"},"common.getProfile.result":{dir:"in"},"common.follows.result":{dir:"in"},"common.follow.result":{dir:"in"},"common.unfollow.result":{dir:"in"},"common.react.result":{dir:"in"},"common.report.result":{dir:"in"},"webrtc.open":{dir:"out",fields:{...u,request:"object"}},"webrtc.send":{dir:"out",fields:{...u,sessionId:"string",payload:"present"}},"webrtc.close":{dir:"out",fields:{...u,sessionId:"string"}},"webrtc.open.result":{dir:"in"},"webrtc.send.result":{dir:"in"},"webrtc.close.result":{dir:"in"},"webrtc.event":{dir:"in"},"link.open":{dir:"out",fields:{...u,url:"string"}},"link.open.result":{dir:"in"},"count.query":{dir:"out",fields:{...u,filters:"array"}},"count.query.result":{dir:"in"},"lists.supported":{dir:"out",fields:{...u}},"lists.add":{dir:"out",fields:{...u,list:"object",items:"array"}},"lists.remove":{dir:"out",fields:{...u,list:"object",items:"array"}},"lists.supported.result":{dir:"in"},"lists.add.result":{dir:"in"},"lists.remove.result":{dir:"in"},"serial.open":{dir:"out",fields:{...u,request:"object"}},"serial.write":{dir:"out",fields:{...u,sessionId:"string",data:"array"}},"serial.close":{dir:"out",fields:{...u,sessionId:"string"}},"serial.open.result":{dir:"in"},"serial.write.result":{dir:"in"},"serial.close.result":{dir:"in"},"serial.event":{dir:"in"},"fs.info":{dir:"out",fields:{...u}},"fs.pickFile":{dir:"out",fields:{...u}},"fs.pickFiles":{dir:"out",fields:{...u}},"fs.pickDirectory":{dir:"out",fields:{...u}},"fs.pickSaveFile":{dir:"out",fields:{...u}},"fs.stat":{dir:"out",fields:{...u,path:"string"}},"fs.list":{dir:"out",fields:{...u,path:"string"}},"fs.read":{dir:"out",fields:{...u,path:"string"}},"fs.write":{dir:"out",fields:{...u,path:"string",data:"string"}},"fs.mkdir":{dir:"out",fields:{...u,path:"string"}},"fs.remove":{dir:"out",fields:{...u,path:"string"}},"fs.move":{dir:"out",fields:{...u,fromPath:"string",toPath:"string"}},"fs.watch":{dir:"out",fields:{...u,path:"string"}},"fs.unwatch":{dir:"out",fields:{...u,watchId:"string"}},"fs.info.result":{dir:"in"},"fs.pickFile.result":{dir:"in"},"fs.pickFiles.result":{dir:"in"},"fs.pickDirectory.result":{dir:"in"},"fs.pickSaveFile.result":{dir:"in"},"fs.stat.result":{dir:"in"},"fs.list.result":{dir:"in"},"fs.read.result":{dir:"in"},"fs.write.result":{dir:"in"},"fs.mkdir.result":{dir:"in"},"fs.remove.result":{dir:"in"},"fs.move.result":{dir:"in"},"fs.watch.result":{dir:"in"},"fs.unwatch.result":{dir:"in"},"fs.changed":{dir:"in"},"dm.status":{dir:"out",fields:{...u}},"dm.conversations":{dir:"out",fields:{...u}},"dm.messages":{dir:"out",fields:{...u,conversationId:"string"}},"dm.send":{dir:"out",fields:{...u,recipients:"array",content:"string"}},"dm.subscribe":{dir:"out",fields:{...u}},"dm.unsubscribe":{dir:"out",fields:{...u,subscriptionId:"string"}},"dm.status.result":{dir:"in"},"dm.conversations.result":{dir:"in"},"dm.messages.result":{dir:"in"},"dm.send.result":{dir:"in"},"dm.subscribe.result":{dir:"in"},"dm.unsubscribe.result":{dir:"in"},"dm.message":{dir:"in"}},Bt=e=>typeof e=="string",we=e=>typeof e=="string"&&e.length>0,Rn=e=>typeof e=="boolean",Ee=(...e)=>n=>typeof n=="string"&&e.includes(n),Nt=e=>typeof e=="string"&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)&&e.length>=4;function _e(e,n={}){return s=>{if(typeof s!="object"||s===null||Array.isArray(s))return!1;const t=s;return Object.keys(t).some(r=>!(r in e)&&!(r in n))?!1:Object.entries(e).every(([r,i])=>i(t[r]))&&Object.entries(n).every(([r,i])=>t[r]===void 0||i(t[r]))}}var Qn=e=>n=>Array.isArray(n)&&n.length>0&&n.every(e),$t=_e({type:Ee("text"),text:Bt}),Lt=_e({type:Ee("image"),mimeType:Ee("image/png","image/jpeg","image/webp"),data:Nt}),Ft=e=>$t(e)||Lt(e),Wt=_e({role:Ee("system","user","assistant"),content:Qn(Ft)}),Gt=_e({},{model:we,images:Rn,json:Rn}),Vt=_e({handle:we,messages:Qn(Wt)},{format:Ee("text","json")}),zt={"llm.select":{optional:{requirements:Gt}},"llm.describe":{required:{handle:we}},"llm.generate":{required:{request:Vt}},"llm.cancel":{required:{requestId:we}}};function Qt(e,n,s){const t=zt[e];if(!t)return;const r=t.required??{},i=t.optional??{};n.id!==void 0&&!we(n.id)&&s.push({code:"wrong-type",field:"id",message:"NAP-LLM request ids are non-empty text"});for(const o of Object.keys(n))o==="type"||o==="id"||o in r||o in i||s.push({code:"forbidden-field",field:o,message:`Field "${o}" is not a parameter of ${e}; NAP-LLM requests carry exactly their API row parameters`});for(const[o,l]of Object.entries({...r,...i})){const a=n[o];if(a===void 0){o in r&&s.push({code:"missing-field",field:o,message:`Field "${o}" is required by ${e}`});continue}l(a)||s.push({code:"wrong-type",field:o,message:`Field "${o}" must match the NAP-LLM ${e} schema`})}}function Le(e){if(e===void 0)return"undefined";if(e===null)return"null";if(Array.isArray(e))return"array";const n=typeof e;return n==="string"||n==="number"||n==="boolean"?n:n==="object"?"object":"present"}function Kt(e,n){return n==="present"?e!=null:Le(e)===n}function Zt(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return;const s=e;typeof s.archetype!="string"&&n.push({code:s.archetype===void 0?"missing-field":"wrong-type",message:'Intent request requires a string "archetype" field',field:"request.archetype"});for(const r of["action","convention"])typeof s[r]!="string"&&n.push({code:s[r]===void 0?"missing-field":"wrong-type",message:`Intent request field "${r}" must be a string`,field:`request.${r}`});const t=typeof s.convention=="string"?/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(s.convention):null;(!t||t[1]!==s.archetype||t[2]!==s.action)&&n.push({code:"wrong-type",message:"Intent convention must be stable and match archetype and action",field:"request.convention"}),s.handler!==void 0&&typeof s.handler!="string"&&n.push({code:"wrong-type",message:'Intent request field "handler" must be a string',field:"request.handler"}),s.behavior!==void 0&&Le(s.behavior)!=="object"&&n.push({code:"wrong-type",message:'Intent request field "behavior" must be an object',field:"request.behavior"}),s.handlerHint!==void 0&&Yt(s.handlerHint,n),"sender"in s&&n.push({code:"forbidden-field",message:"Intent request does not define a caller-supplied sender field",field:"request.sender"})}function Yt(e,n){if(Le(e)!=="object"){n.push({code:"wrong-type",message:'Intent request field "handlerHint" must be an object',field:"request.handlerHint"});return}const{address:s,relays:t}=e;(typeof s!="string"||!/^35129:[0-9a-f]{64}:.+$/s.test(s))&&n.push({code:s===void 0?"missing-field":"wrong-type",message:'Intent handler hint "address" must be a 35129:<pubkey>:<d> coordinate',field:"request.handlerHint.address"}),t!==void 0&&!(Array.isArray(t)&&t.every(r=>typeof r=="string"))&&n.push({code:"wrong-type",message:'Intent handler hint "relays" must be an array of strings',field:"request.handlerHint.relays"})}function Kn(e,n,s){Array.isArray(e)&&e.every(t=>typeof t=="string")||s.push({code:"wrong-type",message:`Field "${n}" must be an array of strings`,field:n})}function Xt(e,n){e.servers!==void 0&&Kn(e.servers,"servers",n)}function Jt(e,n){if(Array.isArray(e)){if(e.length===0){n.push({code:"invalid-resource-request",message:'Field "requests" must contain at least one resource request',field:"requests"});return}for(const[s,t]of e.entries()){const r=`requests[${s}]`;if(typeof t!="object"||t===null||Array.isArray(t)){n.push({code:"invalid-resource-request",message:`Field "${r}" must be a resource request object`,field:r});continue}const i=t;typeof i.url!="string"&&n.push({code:i.url===void 0?"missing-field":"wrong-type",message:`Field "${r}.url" must be a string`,field:`${r}.url`}),i.servers!==void 0&&Kn(i.servers,`${r}.servers`,n)}}}function es(e){const n=[];if(typeof e!="object"||e===null||Array.isArray(e))return{ok:!1,errors:[{code:"not-an-object",message:"Envelope must be a non-null object"}]};const s=e,t=s.type;if(typeof t!="string")return{ok:!1,errors:[{code:"missing-type",message:"Envelope is missing a string `type` field"}]};const r=t.indexOf(".");if(r<=0)return{ok:!1,type:t,errors:[{code:"malformed-type",message:`Envelope type "${t}" is not in domain.action form`}]};const i=t.slice(0,r);if(!$e.includes(i))return{ok:!1,type:t,domain:i,errors:[{code:"unknown-domain",message:`"${i}" is not a known NAP domain`}]};const l=Dt[t];if(!l)return{ok:!1,type:t,domain:i,errors:[{code:"unknown-type",message:`"${t}" is not a known ${i} message type`}]};for(const[a,d]of Object.entries(l.fields??{})){if(!(a in s)||s[a]===void 0){n.push({code:"missing-field",message:`Required field "${a}" is missing`,field:a});continue}Kt(s[a],d)||n.push({code:"wrong-type",message:`Field "${a}" should be ${d} but is ${Le(s[a])}`,field:a})}if(l.dir==="in")return{ok:!1,type:t,domain:i,direction:"in",errors:[{code:"inbound-type-emitted",message:`"${t}" is a shell→napplet message; a napplet must not emit it`},...n]};for(const a of l.forbiddenFields??[])a in s&&n.push({code:"forbidden-field",message:`Field "${a}" cannot be emitted by a napplet: ${l.forbiddenReason??"it must be runtime-derived"}`,field:a});return i==="llm"&&Qt(t,s,n),t==="intent.invoke"&&Zt(s.request,n),t==="resource.bytes"&&Xt(s,n),t==="resource.bytesMany"&&Jt(s.requests,n),{ok:n.length===0,type:t,domain:i,direction:"out",errors:n}}var Zn=5129,ns=15129,ce=35129,gn=[Zn,ns,ce],Yn=["image/png","image/jpeg","image/webp"],Xn=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function Jn(e,n){return e.tags.find(s=>s[0]===n)}function ts(e){return gn.includes(e)}function Fe(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function et(e){return Jn(e,"d")?.[1]||void 0}function ss(e){return e.tags.filter(n=>n[0]==="R").map(n=>n[1]?.trim()??"").filter(Boolean)}function nt(e){return et(e)??Jn(e,"title")?.[1]??e.id}function rs(e){const n=[],s=[];for(const i of e.tags.filter(o=>o[0]==="screenshot")){const o=In(i,n);o&&s.push(o)}const t=e.tags.filter(i=>i[0]==="preview");let r;return t.length>1?n.push({code:"invalid-presentation-media",message:"Multiple preview tags; clients ignore the preview (NIP-5D §Presentation media)"}):t.length===1&&(r=In(t[0],n)),{screenshots:s,preview:r,warnings:n}}function In(e,n){const s=e[0],t=c=>{n.push({code:"invalid-presentation-media",message:`Ignore ${s} tag: ${c} (NIP-5D §Presentation media)`})},r=new Map;for(const c of e.slice(1)){const m=typeof c=="string"?c.indexOf(" "):-1,y=m<0?c:c.slice(0,m),w=m<0?void 0:c.slice(m+1),P=r.get(y)??[];w!==void 0?P.push(w):P.push(""),r.set(y,P)}const i=r.get("x");if(!i||i.length!==1||!Fe(i[0]))return t("exactly one x field with a lowercase sha256 is required");const o={sha256:i[0]},l=(c,m)=>{const y=r.get(c);if(y){if(y.length!==1||!m(y[0])){n.push({code:"invalid-presentation-media",message:`Ignore ${c} field on ${s} ${o.sha256}: malformed or repeated (NIP-5D §Presentation media)`});return}return y[0]}},a=l("m",c=>Xn.test(c));if(a!==void 0){if(!(s==="preview"?a.toLowerCase().startsWith("video/"):Yn.includes(a.toLowerCase())))return t(`${a} cannot match a decodable ${s==="preview"?"video":"PNG, JPEG or WebP"} format`);o.mimeType=a}const d=l("dim",c=>/^[1-9][0-9]*x[1-9][0-9]*$/.test(c));if(d!==void 0){const[c,m]=d.split("x").map(Number);o.dim={width:c,height:m}}const h=l("size",c=>/^(?:0|[1-9][0-9]*)$/.test(c));if(h!==void 0&&(o.size=Number(h)),s==="preview"){const c=l("duration",m=>/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(m));c!==void 0&&(o.duration=Number(c))}const f=l("alt",c=>c.trim().length>0);return f!==void 0&&(o.alt=f),o}function We(e){const n=[],s=[];if(!e)return{ok:!1,requires:[],optional:[],errors:[{code:"missing-manifest-event",message:"No NIP-5D manifest event was resolved"}],warnings:s};const t=et(e),r=ss(e);ts(e.kind)||n.push({code:"invalid-napplet-kind",message:`Manifest event kind ${e.kind} is not a NIP-5D napplet kind`});const i=e.tags.filter(l=>l[0]==="d");e.kind===ce&&(i.length!==1||!t)?n.push({code:"missing-d-tag",message:"Named manifests require exactly one non-empty d tag"}):e.kind!==ce&&i.length>0&&n.push({code:"unexpected-d-tag",message:"Only named manifests carry a d tag"});const o=e.tags.filter(l=>l[0]==="x");return(o.length!==1||o[0].length!==2||!Fe(o[0][1]))&&n.push({code:"invalid-artifact-hash",message:"Manifest requires exactly one x tag with the lowercase sha256 of /index.html"}),(typeof e.content!="string"||!e.content.trim())&&n.push({code:"missing-description",message:"Manifest content must contain a non-empty plain-text description"}),is(e,n,s),os(e,n,s),{ok:n.length===0,kind:e.kind,dTag:t,requires:r,optional:e.tags.filter(l=>l[0]==="O").map(l=>l[1]).filter(Boolean),errors:n,warnings:s}}function is(e,n,s){for(const t of e.tags.filter(r=>r[0]==="R"||r[0]==="O")){const r=t[1];t.length!==2||!r||/[.:\s]/.test(r)||r.startsWith("NAP-")?n.push({code:t[0]==="R"?"invalid-required-nap":"invalid-optional-nap",message:`${t[0]} must name one bare NAP domain`}):$e.includes(r)||s.push({code:"unknown-required-nap",message:`Domain "${r}" is not in this tool's registry; check its NAP and runtime availability`})}}function os(e,n,s){for(const i of["title","source","a","A"]){const o=e.tags.filter(l=>l[0]===i);(o.length>1||o.length&&(i==="a"||i==="A")&&e.kind!==Zn)&&n.push({code:"invalid-metadata",message:`Invalid ${i} tag cardinality for kind ${e.kind}`})}const t=e.tags.filter(i=>i[0]==="source");for(const i of t)(i.length!==2||!kn(i[1]))&&n.push({code:"invalid-metadata",message:"source must contain one HTTP(S), SSH, Git, SCP, or nostr repository location"});as(e,t.length===1&&t[0].length===2&&kn(t[0][1]),n,s);for(const i of e.tags.filter(o=>o[0]==="i"))(!i[1]?.trim()||i[1].includes("?"))&&n.push({code:"invalid-metadata",message:"Intent advertisements must be non-empty queryless identities"});const r=e.tags.filter(i=>i[0]==="icon");(r.length>1||r.some(i=>i.length!==3||!Fe(i[1])||!Yn.includes(i[2])))&&s.push({code:"invalid-icon",message:"Ignore invalid icon metadata and use generic artwork (NIP-5D §Icon)"}),s.push(...rs(e).warnings)}function as(e,n,s,t){const r=e.tags.filter(o=>o[0]==="source-commit");r.length>1||r.some(o=>o.length!==2||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(o[1]))?s.push({code:"invalid-metadata",message:"source-commit must appear once with a full lowercase-hex Git commit ID (40 or 64 characters)"}):r.length===1&&!n&&t.push({code:"unused-source-commit",message:"source-commit without a Git repository source is ignored (NIP-5D §Source)"});const i=e.tags.filter(o=>o[0]==="source-archive");(i.length>1||i.some(o=>o.length!==4||!ls(o[1])||!Fe(o[2])||!Xn.test(o[3]??"")))&&s.push({code:"invalid-metadata",message:"source-archive must appear once with an HTTPS URL without credentials or fragment, a lowercase sha256, and a MIME type"})}function ls(e){if(!e||e.includes("#"))return!1;try{const n=new URL(e);return n.protocol==="https:"&&!n.username&&!n.password}catch{return!1}}function kn(e){if(!e||/^[a-z]:[\\/]/i.test(e))return!1;try{const{protocol:n}=new URL(e);if(["http:","https:","ssh:","git:"].includes(n))return!0;if(n==="nostr:")return e.length>8&&e.startsWith("nostr://");if(n==="file:")return!1}catch{}return!e.includes("://")&&/^(?:[^@\s/:]+@)?[^:\s/]+:[^\s]+$/.test(e)}var de="f".repeat(64),ds={id:"reference-source-endpoint",catalogId:"reference-source"},cs="https://reference.invalid/blob",us=`named:${de}:reference-handler`,fs={kind:35129,pubkey:de,id:"0".repeat(64),tags:[["d","reference-handler"],["z","note"],["i","napplet:note/open","event"]]},ps="reference-subscriber",ms="napplet:note/open";function xe(e,n,s){return p({type:e,id:n,result:{entries:[s]}})}var p=e=>[e],j=()=>[];function xn(e){if(typeof e!="string"||!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return{blob:new Blob([],{type:"text/plain"}),mime:"text/plain"};const s=e.slice(5,n),t=e.slice(n+1),r=s.split(";").filter(Boolean),i=r.includes("base64"),o=r.find(l=>l.includes("/"))??"text/plain";try{if(i){const l=globalThis.atob(t),a=Uint8Array.from(l,d=>d.charCodeAt(0));return{blob:new Blob([a],{type:o}),mime:o}}return{blob:new Blob([decodeURIComponent(t)],{type:o}),mime:o}}catch{return null}}var gs={"gamepad.subscribe":()=>p({type:"gamepad.state",available:!1,reason:"unavailable",focused:!1,pads:[]}),"gamepad.unsubscribe":j,"relay.subscribe":e=>p({type:"relay.eose",subId:e.subId}),"relay.close":j,"relay.publish":e=>p({type:"relay.publish.result",id:e.id,ok:!0,event:e.event}),"relay.publishEncrypted":e=>p({type:"relay.publishEncrypted.result",id:e.id,ok:!0,event:e.event}),"relay.query":e=>p({type:"relay.query.result",id:e.id,events:[]}),"identity.getPublicKey":e=>p({type:"identity.getPublicKey.result",id:e.id,pubkey:de}),"identity.getRelays":e=>p({type:"identity.getRelays.result",id:e.id,relays:{}}),"identity.getProfile":e=>p({type:"identity.getProfile.result",id:e.id,profile:null}),"identity.getFollows":e=>p({type:"identity.getFollows.result",id:e.id,pubkeys:[]}),"identity.getList":e=>p({type:"identity.getList.result",id:e.id,entries:[]}),"identity.getZaps":e=>p({type:"identity.getZaps.result",id:e.id,zaps:[]}),"identity.getMutes":e=>p({type:"identity.getMutes.result",id:e.id,pubkeys:[]}),"identity.getBlocked":e=>p({type:"identity.getBlocked.result",id:e.id,pubkeys:[]}),"identity.getBadges":e=>p({type:"identity.getBadges.result",id:e.id,badges:[]}),"storage.get":e=>p({type:"storage.get.result",id:e.id,value:null}),"storage.set":e=>p({type:"storage.set.result",id:e.id}),"storage.remove":e=>p({type:"storage.remove.result",id:e.id}),"storage.keys":e=>p({type:"storage.keys.result",id:e.id,keys:[]}),"inc.emit":j,"inc.subscribe":e=>p({type:"inc.subscribe.result",id:e.id}),"inc.unsubscribe":j,"inc.channel.open":e=>p({type:"inc.channel.open.result",id:e.id,channelId:`chan-${String(e.id)}`,peer:"reference-peer"}),"inc.channel.emit":j,"inc.channel.broadcast":j,"inc.channel.list":e=>p({type:"inc.channel.list.result",id:e.id,channels:[]}),"inc.channel.close":j,"theme.get":e=>p({type:"theme.get.result",id:e.id,theme:{colors:{background:"#000000",text:"#ffffff",primary:"#663399"}}}),"keys.forward":j,"keys.registerAction":e=>p({type:"keys.registerAction.result",id:e.id,actionId:`action-${String(e.id)}`}),"keys.unregisterAction":j,"media.session.create":e=>p({type:"media.session.create.result",id:e.id,sessionId:`session-${String(e.id)}`,owner:e.owner}),"media.session.update":j,"media.session.destroy":j,"media.state":j,"media.capabilities":j,"notify.send":e=>p({type:"notify.send.result",id:e.id,notificationId:`notif-${String(e.id)}`}),"notify.dismiss":j,"notify.badge":j,"notify.channel.register":j,"notify.permission.request":e=>p({type:"notify.permission.result",id:e.id,granted:!0}),"config.registerSchema":e=>p({type:"config.registerSchema.result",id:e.id,ok:!0}),"config.get":e=>p({type:"config.values",id:e.id,values:{}}),"config.subscribe":()=>p({type:"config.values",values:{}}),"config.unsubscribe":j,"config.openSettings":j,"resource.bytes":e=>{const n=xn(e.url);return p(n?{type:"resource.bytes.result",id:e.id,blob:n.blob,mime:n.mime}:{type:"resource.bytes.result",id:e.id,blob:new Blob([]),mime:"application/octet-stream"})},"resource.bytesMany":e=>p({type:"resource.bytesMany.result",id:e.id,items:Array.isArray(e.requests)?e.requests.map(n=>{const s=typeof n=="object"&&n!==null&&!Array.isArray(n)?n.url:void 0,t=xn(s);return{url:typeof s=="string"?s:"",ok:!0,blob:t?.blob??new Blob([]),mime:t?.mime??"application/octet-stream"}}):[]}),"resource.info":e=>p({type:"resource.info.result",id:e.id,info:{schemes:[{scheme:"data",enabled:!0},{scheme:"https",enabled:!0}],maxServers:8}}),"resource.cancel":j,"cvm.discover":e=>p({type:"cvm.discover.result",id:e.id,servers:[]}),"cvm.request":e=>p({type:"cvm.request.result",id:e.id,message:{}}),"cvm.close":e=>p({type:"cvm.close.result",id:e.id}),"outbox.getEvent":e=>p({type:"outbox.getEvent.result",id:e.id}),"outbox.query":e=>p({type:"outbox.query.result",id:e.id,events:[]}),"outbox.subscribe":e=>p({type:"outbox.closed",subId:e.subId,reason:"reference shell complete"}),"outbox.close":j,"outbox.publish":e=>p({type:"outbox.publish.result",id:e.id,ok:!0}),"outbox.resolveRelays":e=>p({type:"outbox.resolveRelays.result",id:e.id,plan:{}}),"upload.info":e=>p({type:"upload.info.result",id:e.id,info:{rails:[{rail:"nip96",enabled:!0,returns:["https"]},{rail:"blossom",enabled:!0,returns:["https","blossom"]}]}}),"upload.upload":e=>p({type:"upload.upload.result",id:e.id,result:{url:cs}}),"upload.status":e=>p({type:"upload.status.result",id:e.id,status:{}}),"ble.open":e=>p({type:"ble.open.result",id:e.id,session:{id:"ble-reference",state:"open",device:{id:"reference-device",name:"Reference BLE"}}}),"ble.services":e=>p({type:"ble.services.result",id:e.id,services:[]}),"ble.read":e=>p({type:"ble.read.result",id:e.id,data:[]}),"ble.write":e=>p({type:"ble.write.result",id:e.id}),"ble.subscribe":e=>p({type:"ble.subscribe.result",id:e.id}),"ble.unsubscribe":e=>p({type:"ble.unsubscribe.result",id:e.id}),"ble.close":e=>p({type:"ble.close.result",id:e.id}),"common.encodeNip19":e=>p({type:"common.encodeNip19.result",id:e.id,ok:!0,value:"npub1reference",nip19Type:"npub"}),"common.decodeNip19":e=>p({type:"common.decodeNip19.result",id:e.id,ok:!0,nip19Type:"npub",hex:de}),"common.getProfile":e=>p({type:"common.getProfile.result",id:e.id,ok:!0,pubkey:de,profile:null}),"common.follows":e=>p({type:"common.follows.result",id:e.id,ok:!0,pubkeys:[]}),"common.follow":e=>p({type:"common.follow.result",id:e.id,ok:!0}),"common.unfollow":e=>p({type:"common.unfollow.result",id:e.id,ok:!0}),"common.react":e=>p({type:"common.react.result",id:e.id,ok:!0,eventId:"0".repeat(64)}),"common.report":e=>p({type:"common.report.result",id:e.id,ok:!0,eventId:"1".repeat(64)}),"webrtc.open":e=>p({type:"webrtc.open.result",id:e.id,session:{id:"webrtc-reference",scope:{type:"direct",pubkey:de},channel:"default",state:"connecting"}}),"webrtc.send":e=>p({type:"webrtc.send.result",id:e.id}),"webrtc.close":e=>p({type:"webrtc.close.result",id:e.id}),"link.open":e=>p({type:"link.open.result",id:e.id,status:"opened"}),"count.query":e=>p({type:"count.query.result",id:e.id,ok:!0,count:0}),"lists.supported":e=>p({type:"lists.supported.result",id:e.id,lists:[]}),"lists.add":e=>p({type:"lists.add.result",id:e.id,ok:!0,added:0,skipped:0}),"lists.remove":e=>p({type:"lists.remove.result",id:e.id,ok:!0,removed:0,skipped:0}),"serial.open":e=>p({type:"serial.open.result",id:e.id,session:{id:`serial-${String(e.id)}`,state:"open"}}),"serial.write":e=>p({type:"serial.write.result",id:e.id}),"serial.close":e=>p({type:"serial.close.result",id:e.id}),"fs.info":e=>p({type:"fs.info.result",id:e.id,info:{roots:[{path:"/shared",name:"Shared files",permissions:["read","list","write","create","delete","watch"]}],limits:{maxReadBytes:1048576,maxWriteBytes:1048576,maxWatchCount:16}}}),"fs.pickFile":e=>xe("fs.pickFile.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickFiles":e=>xe("fs.pickFiles.result",e.id,{path:"/picked/file.txt",kind:"file",name:"file.txt",permissions:["read"]}),"fs.pickDirectory":e=>xe("fs.pickDirectory.result",e.id,{path:"/picked",kind:"directory",name:"picked",permissions:["read","list"]}),"fs.pickSaveFile":e=>xe("fs.pickSaveFile.result",e.id,{path:"/picked/export.json",kind:"file",name:"export.json",permissions:["write","create"]}),"fs.stat":e=>p({type:"fs.stat.result",id:e.id,metadata:{path:e.path,kind:"file",size:0}}),"fs.list":e=>p({type:"fs.list.result",id:e.id,entries:[]}),"fs.read":e=>p({type:"fs.read.result",id:e.id,result:{data:"",offset:0,bytesRead:0,eof:!0,size:0}}),"fs.write":e=>p({type:"fs.write.result",id:e.id,result:{bytesWritten:0,size:0}}),"fs.mkdir":e=>p({type:"fs.mkdir.result",id:e.id}),"fs.remove":e=>p({type:"fs.remove.result",id:e.id}),"fs.move":e=>p({type:"fs.move.result",id:e.id}),"fs.watch":e=>p({type:"fs.watch.result",id:e.id,watchId:`watch-${String(e.id)}`}),"fs.unwatch":e=>p({type:"fs.unwatch.result",id:e.id})},tt={name:"Reference connection",model:"reference-model",route:"Reference shell → reference provider (no network)",images:!0,json:!0},be=(e,n)=>({error:{code:e,message:n}}),qe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{};function hs(e,n){let s=e.get(n.id);return s||(s={handles:new Set,active:new Map,sequence:0},e.set(n.id,s)),s}function st(e){return{handle:e,...tt}}function ys(e,n){const s=qe(n.requirements);if(s.model!==void 0&&s.model!==tt.model)return be("unsupported","No connection offers the requested model");e.sequence+=1;const t=`reference-llm-h${e.sequence}`;return e.handles.add(t),{model:st(t)}}function bs(e,n){const s=String(n.handle);return e.handles.has(s)?{model:st(s)}:be("selection-expired","Select a model again")}function vs(e){const n=Array.isArray(e.messages)?e.messages:[];let s="";for(const t of n){const r=qe(t);if(!(r.role!=="user"||!Array.isArray(r.content)))for(const i of r.content){const o=qe(i);o.type==="text"&&typeof o.text=="string"&&(s=o.text)}}return s}function ws(e,n,s){const t=a=>[{type:"llm.generate.result",id:n,...a}];if(e.active.has(n))return t(be("invalid-request","Request id is still active"));const r=qe(s.request);if(!e.handles.has(String(r.handle)))return t(be("selection-expired","Select a model again"));const i=vs(r);if(i.includes("[[decline]]"))return t(be("user-cancelled","The user declined disclosure"));if(i.includes("[[stall]]"))return e.active.set(n,s),[];if(i.includes("[[refuse]]"))return t({result:{text:"",finish:"refusal"}});const o=r.format==="json"?JSON.stringify({echo:i}):`Echo: ${i}`,l={inputTokens:JSON.stringify(r.messages).length,outputTokens:o.length};return[{type:"llm.delta",requestId:n,sequence:0,text:o.slice(0,Math.ceil(o.length/2))},...t({result:{text:o,finish:"stop",usage:l}})]}function Es(e,n,s){const t=String(s.requestId);return e.active.delete(t)?[{type:"llm.generate.result",id:t,error:{code:"cancelled",message:"Generation cancelled; provider charges may still apply."}},{type:"llm.cancel.result",id:n,cancelled:!0}]:[{type:"llm.cancel.result",id:n,cancelled:!1}]}function Ss(e,n,s){const t=String(s.type),r=String(s.id),i=hs(e,n);switch(t){case"llm.select":return[{type:"llm.select.result",id:r,...ys(i,s)}];case"llm.describe":return[{type:"llm.describe.result",id:r,...bs(i,s)}];case"llm.generate":return structuredClone(ws(i,r,s));case"llm.cancel":return Es(i,r,s);default:return[{type:`${t}.result`,id:r,error:{code:"invalid-request",message:`Unknown operation ${t}`}}]}}function Ts(){const e=new Map;return{handle:(n,s)=>Ss(e,n,s),reset(){e.clear()}}}function _s(e){const n=new Set,s=Ts();return Object.assign((r,i)=>{const o=Rs(i),l=es(i);if(e.records.push({envelope:i,verdict:l,timestamp:e.now()}),!o||!l.ok)return[];const a=r.domains??$e;if(!a.includes(o.slice(0,o.indexOf("."))))return[];if(o==="shell.ready")return n.has(r.id)?[]:(n.add(r.id),p({type:"shell.init",capabilities:{domains:[...a]},services:[]}));const d=i;if(o.startsWith("llm."))return s.handle(r,d);if(o==="intent.invoke")return e.intents.handleInvoke(r,d);if(o==="intent.available")return p({type:"intent.available.result",id:d.id,availability:e.intents.availability(d.archetype)});if(o==="intent.handlers")return p({type:"intent.handlers.result",id:d.id,handlers:e.intents.handlers()});if(o==="inc.emit")return Is(r,d,e.queueDelivery);const h=gs[o];return h?h(d):[]},{reset(){s.reset()}})}function Rs(e){if(!e||typeof e!="object")return;const n=e.type;return typeof n=="string"?n:void 0}function Is(e,n,s){if(n.topic!==ms)return[];const t={type:"inc.event",topic:n.topic,sender:e.id};return"payload"in n&&(t.payload=n.payload),s(ps,t),[]}function ks(e){return e.kind===5129?`snapshot:${e.id}`:e.kind===15129?`root:${e.pubkey}`:`named:${e.pubkey}:${e.tags.find(n=>n[0]==="d")?.[1]??""}`}function xs(e,n){if(!e.tags.some(t=>t[0]==="z"&&t[1]===n))return[];const s=[];for(const t of e.tags)t[0]!=="i"||/^napplet:([^/?#]+)\/([^/?#]+)$/.exec(t[1]??"")?.[1]!==n||s.push({convention:t[1],params:t.slice(2)});return s}function Ms(e,n,s){const t=[];for(const r of e){const i=xs(r,n);if(!i.length)continue;const o=r.tags.find(a=>a[0]==="title")?.[1],l=ks(r);t.push({id:l,...o?{title:o}:{},actions:[...new Set(i.map(({convention:a})=>a.slice(a.indexOf("/")+1)))],conventions:[...new Set(i.map(({convention:a})=>a))],contracts:i,...l===s?{isDefault:!0}:{}})}return{archetype:n,available:t.length>0,candidates:t,hasDefault:t.some(r=>r.isDefault)}}function Us(e,n=[fs],s={note:us}){const t=r=>Ms(n,String(r),s[String(r)]);return{availability:t,handlers:()=>[...new Set(n.flatMap(r=>r.tags.filter(i=>i[0]==="z").map(i=>i[1])))].map(t),handleInvoke(r,i){const o=i.request,l=t(o.archetype).candidates.filter(m=>m.conventions.includes(o.convention)),a=o.handler&&!["default","choose"].includes(o.handler),d=o.handler==="choose"?void 0:a?l.find(m=>m.id===o.handler):l.find(m=>m.isDefault)??l[0];if(!d)return p({type:"intent.invoke.result",id:i.id,result:{ok:!1,error:"no handler"}});const{archetype:h,action:f,convention:c}=o;return e(d.id,structuredClone({type:"intent.deliver",delivery:{sender:r.catalogId,archetype:h,action:f,convention:c,..."payload"in o?{payload:o.payload}:{}}})),p({type:"intent.invoke.result",id:i.id,result:{ok:!0,archetype:h,action:f,convention:c,handler:d.id}})}}}function Ps(e={}){const n=[],s=As(),t=_s({now:e.now??Date.now,records:n,queueDelivery:s.queue,intents:Us(s.queue,e.manifests,e.defaults)});return{get records(){return n},handle:r=>t(ds,r),handleFrom:t,takeDeliveries:s.take,reset(){n.length=0,t.reset(),s.clear()}}}function As(){const e=new Map;return{queue(n,s){const t=e.get(n);t?t.push(s):e.set(n,[s])},take(n){const s=e.get(n)??[];return e.delete(n),s},clear(){e.clear()}}}function js(e){return{manifestHtml:e.manifestHtml,manifestEvent:e.manifestEvent??null,sandbox:e.sandbox??{allowScripts:!0,allowSameOrigin:!1},installedGlobal:e.boot.installedGlobal,bootError:e.boot.bootError,emitted:e.boot.emitted,forbiddenGlobals:e.forbiddenGlobals??[],degraded:e.boot.degraded,lifecycle:e.lifecycle??null}}var rt="__nappletConformance.error",it="__nappletConformance.installed";function Mn(e){return new Promise(n=>setTimeout(n,e))}function qs(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Os(){return`(() => {
29
2
  const report = (reason) => {
30
- try { window.parent.postMessage({ type: '${Wn}', reason: String(reason && reason.message || reason) }, '*'); }
3
+ try { window.parent.postMessage({ type: '${rt}', reason: String(reason && reason.message || reason) }, '*'); }
31
4
  catch {}
32
5
  };
33
6
  window.addEventListener('error', (event) => report(event.error || event.message));
34
7
  window.addEventListener('unhandledrejection', (event) => report(event.reason));
35
- })();`}function rs(e,n){const s=`window.parent.postMessage({ type: '${Vn}', installed: !!window.napplet }, '*');`;return n!==void 0?`${n}
8
+ })();`}function Cs(e,n){const s=`window.parent.postMessage({ type: '${it}', installed: !!window.napplet }, '*');`;return`${n}
36
9
  ;globalThis.NappletShimPrelude.install(${JSON.stringify({domains:e})});
37
- ${s}`:`
38
- (() => {
39
- const domains = ${JSON.stringify(e)};
40
- const napplet = {};
41
- for (const domain of domains) {
42
- if (domain === 'resource' || domain === 'gamepad') napplet[domain] = {};
43
- }
44
- const gamepadTools = ${ts};
45
- let gamepadState = { available: true, focused: false, pads: [] };
46
- const gamepadHandlers = new Set();
47
- // Subscribe on first use, like the nap binding, so napplets that never touch
48
- // gamepad emit no gamepad traffic for checks to attribute to them.
49
- let gamepadSubscribed = false;
50
- const gamepadSubscribe = () => {
51
- if (gamepadSubscribed) return;
52
- gamepadSubscribed = true;
53
- window.parent.postMessage({ type: 'gamepad.subscribe' }, '*');
54
- };
55
- const pending = new Map();
56
- let seq = 0;
57
- const nextId = () => {
58
- try {
59
- if (window.crypto && typeof window.crypto.randomUUID === 'function') return window.crypto.randomUUID();
60
- } catch {}
61
- seq += 1;
62
- return 'conformance-' + Date.now().toString(36) + '-' + seq.toString(36);
63
- };
64
- const request = (message, resultType, errorType) => new Promise((resolve, reject) => {
65
- const id = message.id || nextId();
66
- const timeout = window.setTimeout(() => {
67
- pending.delete(id);
68
- reject(new Error(message.type + ' timed out'));
69
- }, 5000);
70
- pending.set(id, { resolve, reject, resultType, errorType, timeout });
71
- window.parent.postMessage({ ...message, id }, '*');
72
- });
73
- window.addEventListener('message', (event) => {
74
- if (event.source !== window.parent) return;
75
- const msg = event.data;
76
- if (gamepadSubscribed && msg && msg.type === 'gamepad.state' && !('id' in msg) && gamepadTools.isGamepadState(msg)) {
77
- gamepadState = gamepadTools.copyGamepadState(msg);
78
- const recipients = Array.from(gamepadHandlers);
79
- for (const entry of recipients) {
80
- if (!gamepadHandlers.has(entry)) continue;
81
- try { entry.handler(gamepadTools.copyGamepadState(gamepadState)); }
82
- catch (error) { queueMicrotask(() => { throw error; }); }
83
- }
84
- return;
85
- }
86
- if (!msg || typeof msg !== 'object' || typeof msg.id !== 'string') return;
87
- const slot = pending.get(msg.id);
88
- if (!slot) return;
89
- if (msg.type !== slot.resultType && msg.type !== slot.errorType) return;
90
- pending.delete(msg.id);
91
- window.clearTimeout(slot.timeout);
92
- if (msg.type === slot.errorType) {
93
- slot.reject(new Error(msg.message ? msg.error + ': ' + msg.message : String(msg.error || 'request failed')));
94
- return;
95
- }
96
- slot.resolve(msg);
97
- });
98
- if (napplet.gamepad) {
99
- napplet.gamepad = {
100
- get available() { gamepadSubscribe(); return gamepadState.available; },
101
- get focused() { gamepadSubscribe(); return gamepadState.focused; },
102
- getGamepads() { gamepadSubscribe(); return gamepadTools.copyGamepadState(gamepadState).pads; },
103
- onChange(handler) {
104
- const entry = { handler };
105
- gamepadHandlers.add(entry);
106
- gamepadSubscribe();
107
- return { close() { gamepadHandlers.delete(entry); } };
108
- },
109
- };
110
- }
111
- if (napplet.resource) {
112
- napplet.resource.info = () =>
113
- request({ type: 'resource.info' }, 'resource.info.result', 'resource.info.error')
114
- .then((msg) => msg.info);
115
- napplet.resource.bytes = (url, options) => {
116
- const message = { type: 'resource.bytes', url: String(url) };
117
- if (options && options.servers !== undefined) message.servers = options.servers;
118
- return request(message, 'resource.bytes.result', 'resource.bytes.error')
119
- .then((msg) => msg.blob);
120
- };
121
- napplet.resource.bytesMany = (requests) =>
122
- request({ type: 'resource.bytesMany', requests: Array.from(requests || []) }, 'resource.bytesMany.result', 'resource.bytesMany.error')
123
- .then((msg) => msg.items);
124
- napplet.resource.bytesAsObjectURL = (url) => {
125
- const handle = { url: '', revoke: () => {} };
126
- let objectUrl = '';
127
- let revoked = false;
128
- const ready = napplet.resource.bytes(url).then((blob) => {
129
- if (revoked) return;
130
- objectUrl = URL.createObjectURL(blob);
131
- handle.url = objectUrl;
132
- return objectUrl;
133
- });
134
- handle.revoke = () => {
135
- if (revoked) return;
136
- revoked = true;
137
- if (objectUrl) URL.revokeObjectURL(objectUrl);
138
- };
139
- Object.defineProperty(handle, 'ready', { value: ready, enumerable: false });
140
- return handle;
141
- };
142
- }
143
- window.napplet = napplet;
144
- ${s}
145
- })();
146
- `}function is(e,n,s,t){const r=`<base href="${ns(n)}">`,i=rs(s,t).replace(/<\/script/gi,"<\\/script"),o=`<script>${ss()}<\/script><script>${i}<\/script>`,l=/<head(?:\s[^>]*)?>/i.exec(e);if(l){const a=l.index+l[0].length;return`${e.slice(0,a)}${r}${o}${e.slice(a)}`}return`${r}${o}${e}`}function os(e){if(!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return"";const s=e.slice(0,n),t=e.slice(n+1);return s.endsWith(";base64")?atob(t):decodeURIComponent(t)}async function as(e){if(e==="about:blank")return"<!doctype html><html><head></head><body></body></html>";const n=os(e);if(n!==null)return n;const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch napplet HTML: ${s.status} ${s.statusText}`);return s.text()}async function En(e,n,s,t){const r=Xt(),i=s.createElement("iframe");i.setAttribute("sandbox",n.allowSameOrigin?"allow-scripts allow-same-origin":"allow-scripts"),i.setAttribute("allow","gamepad 'none'"),i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.width="1px",i.style.height="1px",i.style.left="-9999px";let o=null,l=!1;const a=u=>{if(u.source!==i.contentWindow)return;const f=u.data;if(f&&typeof f=="object"&&f.type===Vn){l=f.installed===!0;return}if(f&&typeof f=="object"&&f.type===Wn){o=`napplet boot error: ${String(f.reason??"unknown error")}`;return}const g=r.handle(u.data),b=u.source;for(const E of g)b?.postMessage(E,"*")};let d=!1;const h=new Promise(u=>{i.addEventListener("load",()=>{d=!0,u()},{once:!0})});t.addEventListener("message",a);try{const u=n.html??await as(n.url);i.srcdoc=is(u,n.url,e,n.runtimePreludeSource),(s.body??s.documentElement).appendChild(i)}catch(u){o=u instanceof Error?u.message:String(u)}if(!o){const u=Symbol("timeout");await Promise.race([h.then(()=>"loaded"),wn(n.readyTimeoutMs).then(()=>u)])===u||!d?o=`napplet did not boot (iframe did not load within ${n.readyTimeoutMs}ms; a conformant napplet must run under sandbox="allow-scripts" without allow-same-origin)`:await wn(n.settleMs)}t.removeEventListener("message",a);try{i.remove()}catch{}return{installedGlobal:l,bootError:o,emitted:[...r.records]}}async function ls(e){const n=e.document??document,s=e.window??window,t={url:e.url,html:e.html,readyTimeoutMs:e.readyTimeoutMs??5e3,settleMs:e.settleMs,allowSameOrigin:e.allowSameOrigin??!1,runtimePreludeSource:e.runtimePreludeSource},r=await En(Ce,t,n,s);let i=null;{const o=await En([],t,n,s);i={bootError:o.bootError,emitted:o.emitted}}return{installedGlobal:r.installedGlobal,bootError:r.bootError,emitted:r.emitted,degraded:i}}var ds=e=>({status:"pass",detail:e}),cs=(e,n)=>({status:"fail",detail:e,diagnostics:n}),us=e=>({status:"skip",detail:e}),P={pass:ds,fail:cs,skip:us};function ps(e,n){const s=Be(e.manifestEvent);return[...s.errors,...s.warnings].filter(t=>n.includes(t.code))}function Te(e,n,s,t="error"){return{id:e,area:"manifest",severity:t,title:n,run:r=>{if(!r.manifestEvent)return P.skip("No NIP-5D manifest event was resolved");const i=ps(r,s);return i.length?P.fail(i[0].message,i):P.pass()}}}var fs=[Te("manifest/event-kind","Resolved event is a NIP-5D napplet manifest",["invalid-napplet-kind","missing-d-tag","unexpected-d-tag"]),Te("manifest/index-html","Manifest declares a hashed /index.html",["invalid-artifact-hash","missing-description","invalid-metadata"]),Te("manifest/requires","R/O tags name bare NAP domains",["invalid-required-nap","invalid-optional-nap"]),Te("manifest/requires-known","R/O domains are in this toolchain registry (advisory)",["unknown-required-nap"],"warning"),{id:"boot/sandbox-allow-scripts",area:"boot",severity:"error",title:"Runs under allow-scripts without allow-same-origin",run:e=>e.sandbox.allowScripts?e.sandbox.allowSameOrigin?P.fail("Napplet relied on allow-same-origin, which a shell must not grant"):P.pass():P.fail("Napplet was not loaded with allow-scripts")},{id:"boot/installs-global",area:"boot",severity:"error",title:"Runs after runtime-injected window.napplet is installed",run:e=>e.installedGlobal?P.pass():P.fail("runtime did not inject window.napplet before load")},{id:"boot/no-boot-error",area:"boot",severity:"error",title:"Boots without an uncaught error",run:e=>e.bootError?P.fail(e.bootError):P.pass()},{id:"boot/no-forbidden-globals",area:"boot",severity:"error",title:"Does not access forbidden browser authority surfaces",run:e=>e.forbiddenGlobals.length?P.fail(`Accessed forbidden surface(s): ${e.forbiddenGlobals.join(", ")}`,e.forbiddenGlobals):P.pass()},{id:"wire/envelope-well-formed",area:"wire",severity:"error",title:"Every emitted envelope is well-formed",run:e=>{if(e.emitted.length===0)return P.skip("Napplet emitted no envelopes");const n=e.emitted.filter(t=>!t.verdict.ok);if(n.length===0)return P.pass(`${e.emitted.length} envelope(s) valid`);const s=n.map(t=>({envelope:t.envelope,errors:t.verdict.errors}));return P.fail(`${n.length}/${e.emitted.length} emitted envelope(s) invalid`,s)}},{id:"degrade/domain-absence",area:"degradation",severity:"error",title:"Does not crash when no NAP domains are injected",run:e=>e.degraded?e.degraded.bootError?P.fail(`Crashed with no injected domains: ${e.degraded.bootError}`):P.pass():P.skip("Host did not run the degraded (no-capabilities) pass")},{id:"lifecycle/clean-teardown",area:"lifecycle",severity:"warning",title:"Tears down listeners on unload",run:e=>e.lifecycle?e.lifecycle.listenerLeak?P.fail("Message listeners remained after unload"):P.pass():P.skip("Lifecycle not measured")}];function ms(e,n={}){const s=n.now??(()=>Date.now()),t=n.checks??fs,r=s(),i=t.map(a=>{const d=a.run(e);return{id:a.id,area:a.area,severity:a.severity,title:a.title,status:d.status,detail:d.detail,diagnostics:d.diagnostics}}),o={total:i.length,passed:i.filter(a=>a.status==="pass").length,failed:i.filter(a=>a.status==="fail").length,skipped:i.filter(a=>a.status==="skip").length,errors:i.filter(a=>a.status==="fail"&&a.severity==="error").length,warnings:i.filter(a=>a.status==="fail"&&a.severity==="warning").length};return{napplet:e.manifestEvent?Gn(e.manifestEvent):void 0,startedAt:r,finishedAt:s(),checks:i,summary:o,ok:o.errors===0}}function gs(e,n){const s=r=>e.tags.find(i=>i[0]===r)?.[1],t=e.tags.filter(r=>r[0]==="server").map(r=>r[1]).filter(Boolean);return[["event",e.id],["kind",e.kind],["d",s("d")],["name",Gn(e)],["requires",n.requires.join(", ")],["optional",n.optional.join(", ")],["artifact hash (x)",s("x")],["servers",t.join(", ")]]}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function cn(e,n=""){if(!Number.isSafeInteger(e)||e<0){const s=n&&`"${n}" `;throw new Error(`${s}expected integer >= 0, got ${e}`)}}function $(e,n,s=""){const t=hs(e),r=e?.length,i=n!==void 0;if(!t||i&&r!==n){const o=s&&`"${s}" `,l=i?` of length ${n}`:"",a=t?`length=${r}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+l+", got "+a)}return e}function Sn(e,n=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(n&&e.finished)throw new Error("Hash#digest() has already been called")}function ys(e,n){$(e,void 0,"digestInto() output");const s=n.outputLen;if(e.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Je(...e){for(let n=0;n<e.length;n++)e[n].fill(0)}function Ge(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function K(e,n){return e<<32-n|e>>>n}const Qn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",bs=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function C(e){if($(e),Qn)return e.toHex();let n="";for(let s=0;s<e.length;s++)n+=bs[e[s]];return n}const X={_0:48,_9:57,A:65,F:70,a:97,f:102};function _n(e){if(e>=X._0&&e<=X._9)return e-X._0;if(e>=X.A&&e<=X.F)return e-(X.A-10);if(e>=X.a&&e<=X.f)return e-(X.a-10)}function Y(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Qn)return Uint8Array.fromHex(e);const n=e.length,s=n/2;if(n%2)throw new Error("hex string expected, got unpadded hex of length "+n);const t=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=_n(e.charCodeAt(i)),l=_n(e.charCodeAt(i+1));if(o===void 0||l===void 0){const a=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+i)}t[r]=o*16+l}return t}function Me(...e){let n=0;for(let t=0;t<e.length;t++){const r=e[t];$(r),n+=r.length}const s=new Uint8Array(n);for(let t=0,r=0;t<e.length;t++){const i=e[t];s.set(i,r),r+=i.length}return s}function vs(e,n={}){const s=(r,i)=>e(i).update(r).digest(),t=e(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=r=>e(r),Object.assign(s,n),Object.freeze(s)}function zn(e=32){const n=typeof globalThis=="object"?globalThis.crypto:null;if(typeof n?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return n.getRandomValues(new Uint8Array(e))}const ws=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Kn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zn(e,n){return Array.isArray(n)?n.length===0?!0:e?n.every(s=>typeof s=="string"):n.every(s=>Number.isSafeInteger(s)):!1}function Es(e){if(typeof e!="function")throw new Error("function expected");return!0}function be(e,n){if(typeof n!="string")throw new Error(`${e}: string expected`);return!0}function Yn(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function en(e){if(!Array.isArray(e))throw new Error("array expected")}function Xn(e,n){if(!Zn(!0,n))throw new Error(`${e}: array of strings expected`)}function Jn(e,n){if(!Zn(!1,n))throw new Error(`${e}: array of numbers expected`)}function Ss(...e){const n=i=>i,s=(i,o)=>l=>i(o(l)),t=e.map(i=>i.encode).reduceRight(s,n),r=e.map(i=>i.decode).reduce(s,n);return{encode:t,decode:r}}function _s(e){const n=typeof e=="string"?e.split(""):e,s=n.length;Xn("alphabet",n);const t=new Map(n.map((r,i)=>[r,i]));return{encode:r=>(en(r),r.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=s)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return n[i]})),decode:r=>(en(r),r.map(i=>{be("alphabet.decode",i);const o=t.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function Ts(e=""){return be("join",e),{encode:n=>(Xn("join.decode",n),n.join(e)),decode:n=>(be("join.decode",n),n.split(e))}}const et=(e,n)=>n===0?e:et(n,e%n),Pe=(e,n)=>e+(n-et(e,n)),xe=(()=>{let e=[];for(let n=0;n<40;n++)e.push(2**n);return e})();function nn(e,n,s,t){if(en(e),n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(Pe(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${Pe(n,s)}`);let r=0,i=0;const o=xe[n],l=xe[s]-1,a=[];for(const d of e){if(Yn(d),d>=o)throw new Error(`convertRadix2: invalid data word=${d} from=${n}`);if(r=r<<n|d,i+n>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${n}`);for(i+=n;i>=s;i-=s)a.push((r>>i-s&l)>>>0);const h=xe[i];if(h===void 0)throw new Error("invalid carry");r&=h-1}if(r=r<<s-i&l,!t&&i>=n)throw new Error("Excess padding");if(!t&&r>0)throw new Error(`Non-zero padding: ${r}`);return t&&i>0&&a.push(r>>>0),a}function Rs(e,n=!1){if(Yn(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Pe(8,e)>32||Pe(e,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!Kn(s))throw new Error("radix2.encode input should be Uint8Array");return nn(Array.from(s),8,e,!n)},decode:s=>(Jn("radix2.decode",s),Uint8Array.from(nn(s,e,8,n)))}}function Tn(e){return Es(e),function(...n){try{return e.apply(null,n)}catch{}}}const tn=Ss(_s("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Ts("")),Rn=[996825010,642813549,513874426,1027748829,705979059];function me(e){const n=e>>25;let s=(e&33554431)<<5;for(let t=0;t<Rn.length;t++)(n>>t&1)===1&&(s^=Rn[t]);return s}function In(e,n,s=1){const t=e.length;let r=1;for(let i=0;i<t;i++){const o=e.charCodeAt(i);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);r=me(r)^o>>5}r=me(r);for(let i=0;i<t;i++)r=me(r)^e.charCodeAt(i)&31;for(let i of n)r=me(r)^i;for(let i=0;i<6;i++)r=me(r);return r^=s,tn.encode(nn([r%xe[30]],30,5,!1))}function Is(e){const n=e==="bech32"?1:734539939,s=Rs(5),t=s.decode,r=s.encode,i=Tn(t);function o(u,f,g=90){be("bech32.encode prefix",u),Kn(f)&&(f=Array.from(f)),Jn("bech32.encode",f);const b=u.length;if(b===0)throw new TypeError(`Invalid prefix length ${b}`);const E=b+7+f.length;if(g!==!1&&E>g)throw new TypeError(`Length ${E} exceeds limit ${g}`);const j=u.toLowerCase(),O=In(j,f,n);return`${j}1${tn.encode(f)}${O}`}function l(u,f=90){be("bech32.decode input",u);const g=u.length;if(g<8||f!==!1&&g>f)throw new TypeError(`invalid string length: ${g} (${u}). Expected (8..${f})`);const b=u.toLowerCase();if(u!==b&&u!==u.toUpperCase())throw new Error("String must be lowercase or uppercase");const E=b.lastIndexOf("1");if(E===0||E===-1)throw new Error('Letter "1" must be present between prefix and data only');const j=b.slice(0,E),O=b.slice(E+1);if(O.length<6)throw new Error("Data must be at least 6 characters long");const Q=tn.decode(O).slice(0,-6),J=In(j,Q,n);if(!O.endsWith(J))throw new Error(`Invalid checksum in ${u}: expected "${J}"`);return{prefix:j,words:Q}}const a=Tn(l);function d(u){const{prefix:f,words:g}=l(u,!1);return{prefix:f,words:g,bytes:t(g)}}function h(u,f){return o(u,r(f))}return{encode:o,decode:l,encodeFromBytes:h,decodeToBytes:d,decodeUnsafe:a,fromWords:t,fromWordsUnsafe:i,toWords:r}}const kn=Is("bech32");var Re=new TextDecoder("utf-8");new TextEncoder;var ks=5e3;function xs(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),Us(e)}catch{return{type:"invalid",data:null}}}function Us(e){let{prefix:n,words:s}=kn.decode(e,ks),t=new Uint8Array(kn.fromWords(s));switch(n){case"nprofile":{let r=We(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(r[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:C(r[0][0]),relays:r[1]?r[1].map(i=>Re.decode(i)):[]}}}case"nevent":{let r=We(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for nevent");if(r[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(r[2]&&r[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(r[3]&&r[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:C(r[0][0]),relays:r[1]?r[1].map(i=>Re.decode(i)):[],author:r[2]?.[0]?C(r[2][0]):void 0,kind:r[3]?.[0]?parseInt(C(r[3][0]),16):void 0}}}case"naddr":{let r=We(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!r[2]?.[0])throw new Error("missing TLV 2 for naddr");if(r[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!r[3]?.[0])throw new Error("missing TLV 3 for naddr");if(r[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Re.decode(r[0][0]),pubkey:C(r[2][0]),kind:parseInt(C(r[3][0]),16),relays:r[1]?r[1].map(i=>Re.decode(i)):[]}}}case"nsec":return{type:n,data:t};case"npub":case"note":return{type:n,data:C(t)};default:throw new Error(`unknown prefix ${n}`)}}function We(e){let n={},s=e;for(;s.length>0;){let t=s[0],r=s[1],i=s.slice(2,2+r);if(s=s.slice(2+r),i.length<r)throw new Error(`not enough data to read on TLV ${t}`);n[t]=n[t]||[],n[t].push(i)}return n}function Ms(e,n,s){return e&n^~e&s}function Ps(e,n,s){return e&n^e&s^n&s}class As{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(n,s,t,r){this.blockLen=n,this.outputLen=s,this.padOffset=t,this.isLE=r,this.buffer=new Uint8Array(n),this.view=Ge(this.buffer)}update(n){Sn(this),$(n);const{view:s,buffer:t,blockLen:r}=this,i=n.length;for(let o=0;o<i;){const l=Math.min(r-this.pos,i-o);if(l===r){const a=Ge(n);for(;r<=i-o;o+=r)this.process(a,o);continue}t.set(n.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=n.length,this.roundClean(),this}digestInto(n){Sn(this),ys(n,this),this.finished=!0;const{buffer:s,view:t,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,Je(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(t,0),o=0);for(let u=o;u<r;u++)s[u]=0;t.setBigUint64(r-8,BigInt(this.length*8),i),this.process(t,0);const l=Ge(n),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const d=a/4,h=this.get();if(d>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<d;u++)l.setUint32(4*u,h[u],i)}digest(){const{buffer:n,outputLen:s}=this;this.digestInto(n);const t=n.slice(0,s);return this.destroy(),t}_cloneInto(n){n||=new this.constructor,n.set(...this.get());const{blockLen:s,buffer:t,length:r,finished:i,destroyed:o,pos:l}=this;return n.destroyed=o,n.finished=i,n.length=r,n.pos=l,r%s&&n.buffer.set(t),n}clone(){return this._cloneInto()}}const ee=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),js=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ne=new Uint32Array(64);class Os extends As{constructor(n){super(64,n,8,!1)}get(){const{A:n,B:s,C:t,D:r,E:i,F:o,G:l,H:a}=this;return[n,s,t,r,i,o,l,a]}set(n,s,t,r,i,o,l,a){this.A=n|0,this.B=s|0,this.C=t|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=a|0}process(n,s){for(let u=0;u<16;u++,s+=4)ne[u]=n.getUint32(s,!1);for(let u=16;u<64;u++){const f=ne[u-15],g=ne[u-2],b=K(f,7)^K(f,18)^f>>>3,E=K(g,17)^K(g,19)^g>>>10;ne[u]=E+ne[u-7]+b+ne[u-16]|0}let{A:t,B:r,C:i,D:o,E:l,F:a,G:d,H:h}=this;for(let u=0;u<64;u++){const f=K(l,6)^K(l,11)^K(l,25),g=h+f+Ms(l,a,d)+js[u]+ne[u]|0,E=(K(t,2)^K(t,13)^K(t,22))+Ps(t,r,i)|0;h=d,d=a,a=l,l=o+g|0,o=i,i=r,r=t,t=g+E|0}t=t+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,a=a+this.F|0,d=d+this.G|0,h=h+this.H|0,this.set(t,r,i,o,l,a,d,h)}roundClean(){Je(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),Je(this.buffer)}}class qs extends Os{A=ee[0]|0;B=ee[1]|0;C=ee[2]|0;D=ee[3]|0;E=ee[4]|0;F=ee[5]|0;G=ee[6]|0;H=ee[7]|0;constructor(){super(32)}}const Ae=vs(()=>new qs,ws(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const un=BigInt(0),sn=BigInt(1);function xn(e,n=""){if(typeof e!="boolean"){const s=n&&`"${n}" `;throw new Error(s+"expected boolean, got type="+typeof e)}return e}function Cs(e){if(typeof e=="bigint"){if(!Ds(e))throw new Error("positive bigint expected, got "+e)}else cn(e);return e}function nt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?un:BigInt("0x"+e)}function pn(e){return nt(C(e))}function tt(e){return nt(C(Hs($(e)).reverse()))}function fn(e,n){cn(n),e=Cs(e);const s=Y(e.toString(16).padStart(n*2,"0"));if(s.length!==n)throw new Error("number too large");return s}function st(e,n){return fn(e,n).reverse()}function Hs(e){return Uint8Array.from(e)}function Bs(e){return Uint8Array.from(e,(n,s)=>{const t=n.charCodeAt(0);if(n.length!==1||t>127)throw new Error(`string contains non-ASCII character "${e[s]}" with code ${t} at position ${s}`);return t})}const Ds=e=>typeof e=="bigint"&&un<=e;function Ns(e){let n;for(n=0;e>un;e>>=sn,n+=1);return n}const rt=e=>(sn<<BigInt(e))-sn;function it(e,n={},s={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function t(i,o,l){const a=e[i];if(l&&a===void 0)return;const d=typeof a;if(d!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${d}`)}const r=(i,o)=>Object.entries(i).forEach(([l,a])=>t(l,a,o));r(n,!1),r(s,!0)}function Un(e){const n=new WeakMap;return(s,...t)=>{const r=n.get(s);if(r!==void 0)return r;const i=e(s,...t);return n.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const N=BigInt(0),D=BigInt(1),ie=BigInt(2),ot=BigInt(3),at=BigInt(4),lt=BigInt(5),$s=BigInt(7),dt=BigInt(8),Ls=BigInt(9),ct=BigInt(16);function V(e,n){const s=e%n;return s>=N?s:n+s}function F(e,n,s){let t=e;for(;n-- >N;)t*=t,t%=s;return t}function Mn(e,n){if(e===N)throw new Error("invert: expected non-zero number");if(n<=N)throw new Error("invert: expected positive modulus, got "+n);let s=V(e,n),t=n,r=N,i=D;for(;s!==N;){const l=t/s,a=t%s,d=r-i*l;t=s,s=a,r=i,i=d}if(t!==D)throw new Error("invert: does not exist");return V(r,n)}function mn(e,n,s){if(!e.eql(e.sqr(n),s))throw new Error("Cannot find square root")}function ut(e,n){const s=(e.ORDER+D)/at,t=e.pow(n,s);return mn(e,t,n),t}function Fs(e,n){const s=(e.ORDER-lt)/dt,t=e.mul(n,ie),r=e.pow(t,s),i=e.mul(n,r),o=e.mul(e.mul(i,ie),r),l=e.mul(i,e.sub(o,e.ONE));return mn(e,l,n),l}function Gs(e){const n=De(e),s=pt(e),t=s(n,n.neg(n.ONE)),r=s(n,t),i=s(n,n.neg(t)),o=(e+$s)/ct;return(l,a)=>{let d=l.pow(a,o),h=l.mul(d,t);const u=l.mul(d,r),f=l.mul(d,i),g=l.eql(l.sqr(h),a),b=l.eql(l.sqr(u),a);d=l.cmov(d,h,g),h=l.cmov(f,u,b);const E=l.eql(l.sqr(h),a),j=l.cmov(d,h,E);return mn(l,j,a),j}}function pt(e){if(e<ot)throw new Error("sqrt is not defined for small field");let n=e-D,s=0;for(;n%ie===N;)n/=ie,s++;let t=ie;const r=De(e);for(;Pn(r,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return ut;let i=r.pow(t,n);const o=(n+D)/ie;return function(a,d){if(a.is0(d))return d;if(Pn(a,d)!==1)throw new Error("Cannot find square root");let h=s,u=a.mul(a.ONE,i),f=a.pow(d,n),g=a.pow(d,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let b=1,E=a.sqr(f);for(;!a.eql(E,a.ONE);)if(b++,E=a.sqr(E),b===h)throw new Error("Cannot find square root");const j=D<<BigInt(h-b-1),O=a.pow(u,j);h=b,u=a.sqr(O),f=a.mul(f,u),g=a.mul(g,O)}return g}}function Ws(e){return e%at===ot?ut:e%dt===lt?Fs:e%ct===Ls?Gs(e):pt(e)}const Vs=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qs(e){const n={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Vs.reduce((t,r)=>(t[r]="function",t),n);return it(e,s),e}function zs(e,n,s){if(s<N)throw new Error("invalid exponent, negatives unsupported");if(s===N)return e.ONE;if(s===D)return n;let t=e.ONE,r=n;for(;s>N;)s&D&&(t=e.mul(t,r)),r=e.sqr(r),s>>=D;return t}function ft(e,n,s=!1){const t=new Array(n.length).fill(s?e.ZERO:void 0),r=n.reduce((o,l,a)=>e.is0(l)?o:(t[a]=o,e.mul(o,l)),e.ONE),i=e.inv(r);return n.reduceRight((o,l,a)=>e.is0(l)?o:(t[a]=e.mul(o,t[a]),e.mul(o,l)),i),t}function Pn(e,n){const s=(e.ORDER-D)/ie,t=e.pow(n,s),r=e.eql(t,e.ONE),i=e.eql(t,e.ZERO),o=e.eql(t,e.neg(e.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Ks(e,n){n!==void 0&&cn(n);const s=n!==void 0?n:e.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Zs{ORDER;BITS;BYTES;isLE;ZERO=N;ONE=D;_lengths;_sqrt;_mod;constructor(n,s={}){if(n<=N)throw new Error("invalid field: expected ORDER > 0, got "+n);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=s.allowedLengths?.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:r,nByteLength:i}=Ks(n,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=n,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(n){return V(n,this.ORDER)}isValid(n){if(typeof n!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof n);return N<=n&&n<this.ORDER}is0(n){return n===N}isValidNot0(n){return!this.is0(n)&&this.isValid(n)}isOdd(n){return(n&D)===D}neg(n){return V(-n,this.ORDER)}eql(n,s){return n===s}sqr(n){return V(n*n,this.ORDER)}add(n,s){return V(n+s,this.ORDER)}sub(n,s){return V(n-s,this.ORDER)}mul(n,s){return V(n*s,this.ORDER)}pow(n,s){return zs(this,n,s)}div(n,s){return V(n*Mn(s,this.ORDER),this.ORDER)}sqrN(n){return n*n}addN(n,s){return n+s}subN(n,s){return n-s}mulN(n,s){return n*s}inv(n){return Mn(n,this.ORDER)}sqrt(n){return this._sqrt||(this._sqrt=Ws(this.ORDER)),this._sqrt(this,n)}toBytes(n){return this.isLE?st(n,this.BYTES):fn(n,this.BYTES)}fromBytes(n,s=!1){$(n);const{_lengths:t,BYTES:r,isLE:i,ORDER:o,_mod:l}=this;if(t){if(!t.includes(n.length)||n.length>r)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+n.length);const d=new Uint8Array(r);d.set(n,i?0:d.length-n.length),n=d}if(n.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+n.length);let a=i?tt(n):pn(n);if(l&&(a=V(a,o)),!s&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(n){return ft(this,n)}cmov(n,s,t){return t?s:n}}function De(e,n={}){return new Zs(e,n)}function mt(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function Ys(e){const n=mt(e);return n+Math.ceil(n/2)}function Xs(e,n,s=!1){$(e);const t=e.length,r=mt(n),i=Ys(n);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?tt(e):pn(e),l=V(o,n-D)+D;return s?st(l,r):fn(l,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ue=BigInt(0),oe=BigInt(1);function je(e,n){const s=n.negate();return e?s:n}function An(e,n){const s=ft(e.Fp,n.map(t=>t.Z));return n.map((t,r)=>e.fromAffine(t.toAffine(s[r])))}function gt(e,n){if(!Number.isSafeInteger(e)||e<=0||e>n)throw new Error("invalid window size, expected [1.."+n+"], got W="+e)}function Ve(e,n){gt(e,n);const s=Math.ceil(n/e)+1,t=2**(e-1),r=2**e,i=rt(e),o=BigInt(e);return{windows:s,windowSize:t,mask:i,maxNumber:r,shiftBy:o}}function jn(e,n,s){const{windowSize:t,mask:r,maxNumber:i,shiftBy:o}=s;let l=Number(e&r),a=e>>o;l>t&&(l-=i,a+=oe);const d=n*t,h=d+Math.abs(l)-1,u=l===0,f=l<0,g=n%2!==0;return{nextN:a,offset:h,isZero:u,isNeg:f,isNegF:g,offsetF:d}}const Qe=new WeakMap,ht=new WeakMap;function ze(e){return ht.get(e)||1}function On(e){if(e!==ue)throw new Error("invalid wNAF")}class Js{BASE;ZERO;Fn;bits;constructor(n,s){this.BASE=n.BASE,this.ZERO=n.ZERO,this.Fn=n.Fn,this.bits=s}_unsafeLadder(n,s,t=this.ZERO){let r=n;for(;s>ue;)s&oe&&(t=t.add(r)),r=r.double(),s>>=oe;return t}precomputeWindow(n,s){const{windows:t,windowSize:r}=Ve(s,this.bits),i=[];let o=n,l=o;for(let a=0;a<t;a++){l=o,i.push(l);for(let d=1;d<r;d++)l=l.add(o),i.push(l);o=l.double()}return i}wNAF(n,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Ve(n,this.bits);for(let l=0;l<o.windows;l++){const{nextN:a,offset:d,isZero:h,isNeg:u,isNegF:f,offsetF:g}=jn(t,l,o);t=a,h?i=i.add(je(f,s[g])):r=r.add(je(u,s[d]))}return On(t),{p:r,f:i}}wNAFUnsafe(n,s,t,r=this.ZERO){const i=Ve(n,this.bits);for(let o=0;o<i.windows&&t!==ue;o++){const{nextN:l,offset:a,isZero:d,isNeg:h}=jn(t,o,i);if(t=l,!d){const u=s[a];r=r.add(h?u.negate():u)}}return On(t),r}getPrecomputes(n,s,t){let r=Qe.get(s);return r||(r=this.precomputeWindow(s,n),n!==1&&(typeof t=="function"&&(r=t(r)),Qe.set(s,r))),r}cached(n,s,t){const r=ze(n);return this.wNAF(r,this.getPrecomputes(r,n,t),s)}unsafe(n,s,t,r){const i=ze(n);return i===1?this._unsafeLadder(n,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,n,t),s,r)}createCache(n,s){gt(s,this.bits),ht.set(n,s),Qe.delete(n)}hasCache(n){return ze(n)!==1}}function er(e,n,s,t){let r=n,i=e.ZERO,o=e.ZERO;for(;s>ue||t>ue;)s&oe&&(i=i.add(r)),t&oe&&(o=o.add(r)),r=r.double(),s>>=oe,t>>=oe;return{p1:i,p2:o}}function qn(e,n,s){if(n){if(n.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Qs(n),n}else return De(e,{isLE:s})}function nr(e,n,s={},t){if(t===void 0&&(t=e==="edwards"),!n||typeof n!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const d=n[a];if(!(typeof d=="bigint"&&d>ue))throw new Error(`CURVE.${a} must be positive bigint`)}const r=qn(n.p,s.Fp,t),i=qn(n.n,s.Fn,t),l=["Gx","Gy","a","b"];for(const a of l)if(!r.isValid(n[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return n=Object.freeze(Object.assign({},n)),{CURVE:n,Fp:r,Fn:i}}function tr(e,n){return function(t){const r=e(t);return{secretKey:r,publicKey:n(r)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Cn=(e,n)=>(e+(e>=0?n:-n)/rr)/n;function sr(e,n,s){const[[t,r],[i,o]]=n,l=Cn(o*e,s),a=Cn(-r*e,s);let d=e-l*t-a*i,h=-l*r-a*o;const u=d<ge,f=h<ge;u&&(d=-d),f&&(h=-h);const g=rt(Math.ceil(Ns(s)/2))+Ue;if(d<ge||d>=g||h<ge||h>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:d,k2neg:f,k2:h}}const ge=BigInt(0),Ue=BigInt(1),rr=BigInt(2),Ie=BigInt(3),ir=BigInt(4);function or(e,n={}){const s=nr("weierstrass",e,n),{Fp:t,Fn:r}=s;let i=s.CURVE;const{h:o,n:l}=i;it(n,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:a}=n;if(a&&(!t.is0(i.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const d=lr(t,r);function h(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(k,m,y){const{x:w,y:S}=m.toAffine(),x=t.toBytes(w);if(xn(y,"isCompressed"),y){h();const R=!t.isOdd(S);return Me(ar(R),x)}else return Me(Uint8Array.of(4),x,t.toBytes(S))}function f(k){$(k,void 0,"Point");const{publicKey:m,publicKeyUncompressed:y}=d,w=k.length,S=k[0],x=k.subarray(1);if(w===m&&(S===2||S===3)){const R=t.fromBytes(x);if(!t.isValid(R))throw new Error("bad point: is not on curve, wrong x");const _=E(R);let v;try{v=t.sqrt(_)}catch(L){const q=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}h();const T=t.isOdd(v);return(S&1)===1!==T&&(v=t.neg(v)),{x:R,y:v}}else if(w===y&&S===4){const R=t.BYTES,_=t.fromBytes(x.subarray(0,R)),v=t.fromBytes(x.subarray(R,R*2));if(!j(_,v))throw new Error("bad point: is not on curve");return{x:_,y:v}}else throw new Error(`bad point: got length ${w}, expected compressed=${m} or uncompressed=${y}`)}const g=n.toBytes||u,b=n.fromBytes||f;function E(k){const m=t.sqr(k),y=t.mul(m,k);return t.add(t.add(y,t.mul(k,i.a)),i.b)}function j(k,m){const y=t.sqr(m),w=E(k);return t.eql(y,w)}if(!j(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const O=t.mul(t.pow(i.a,Ie),ir),Q=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(O,Q)))throw new Error("bad curve params: a or b");function J(k,m,y=!1){if(!t.isValid(m)||y&&t.is0(m))throw new Error(`bad point coordinate ${k}`);return m}function we(k){if(!(k instanceof M))throw new Error("Weierstrass Point expected")}function Ee(k){if(!a||!a.basises)throw new Error("no endo");return sr(k,a.basises,r.ORDER)}const Se=Un((k,m)=>{const{X:y,Y:w,Z:S}=k;if(t.eql(S,t.ONE))return{x:y,y:w};const x=k.is0();m==null&&(m=x?t.ONE:t.inv(S));const R=t.mul(y,m),_=t.mul(w,m),v=t.mul(S,m);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:R,y:_}}),Tt=Un(k=>{if(k.is0()){if(n.allowInfinityPoint&&!t.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:m,y}=k.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not field elements");if(!j(m,y))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function yn(k,m,y,w,S){return y=new M(t.mul(y.X,k),y.Y,y.Z),m=je(w,m),y=je(S,y),m.add(y)}class M{static BASE=new M(i.Gx,i.Gy,t.ONE);static ZERO=new M(t.ZERO,t.ONE,t.ZERO);static Fp=t;static Fn=r;X;Y;Z;constructor(m,y,w){this.X=J("x",m),this.Y=J("y",y,!0),this.Z=J("z",w),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof M)throw new Error("projective point not allowed");return t.is0(y)&&t.is0(w)?M.ZERO:new M(y,w,t.ONE)}static fromBytes(m){const y=M.fromAffine(b($(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return M.fromBytes(Y(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return fe.createCache(this,m),y||this.multiply(Ie),this}assertValidity(){Tt(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){we(m);const{X:y,Y:w,Z:S}=this,{X:x,Y:R,Z:_}=m,v=t.eql(t.mul(y,_),t.mul(x,S)),T=t.eql(t.mul(w,_),t.mul(R,S));return v&&T}negate(){return new M(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:y}=i,w=t.mul(y,Ie),{X:S,Y:x,Z:R}=this;let _=t.ZERO,v=t.ZERO,T=t.ZERO,I=t.mul(S,S),L=t.mul(x,x),q=t.mul(R,R),U=t.mul(S,x);return U=t.add(U,U),T=t.mul(S,R),T=t.add(T,T),_=t.mul(m,T),v=t.mul(w,q),v=t.add(_,v),_=t.sub(L,v),v=t.add(L,v),v=t.mul(_,v),_=t.mul(U,_),T=t.mul(w,T),q=t.mul(m,q),U=t.sub(I,q),U=t.mul(m,U),U=t.add(U,T),T=t.add(I,I),I=t.add(T,I),I=t.add(I,q),I=t.mul(I,U),v=t.add(v,I),q=t.mul(x,R),q=t.add(q,q),I=t.mul(q,U),_=t.sub(_,I),T=t.mul(q,L),T=t.add(T,T),T=t.add(T,T),new M(_,v,T)}add(m){we(m);const{X:y,Y:w,Z:S}=this,{X:x,Y:R,Z:_}=m;let v=t.ZERO,T=t.ZERO,I=t.ZERO;const L=i.a,q=t.mul(i.b,Ie);let U=t.mul(y,x),G=t.mul(w,R),W=t.mul(S,_),ae=t.add(y,w),B=t.add(x,R);ae=t.mul(ae,B),B=t.add(U,G),ae=t.sub(ae,B),B=t.add(y,S);let z=t.add(x,_);return B=t.mul(B,z),z=t.add(U,W),B=t.sub(B,z),z=t.add(w,S),v=t.add(R,_),z=t.mul(z,v),v=t.add(G,W),z=t.sub(z,v),I=t.mul(L,B),v=t.mul(q,W),I=t.add(v,I),v=t.sub(G,I),I=t.add(G,I),T=t.mul(v,I),G=t.add(U,U),G=t.add(G,U),W=t.mul(L,W),B=t.mul(q,B),G=t.add(G,W),W=t.sub(U,W),W=t.mul(L,W),B=t.add(B,W),U=t.mul(G,B),T=t.add(T,U),U=t.mul(z,B),v=t.mul(ae,v),v=t.sub(v,U),U=t.mul(ae,G),I=t.mul(z,I),I=t.add(I,U),new M(v,T,I)}subtract(m){return this.add(m.negate())}is0(){return this.equals(M.ZERO)}multiply(m){const{endo:y}=n;if(!r.isValidNot0(m))throw new Error("invalid scalar: out of range");let w,S;const x=R=>fe.cached(this,R,_=>An(M,_));if(y){const{k1neg:R,k1:_,k2neg:v,k2:T}=Ee(m),{p:I,f:L}=x(_),{p:q,f:U}=x(T);S=L.add(U),w=yn(y.beta,I,q,R,v)}else{const{p:R,f:_}=x(m);w=R,S=_}return An(M,[w,S])[0]}multiplyUnsafe(m){const{endo:y}=n,w=this;if(!r.isValid(m))throw new Error("invalid scalar: out of range");if(m===ge||w.is0())return M.ZERO;if(m===Ue)return w;if(fe.hasCache(this))return this.multiply(m);if(y){const{k1neg:S,k1:x,k2neg:R,k2:_}=Ee(m),{p1:v,p2:T}=er(M,w,x,_);return yn(y.beta,v,T,S,R)}else return fe.unsafe(w,m)}toAffine(m){return Se(this,m)}isTorsionFree(){const{isTorsionFree:m}=n;return o===Ue?!0:m?m(M,this):fe.unsafe(this,l).is0()}clearCofactor(){const{clearCofactor:m}=n;return o===Ue?this:m?m(M,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return xn(m,"isCompressed"),this.assertValidity(),g(M,this,m)}toHex(m=!0){return C(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const bn=r.BITS,fe=new Js(M,n.endo?Math.ceil(bn/2):bn);return M.BASE.precompute(8),M}function ar(e){return Uint8Array.of(e?2:3)}function lr(e,n){return{secretKey:n.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*n.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ne={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},dr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},cr=BigInt(0),rn=BigInt(2);function ur(e){const n=Ne.p,s=BigInt(3),t=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),l=BigInt(44),a=BigInt(88),d=e*e*e%n,h=d*d*e%n,u=F(h,s,n)*h%n,f=F(u,s,n)*h%n,g=F(f,rn,n)*d%n,b=F(g,r,n)*g%n,E=F(b,i,n)*b%n,j=F(E,l,n)*E%n,O=F(j,a,n)*j%n,Q=F(O,l,n)*E%n,J=F(Q,s,n)*h%n,we=F(J,o,n)*b%n,Ee=F(we,t,n)*d%n,Se=F(Ee,rn,n);if(!Oe.eql(Oe.sqr(Se),e))throw new Error("Cannot find square root");return Se}const Oe=De(Ne.p,{sqrt:ur}),pe=or(Ne,{Fp:Oe,endo:dr}),Hn={};function qe(e,...n){let s=Hn[e];if(s===void 0){const t=Ae(Bs(e));s=Me(t,t),Hn[e]=s}return Ae(Me(s,...n))}const gn=e=>e.toBytes(!0).slice(1),hn=e=>e%rn===cr;function on(e){const{Fn:n,BASE:s}=pe,t=n.fromBytes(e),r=s.multiply(t);return{scalar:hn(r.y)?t:n.neg(t),bytes:gn(r)}}function yt(e){const n=Oe;if(!n.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const s=n.create(e*e),t=n.create(s*e+BigInt(7));let r=n.sqrt(t);hn(r)||(r=n.neg(r));const i=pe.fromAffine({x:e,y:r});return i.assertValidity(),i}const ye=pn;function bt(...e){return pe.Fn.create(ye(qe("BIP0340/challenge",...e)))}function Bn(e){return on(e).bytes}function pr(e,n,s=zn(32)){const{Fn:t}=pe,r=$(e,void 0,"message"),{bytes:i,scalar:o}=on(n),l=$(s,32,"auxRand"),a=t.toBytes(o^ye(qe("BIP0340/aux",l))),d=qe("BIP0340/nonce",a,i,r),{bytes:h,scalar:u}=on(d),f=bt(h,i,r),g=new Uint8Array(64);if(g.set(h,0),g.set(t.toBytes(t.create(u+f*o)),32),!vt(g,r,i))throw new Error("sign: Invalid signature produced");return g}function vt(e,n,s){const{Fp:t,Fn:r,BASE:i}=pe,o=$(e,64,"signature"),l=$(n,void 0,"message"),a=$(s,32,"publicKey");try{const d=yt(ye(a)),h=ye(o.subarray(0,32));if(!t.isValidNot0(h))return!1;const u=ye(o.subarray(32,64));if(!r.isValidNot0(u))return!1;const f=bt(r.toBytes(h),gn(d),l),g=i.multiplyUnsafe(u).add(d.multiplyUnsafe(r.neg(f))),{x:b,y:E}=g.toAffine();return!(g.is0()||!hn(E)||b!==h)}catch{return!1}}const Z=(()=>{const s=(t=zn(48))=>Xs(t,Ne.n);return{keygen:tr(s,Bn),getPublicKey:Bn,sign:pr,verify:vt,Point:pe,utils:{randomSecretKey:s,taggedHash:qe,lift_x:yt,pointToBytes:gn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var re=Symbol("verified"),fr=e=>e instanceof Object;function mr(e){if(!fr(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let s=e.tags[n];if(!Array.isArray(s))return!1;for(let t=0;t<s.length;t++)if(typeof s[t]!="string")return!1}return!0}new TextDecoder("utf-8");var gr=new TextEncoder;function he(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let n=new URL(e);return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),n.pathname=n.pathname.replace(/\/+/g,"/"),n.pathname.endsWith("/")&&(n.pathname=n.pathname.slice(0,-1)),(n.port==="80"&&n.protocol==="ws:"||n.port==="443"&&n.protocol==="wss:")&&(n.port=""),n.searchParams.sort(),n.hash="",n.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}var hr=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(n){return C(Z.getPublicKey(n))}finalizeEvent(n,s){const t=n;return t.pubkey=C(Z.getPublicKey(s)),t.id=Ke(t),t.sig=C(Z.sign(Y(Ke(t)),s)),t[re]=!0,t}verifyEvent(n){if(typeof n[re]=="boolean")return n[re];try{const s=Ke(n);if(s!==n.id)return n[re]=!1,!1;const t=Z.verify(Y(n.sig),Y(s),Y(n.pubkey));return n[re]=t,t}catch{return n[re]=!1,!1}}};function yr(e){if(!mr(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function Ke(e){let n=Ae(gr.encode(yr(e)));return C(n)}var $e=new hr;$e.generateSecretKey;$e.getPublicKey;$e.finalizeEvent;var br=$e.verifyEvent,vr=22242;function wr(e,n){if(e.ids&&e.ids.indexOf(n.id)===-1||e.kinds&&e.kinds.indexOf(n.kind)===-1||e.authors&&e.authors.indexOf(n.pubkey)===-1)return!1;for(let s in e)if(s[0]==="#"){let t=s.slice(1),r=e[`#${t}`];if(r&&!n.tags.find(([i,o])=>i===s.slice(1)&&r.indexOf(o)!==-1))return!1}return!(e.since&&n.created_at<e.since||e.until&&n.created_at>e.until)}function Er(e,n){for(let s=0;s<e.length;s++)if(wr(e[s],n))return!0;return!1}function Sr(e,n){let s=n.length+3,t=e.indexOf(`"${n}":`)+s,r=e.slice(t).indexOf('"')+t+1;return e.slice(r,r+64)}function _r(e){let n=e.slice(0,22).indexOf('"EVENT"');if(n===-1)return null;let s=e.slice(n+7+1).indexOf('"');if(s===-1)return null;let t=n+7+1+s,r=e.slice(t+1,80).indexOf('"');if(r===-1)return null;let i=t+1+r;return e.slice(t+1,i)}function Tr(e,n){return{kind:vr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",n]],content:""}}var wt=class extends Error{constructor(e,n){super(`Tried to send message '${e} on a closed connection to ${n}.`),this.name="SendingOnClosedConnection"}},Et=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(e,n){this.url=he(e),this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation||WebSocket,this.enablePing=n.enablePing,this.enableReconnect=n.enableReconnect||!1}static async connect(e,n){const s=new Et(e,n);return await s.connect(n),s}closeAllSubscriptions(e){for(let[n,s]of this.openSubs)s.close(e);this.openSubs.clear();for(let[n,s]of this.openEventPublishes)s.reject(new Error(e));this.openEventPublishes.clear();for(let[n,s]of this.openCountRequests)s.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(e))}async connect(e){let n;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((s,t)=>{e?.timeout&&(n=setTimeout(()=>{t("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},e.timeout)),e?.abort&&(e.abort.onabort=t);try{this.ws=new this._WebSocket(this.url)}catch(r){clearTimeout(n),t(r);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(n),this._connected=!0;const r=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const i of this.openSubs.values()){if(i.eosed=!1,r)for(let o=0;o<i.filters.length;o++)i.lastEmitted&&(i.filters[o].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),s()},this.ws.onerror=()=>{clearTimeout(n),t("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=r=>{clearTimeout(n),t(r.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,n)=>{if(!this.connectionPromise)return n(new Error(`no connection to ${this.url}, can't ping`));try{const s=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),s.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(s){n(s)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(n=>setTimeout(()=>n(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(e){if(!this.connectionPromise)throw new wt(e,this.url);this.connectionPromise.then(()=>{this.ws?.send(e)})}async auth(e){const n=this.challenge;if(!n)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(s,t)=>{try{let r=await e(Tr(this.url,n)),i=setTimeout(()=>{let o=this.openEventPublishes.get(r.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(r.id))},this.publishTimeout);this.openEventPublishes.set(r.id,{resolve:s,reject:t,timeout:i}),this.send('["AUTH",'+JSON.stringify(r)+"]")}catch(r){console.warn("subscribe auth function failed:",r)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.ongoingOperations++;const n=new Promise((s,t)=>{const r=setTimeout(()=>{const i=this.openEventPublishes.get(e.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:s,reject:t,timeout:r})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),n}async count(e,n){this.serial++;const s=n?.id||"count:"+this.serial,t=new Promise((r,i)=>{this.openCountRequests.set(s,{resolve:r,reject:i})});return this.send('["COUNT","'+s+'",'+JSON.stringify(e).substring(1)),t}subscribe(e,n){n.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const s=this.prepareSubscription(e,n);return s.fire(),n.abort&&(n.abort.onabort=()=>s.close(String(n.abort.reason||"<aborted>"))),s}prepareSubscription(e,n){this.serial++;const s=n.id||(n.label?n.label+":":"sub:")+this.serial,t=new Rr(this,s,e,n);return this.openSubs.set(s,t),t}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(e){const n=e.data;if(!n)return;const s=_r(n);if(s){const t=this.openSubs.get(s);if(!t)return;const r=Sr(n,"id"),i=t.alreadyHaveEvent?.(r);if(t.receivedEvent?.(this,r),i)return}try{let t=JSON.parse(n);switch(t[0]){case"EVENT":{const r=this.openSubs.get(t[1]),i=t[2];this.verifyEvent(i)&&Er(r.filters,i)?r.onevent(i):r.oninvalidevent?.(i),(!r.lastEmitted||r.lastEmitted<i.created_at)&&(r.lastEmitted=i.created_at);return}case"COUNT":{const r=t[1],i=t[2],o=this.openCountRequests.get(r);o&&(o.resolve(i.count),this.openCountRequests.delete(r));return}case"EOSE":{const r=this.openSubs.get(t[1]);if(!r)return;r.receivedEose();return}case"OK":{const r=t[1],i=t[2],o=t[3],l=this.openEventPublishes.get(r);l&&(clearTimeout(l.timeout),i?l.resolve(o):l.reject(new Error(o)),this.openEventPublishes.delete(r));return}case"CLOSED":{const r=t[1],i=this.openSubs.get(r);if(!i)return;i.closed=!0,i.close(t[2]);return}case"NOTICE":{this.onnotice(t[1]);return}case"AUTH":{this.challenge=t[1],this.onauth&&this.auth(this.onauth);return}default:{this.openSubs.get(t[1])?.oncustom?.(t);return}}}catch(t){try{const[r,i,o]=JSON.parse(n);console.warn(`[nostr] relay ${this.url} error processing message:`,t,o)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,t)}return}}},Rr=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,n,s,t){if(s.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=s,this.id=n,this.alreadyHaveEvent=t.alreadyHaveEvent,this.receivedEvent=t.receivedEvent,this.eoseTimeout=t.eoseTimeout||e.baseEoseTimeout,this.oneose=t.oneose,this.onclose=t.onclose,this.oninvalidevent=t.oninvalidevent,this.onevent=t.onevent||(r=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,r)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(n){if(!(n instanceof wt))throw n}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(e)}},Ir=e=>(e[re]=!0,!0),kr=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;automaticallyAuth;trustedRelayURLs=new Set;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(e){this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,n){e=he(e);let s=this.relays.get(e);if(s||(s=new Et(e,{verifyEvent:this.trustedRelayURLs.has(e)?Ir:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),s.onclose=()=>{this.relays.delete(e)},this.relays.set(e,s)),this.automaticallyAuth){const t=this.automaticallyAuth(e);t&&(s.onauth=t)}try{await s.connect({timeout:n?.connectionTimeout,abort:n?.abort})}catch(t){throw this.relays.delete(e),t}return s}close(e){e.map(he).forEach(n=>{this.relays.get(n)?.close(),this.relays.delete(n)})}subscribe(e,n,s){const t=[],r=[];for(let i=0;i<e.length;i++){const o=he(e[i]);t.find(l=>l.url===o)||r.indexOf(o)===-1&&(r.push(o),t.push({url:o,filter:n}))}return this.subscribeMap(t,s)}subscribeMany(e,n,s){return this.subscribe(e,n,s)}subscribeMap(e,n){const s=new Map;for(const f of e){const{url:g,filter:b}=f;s.has(g)||s.set(g,[]),s.get(g).push(b)}const t=Array.from(s.entries()).map(([f,g])=>({url:f,filters:g}));this.trackRelays&&(n.receivedEvent=(f,g)=>{let b=this.seenOn.get(g);b||(b=new Set,this.seenOn.set(g,b)),b.add(f)});const r=new Set,i=[],o=[];let l=f=>{o[f]||(o[f]=!0,o.filter(g=>g).length===t.length&&(n.oneose?.(),l=()=>{}))};const a=[];let d=(f,g)=>{a[f]||(l(f),a[f]=g,a.filter(b=>b).length===t.length&&(n.onclose?.(a),d=()=>{}))};const h=f=>{if(n.alreadyHaveEvent?.(f))return!0;const g=r.has(f);return r.add(f),g},u=Promise.all(t.map(async({url:f,filters:g},b)=>{if(this.allowConnectingToRelay?.(f,["read",g])===!1){d(b,"connection skipped by allowConnectingToRelay");return}let E;try{E=await this.ensureRelay(f,{connectionTimeout:this.maxWaitForConnection<(n.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n.abort})}catch(O){this.onRelayConnectionFailure?.(f),d(b,O?.message||String(O));return}this.onRelayConnectionSuccess?.(f);let j=E.subscribe(g,{...n,oneose:()=>l(b),onclose:O=>{O.startsWith("auth-required: ")&&n.onauth?E.auth(n.onauth).then(()=>{E.subscribe(g,{...n,oneose:()=>l(b),onclose:Q=>{d(b,Q)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort})}).catch(Q=>{d(b,`auth was required and attempted, but failed with: ${Q}`)}):d(b,O)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort});i.push(j)}));return{async close(f){await u,i.forEach(g=>{g.close(f)})}}}subscribeEose(e,n,s){let t;return t=this.subscribe(e,n,{...s,oneose(){const r="closed automatically on eose";t?t.close(r):s.onclose?.(e.map(i=>r))}}),t}subscribeManyEose(e,n,s){return this.subscribeEose(e,n,s)}async querySync(e,n,s){return new Promise(async t=>{const r=[];this.subscribeEose(e,n,{...s,onevent(i){r.push(i)},onclose(i){t(r)}})})}async get(e,n,s){n.limit=1;const t=await this.querySync(e,n,s);return t.sort((r,i)=>i.created_at-r.created_at),t[0]||null}publish(e,n,s){return e.map(he).map(async(t,r,i)=>{if(i.indexOf(t)!==r)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(t,["write",n])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(t,{connectionTimeout:this.maxWaitForConnection<(s?.maxWait||0)?Math.max(s.maxWait*.8,s.maxWait-1e3):this.maxWaitForConnection,abort:s?.abort})}catch(l){return this.onRelayConnectionFailure?.(t),"connection failure: "+String(l)}return o.publish(n).catch(async l=>{if(l instanceof Error&&l.message.startsWith("auth-required: ")&&s?.onauth)return await o.auth(s.onauth),o.publish(n);throw l}).then(l=>{if(this.trackRelays){let a=this.seenOn.get(n.id);a||(a=new Set,this.seenOn.set(n.id,a)),a.add(o)}return l})})}listConnectionStatus(){const e=new Map;return this.relays.forEach((n,s)=>e.set(s,n.connected)),e}destroy(){this.relays.forEach(e=>e.close()),this.relays=new Map}pruneIdleRelays(e=1e4){const n=[];for(const[s,t]of this.relays)t.idleSince&&Date.now()-t.idleSince>=e&&(this.relays.delete(s),n.push(s),t.close());return n}},St;try{St=WebSocket}catch{}var xr=class extends kr{constructor(e){super({verifyEvent:br,websocketImplementation:St,maxWaitForConnection:3e3,...e})}},le=Symbol("verified"),Ur=e=>e instanceof Object;function Mr(e){if(!Ur(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let s=e.tags[n];if(!Array.isArray(s))return!1;for(let t=0;t<s.length;t++)if(typeof s[t]!="string")return!1}return!0}new TextDecoder("utf-8");var Pr=new TextEncoder,Ar=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(e){return C(Z.getPublicKey(e))}finalizeEvent(e,n){const s=e;return s.pubkey=C(Z.getPublicKey(n)),s.id=Ze(s),s.sig=C(Z.sign(Y(Ze(s)),n)),s[le]=!0,s}verifyEvent(e){if(typeof e[le]=="boolean")return e[le];try{const n=Ze(e);if(n!==e.id)return e[le]=!1,!1;const s=Z.verify(Y(e.sig),Y(n),Y(e.pubkey));return e[le]=s,s}catch{return e[le]=!1,!1}}};function jr(e){if(!Mr(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function Ze(e){let n=Ae(Pr.encode(jr(e)));return C(n)}var Le=new Ar;Le.generateSecretKey;Le.getPublicKey;Le.finalizeEvent;var Or=Le.verifyEvent;const qr=8e3;function Cr(e){return typeof e=="number"&&dn.includes(e)}function Hr(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function Br(e){const n=[];for(const s of e??[])try{const t=new URL(s);if(t.protocol!=="ws:"&&t.protocol!=="wss:")continue;n.push(t.href)}catch{}return[...new Set(n)]}function Dr(e){const n=xs(e.trim());if(n.type!=="nevent"&&n.type!=="naddr")throw new Error("Enter a NIP-19 nevent or naddr for a NIP-5D napplet manifest event");const s=Br(n.data.relays);if(s.length===0)throw new Error("The pointer does not include relay hints; include at least one relay in the nevent/naddr");if(n.type==="nevent"){if(n.data.kind!==void 0&&!Cr(n.data.kind))throw new Error(`nevent points at kind ${n.data.kind}, not a NIP-5D napplet manifest kind`);return{type:"nevent",relays:s,filter:{ids:[n.data.id],kinds:n.data.kind===void 0?[...dn]:[n.data.kind],authors:n.data.author?[n.data.author]:void 0,limit:1}}}if(n.data.kind!==ce)throw new Error(`naddr kind ${n.data.kind} is not the named napplet kind ${ce}`);return{type:"naddr",relays:s,filter:{kinds:[ce],authors:[n.data.pubkey],"#d":[n.data.identifier],limit:1}}}function Nr(e){return{id:e.id,pubkey:e.pubkey,kind:e.kind,tags:e.tags,content:e.content}}async function $r(e){const n=typeof e=="string"?new TextEncoder().encode(e):e,s=new Uint8Array(n.byteLength);s.set(n);const t=await crypto.subtle.digest("SHA-256",s.buffer);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}function Lr(e){const n=[];for(const s of e.tags)if(!(s[0]!=="server"||!s[1]))try{const t=new URL(s[1]);(t.protocol==="http:"||t.protocol==="https:")&&n.push(t.href)}catch{}return[...new Set(n)]}function Fr(e,n){const s=e.endsWith("/")?e:`${e}/`;return new URL(n,s).href}async function Gr(e,n=fetch){const s=Be(e);if(!s.ok)throw new Error(s.errors.map(o=>o.message).join("; "));const t=e.tags.find(o=>o[0]==="x")[1],r=Lr(e);if(r.length===0)throw new Error("Manifest does not include any usable Blossom server hints");const i=[];for(const o of r){const l=Fr(o,t);try{const a=await n(l,{mode:"cors"});if(!a.ok){i.push(`${l}: HTTP ${a.status}`);continue}const d=new Uint8Array(await a.arrayBuffer()),h=await $r(d);if(h!==t){i.push(`${l}: sha256 ${h} did not match manifest ${t}`);continue}return new TextDecoder().decode(d)}catch(a){i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}}throw new Error(`Unable to fetch verified /index.html from Blossom servers: ${i.join("; ")}`)}async function Wr(e,n){try{const t=await(await n(e,{mode:"cors"})).text();return{source:"url",input:e,label:e,bootUrl:e,html:t,fetched:!0,manifestEvent:null}}catch{return{source:"url",input:e,label:e,bootUrl:e,html:"",fetched:!1,manifestEvent:null}}}async function Vr(e,n){const s=Dr(e),t=!n.pool,r=n.pool??new xr;try{const i=await r.get(s.relays,{...s.filter},{maxWait:n.maxRelayWaitMs??qr});if(!i)throw new Error("No matching napplet manifest event was found on the pointer relay hints");if(!Or(i))throw new Error("Resolved manifest event signature is invalid");const o=Nr(i),l=Be(o);if(!l.ok)throw new Error(`Resolved event is not a valid NIP-5D napplet manifest: ${l.errors[0]?.message}`);const a=await Gr(o,n.fetcher??fetch),d=(n.createObjectUrl??URL.createObjectURL)(new Blob([a],{type:"text/html;charset=utf-8"})),h=()=>(n.revokeObjectUrl??URL.revokeObjectURL)(d);return{source:"nostr",input:e,label:o.id??e,bootUrl:d,html:a,fetched:!0,manifestEvent:o,revoke:h}}finally{t&&r.destroy()}}async function Qr(e,n={}){const s=e.trim();if(!s)throw new Error("Enter a NIP-19 nevent/naddr, or an HTTP URL for local dev");return Hr(s)?Wr(s,n.fetcher??fetch):Vr(s,n)}const zr=`"use strict";
10
+ ${s}`}function Hs(e,n,s,t){const r=`<base href="${qs(n)}">`,i=Cs(s,t).replace(/<\/script/gi,"<\\/script"),o=`<script>${Os()}<\/script><script>${i}<\/script>`,l=/<head(?:\s[^>]*)?>/i.exec(e);if(l){const a=l.index+l[0].length;return`${e.slice(0,a)}${r}${o}${e.slice(a)}`}return`${r}${o}${e}`}function Ds(e){if(!e.startsWith("data:"))return null;const n=e.indexOf(",");if(n<0)return"";const s=e.slice(0,n),t=e.slice(n+1);return s.endsWith(";base64")?atob(t):decodeURIComponent(t)}async function Bs(e){if(e==="about:blank")return"<!doctype html><html><head></head><body></body></html>";const n=Ds(e);if(n!==null)return n;const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch napplet HTML: ${s.status} ${s.statusText}`);return s.text()}async function Un(e,n,s,t){const r=Ps(),i=s.createElement("iframe");i.setAttribute("sandbox",n.allowSameOrigin?"allow-scripts allow-same-origin":"allow-scripts"),i.setAttribute("allow","gamepad 'none'"),i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.width="1px",i.style.height="1px",i.style.left="-9999px";let o=null,l=!1;const a=f=>{if(f.source!==i.contentWindow)return;const c=f.data;if(c&&typeof c=="object"&&c.type===it){l=c.installed===!0;return}if(c&&typeof c=="object"&&c.type===rt){o=`napplet boot error: ${String(c.reason??"unknown error")}`;return}const m=r.handle(f.data),y=f.source;for(const w of m)y?.postMessage(w,"*")};let d=!1;const h=new Promise(f=>{i.addEventListener("load",()=>{d=!0,f()},{once:!0})});t.addEventListener("message",a);try{const f=n.html??await Bs(n.url);i.srcdoc=Hs(f,n.url,e,n.runtimePreludeSource),(s.body??s.documentElement).appendChild(i)}catch(f){o=f instanceof Error?f.message:String(f)}if(!o){const f=Symbol("timeout");await Promise.race([h.then(()=>"loaded"),Mn(n.readyTimeoutMs).then(()=>f)])===f||!d?o=`napplet did not boot (iframe did not load within ${n.readyTimeoutMs}ms; a conformant napplet must run under sandbox="allow-scripts" without allow-same-origin)`:await Mn(n.settleMs)}t.removeEventListener("message",a);try{i.remove()}catch{}return{installedGlobal:l,bootError:o,emitted:[...r.records]}}async function Ns(e){const n=e.document??document,s=e.window??window,t={url:e.url,html:e.html,readyTimeoutMs:e.readyTimeoutMs??5e3,settleMs:e.settleMs,allowSameOrigin:e.allowSameOrigin??!1,runtimePreludeSource:e.runtimePreludeSource},r=await Un($e,t,n,s);let i=null;{const o=await Un([],t,n,s);i={bootError:o.bootError,emitted:o.emitted}}return{installedGlobal:r.installedGlobal,bootError:r.bootError,emitted:r.emitted,degraded:i}}var $s=e=>({status:"pass",detail:e}),Ls=(e,n)=>({status:"fail",detail:e,diagnostics:n}),Fs=e=>({status:"skip",detail:e}),A={pass:$s,fail:Ls,skip:Fs};function Ws(e,n){const s=We(e.manifestEvent);return[...s.errors,...s.warnings].filter(t=>n.includes(t.code))}function me(e,n,s,t="error"){return{id:e,area:"manifest",severity:t,title:n,run:r=>{if(!r.manifestEvent)return A.skip("No NIP-5D manifest event was resolved");const i=Ws(r,s);return i.length?A.fail(i[0].message,i):A.pass()}}}var Gs=[me("manifest/event-kind","Resolved event is a NIP-5D napplet manifest",["invalid-napplet-kind","missing-d-tag","unexpected-d-tag"]),me("manifest/index-html","Manifest declares a hashed /index.html",["invalid-artifact-hash","missing-description","invalid-metadata"]),me("manifest/requires","R/O tags name bare NAP domains",["invalid-required-nap","invalid-optional-nap"]),me("manifest/requires-known","R/O domains are in this toolchain registry (advisory)",["unknown-required-nap"],"warning"),me("manifest/media-usable","Icon, screenshots, preview and source pins are usable (advisory)",["invalid-icon","invalid-presentation-media","unused-source-commit"],"warning"),{id:"boot/sandbox-allow-scripts",area:"boot",severity:"error",title:"Runs under allow-scripts without allow-same-origin",run:e=>e.sandbox.allowScripts?e.sandbox.allowSameOrigin?A.fail("Napplet relied on allow-same-origin, which a shell must not grant"):A.pass():A.fail("Napplet was not loaded with allow-scripts")},{id:"boot/installs-global",area:"boot",severity:"error",title:"Runs after runtime-injected window.napplet is installed",run:e=>e.installedGlobal?A.pass():A.fail("runtime did not inject window.napplet before load")},{id:"boot/no-boot-error",area:"boot",severity:"error",title:"Boots without an uncaught error",run:e=>e.bootError?A.fail(e.bootError):A.pass()},{id:"boot/no-forbidden-globals",area:"boot",severity:"error",title:"Does not access forbidden browser authority surfaces",run:e=>e.forbiddenGlobals.length?A.fail(`Accessed forbidden surface(s): ${e.forbiddenGlobals.join(", ")}`,e.forbiddenGlobals):A.pass()},{id:"wire/envelope-well-formed",area:"wire",severity:"error",title:"Every emitted envelope is well-formed",run:e=>{if(e.emitted.length===0)return A.skip("Napplet emitted no envelopes");const n=e.emitted.filter(t=>!t.verdict.ok);if(n.length===0)return A.pass(`${e.emitted.length} envelope(s) valid`);const s=n.map(t=>({envelope:t.envelope,errors:t.verdict.errors}));return A.fail(`${n.length}/${e.emitted.length} emitted envelope(s) invalid`,s)}},{id:"degrade/domain-absence",area:"degradation",severity:"error",title:"Does not crash when no NAP domains are injected",run:e=>e.degraded?e.degraded.bootError?A.fail(`Crashed with no injected domains: ${e.degraded.bootError}`):A.pass():A.skip("Host did not run the degraded (no-capabilities) pass")},{id:"lifecycle/clean-teardown",area:"lifecycle",severity:"warning",title:"Tears down listeners on unload",run:e=>e.lifecycle?e.lifecycle.listenerLeak?A.fail("Message listeners remained after unload"):A.pass():A.skip("Lifecycle not measured")}];function Vs(e,n={}){const s=n.now??(()=>Date.now()),t=n.checks??Gs,r=s(),i=t.map(a=>{const d=a.run(e);return{id:a.id,area:a.area,severity:a.severity,title:a.title,status:d.status,detail:d.detail,diagnostics:d.diagnostics}}),o={total:i.length,passed:i.filter(a=>a.status==="pass").length,failed:i.filter(a=>a.status==="fail").length,skipped:i.filter(a=>a.status==="skip").length,errors:i.filter(a=>a.status==="fail"&&a.severity==="error").length,warnings:i.filter(a=>a.status==="fail"&&a.severity==="warning").length};return{napplet:e.manifestEvent?nt(e.manifestEvent):void 0,startedAt:r,finishedAt:s(),checks:i,summary:o,ok:o.errors===0}}function zs(e,n){const s=r=>e.tags.find(i=>i[0]===r)?.[1],t=e.tags.filter(r=>r[0]==="server").map(r=>r[1]).filter(Boolean);return[["event",e.id],["kind",e.kind],["d",s("d")],["name",nt(e)],["requires",n.requires.join(", ")],["optional",n.optional.join(", ")],["artifact hash (x)",s("x")],["servers",t.join(", ")]]}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Qs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function hn(e,n=""){if(!Number.isSafeInteger(e)||e<0){const s=n&&`"${n}" `;throw new Error(`${s}expected integer >= 0, got ${e}`)}}function $(e,n,s=""){const t=Qs(e),r=e?.length,i=n!==void 0;if(!t||i&&r!==n){const o=s&&`"${s}" `,l=i?` of length ${n}`:"",a=t?`length=${r}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+l+", got "+a)}return e}function Pn(e,n=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(n&&e.finished)throw new Error("Hash#digest() has already been called")}function Ks(e,n){$(e,void 0,"digestInto() output");const s=n.outputLen;if(e.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function on(...e){for(let n=0;n<e.length;n++)e[n].fill(0)}function Ze(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function K(e,n){return e<<32-n|e>>>n}const ot=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zs=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function C(e){if($(e),ot)return e.toHex();let n="";for(let s=0;s<e.length;s++)n+=Zs[e[s]];return n}const X={_0:48,_9:57,A:65,F:70,a:97,f:102};function An(e){if(e>=X._0&&e<=X._9)return e-X._0;if(e>=X.A&&e<=X.F)return e-(X.A-10);if(e>=X.a&&e<=X.f)return e-(X.a-10)}function Y(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(ot)return Uint8Array.fromHex(e);const n=e.length,s=n/2;if(n%2)throw new Error("hex string expected, got unpadded hex of length "+n);const t=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=An(e.charCodeAt(i)),l=An(e.charCodeAt(i+1));if(o===void 0||l===void 0){const a=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+i)}t[r]=o*16+l}return t}function Oe(...e){let n=0;for(let t=0;t<e.length;t++){const r=e[t];$(r),n+=r.length}const s=new Uint8Array(n);for(let t=0,r=0;t<e.length;t++){const i=e[t];s.set(i,r),r+=i.length}return s}function Ys(e,n={}){const s=(r,i)=>e(i).update(r).digest(),t=e(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=r=>e(r),Object.assign(s,n),Object.freeze(s)}function at(e=32){const n=typeof globalThis=="object"?globalThis.crypto:null;if(typeof n?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return n.getRandomValues(new Uint8Array(e))}const Xs=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function lt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function dt(e,n){return Array.isArray(n)?n.length===0?!0:e?n.every(s=>typeof s=="string"):n.every(s=>Number.isSafeInteger(s)):!1}function Js(e){if(typeof e!="function")throw new Error("function expected");return!0}function Se(e,n){if(typeof n!="string")throw new Error(`${e}: string expected`);return!0}function ct(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function an(e){if(!Array.isArray(e))throw new Error("array expected")}function ut(e,n){if(!dt(!0,n))throw new Error(`${e}: array of strings expected`)}function ft(e,n){if(!dt(!1,n))throw new Error(`${e}: array of numbers expected`)}function er(...e){const n=i=>i,s=(i,o)=>l=>i(o(l)),t=e.map(i=>i.encode).reduceRight(s,n),r=e.map(i=>i.decode).reduce(s,n);return{encode:t,decode:r}}function nr(e){const n=typeof e=="string"?e.split(""):e,s=n.length;ut("alphabet",n);const t=new Map(n.map((r,i)=>[r,i]));return{encode:r=>(an(r),r.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=s)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return n[i]})),decode:r=>(an(r),r.map(i=>{Se("alphabet.decode",i);const o=t.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${e}`);return o}))}}function tr(e=""){return Se("join",e),{encode:n=>(ut("join.decode",n),n.join(e)),decode:n=>(Se("join.decode",n),n.split(e))}}const pt=(e,n)=>n===0?e:pt(n,e%n),Ce=(e,n)=>e+(n-pt(e,n)),Ae=(()=>{let e=[];for(let n=0;n<40;n++)e.push(2**n);return e})();function ln(e,n,s,t){if(an(e),n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(Ce(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${Ce(n,s)}`);let r=0,i=0;const o=Ae[n],l=Ae[s]-1,a=[];for(const d of e){if(ct(d),d>=o)throw new Error(`convertRadix2: invalid data word=${d} from=${n}`);if(r=r<<n|d,i+n>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${n}`);for(i+=n;i>=s;i-=s)a.push((r>>i-s&l)>>>0);const h=Ae[i];if(h===void 0)throw new Error("invalid carry");r&=h-1}if(r=r<<s-i&l,!t&&i>=n)throw new Error("Excess padding");if(!t&&r>0)throw new Error(`Non-zero padding: ${r}`);return t&&i>0&&a.push(r>>>0),a}function sr(e,n=!1){if(ct(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Ce(8,e)>32||Ce(e,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!lt(s))throw new Error("radix2.encode input should be Uint8Array");return ln(Array.from(s),8,e,!n)},decode:s=>(ft("radix2.decode",s),Uint8Array.from(ln(s,e,8,n)))}}function jn(e){return Js(e),function(...n){try{return e.apply(null,n)}catch{}}}const dn=er(nr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),tr("")),qn=[996825010,642813549,513874426,1027748829,705979059];function ge(e){const n=e>>25;let s=(e&33554431)<<5;for(let t=0;t<qn.length;t++)(n>>t&1)===1&&(s^=qn[t]);return s}function On(e,n,s=1){const t=e.length;let r=1;for(let i=0;i<t;i++){const o=e.charCodeAt(i);if(o<33||o>126)throw new Error(`Invalid prefix (${e})`);r=ge(r)^o>>5}r=ge(r);for(let i=0;i<t;i++)r=ge(r)^e.charCodeAt(i)&31;for(let i of n)r=ge(r)^i;for(let i=0;i<6;i++)r=ge(r);return r^=s,dn.encode(ln([r%Ae[30]],30,5,!1))}function rr(e){const n=e==="bech32"?1:734539939,s=sr(5),t=s.decode,r=s.encode,i=jn(t);function o(f,c,m=90){Se("bech32.encode prefix",f),lt(c)&&(c=Array.from(c)),ft("bech32.encode",c);const y=f.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);const w=y+7+c.length;if(m!==!1&&w>m)throw new TypeError(`Length ${w} exceeds limit ${m}`);const P=f.toLowerCase(),q=On(P,c,n);return`${P}1${dn.encode(c)}${q}`}function l(f,c=90){Se("bech32.decode input",f);const m=f.length;if(m<8||c!==!1&&m>c)throw new TypeError(`invalid string length: ${m} (${f}). Expected (8..${c})`);const y=f.toLowerCase();if(f!==y&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");const w=y.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const P=y.slice(0,w),q=y.slice(w+1);if(q.length<6)throw new Error("Data must be at least 6 characters long");const z=dn.decode(q).slice(0,-6),J=On(P,z,n);if(!q.endsWith(J))throw new Error(`Invalid checksum in ${f}: expected "${J}"`);return{prefix:P,words:z}}const a=jn(l);function d(f){const{prefix:c,words:m}=l(f,!1);return{prefix:c,words:m,bytes:t(m)}}function h(f,c){return o(f,r(c))}return{encode:o,decode:l,encodeFromBytes:h,decodeToBytes:d,decodeUnsafe:a,fromWords:t,fromWordsUnsafe:i,toWords:r}}const Cn=rr("bech32");var Me=new TextDecoder("utf-8");new TextEncoder;var ir=5e3;function or(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),ar(e)}catch{return{type:"invalid",data:null}}}function ar(e){let{prefix:n,words:s}=Cn.decode(e,ir),t=new Uint8Array(Cn.fromWords(s));switch(n){case"nprofile":{let r=Ye(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(r[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:C(r[0][0]),relays:r[1]?r[1].map(i=>Me.decode(i)):[]}}}case"nevent":{let r=Ye(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for nevent");if(r[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(r[2]&&r[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(r[3]&&r[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:C(r[0][0]),relays:r[1]?r[1].map(i=>Me.decode(i)):[],author:r[2]?.[0]?C(r[2][0]):void 0,kind:r[3]?.[0]?parseInt(C(r[3][0]),16):void 0}}}case"naddr":{let r=Ye(t);if(!r[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!r[2]?.[0])throw new Error("missing TLV 2 for naddr");if(r[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!r[3]?.[0])throw new Error("missing TLV 3 for naddr");if(r[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Me.decode(r[0][0]),pubkey:C(r[2][0]),kind:parseInt(C(r[3][0]),16),relays:r[1]?r[1].map(i=>Me.decode(i)):[]}}}case"nsec":return{type:n,data:t};case"npub":case"note":return{type:n,data:C(t)};default:throw new Error(`unknown prefix ${n}`)}}function Ye(e){let n={},s=e;for(;s.length>0;){let t=s[0],r=s[1],i=s.slice(2,2+r);if(s=s.slice(2+r),i.length<r)throw new Error(`not enough data to read on TLV ${t}`);n[t]=n[t]||[],n[t].push(i)}return n}function lr(e,n,s){return e&n^~e&s}function dr(e,n,s){return e&n^e&s^n&s}class cr{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(n,s,t,r){this.blockLen=n,this.outputLen=s,this.padOffset=t,this.isLE=r,this.buffer=new Uint8Array(n),this.view=Ze(this.buffer)}update(n){Pn(this),$(n);const{view:s,buffer:t,blockLen:r}=this,i=n.length;for(let o=0;o<i;){const l=Math.min(r-this.pos,i-o);if(l===r){const a=Ze(n);for(;r<=i-o;o+=r)this.process(a,o);continue}t.set(n.subarray(o,o+l),this.pos),this.pos+=l,o+=l,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=n.length,this.roundClean(),this}digestInto(n){Pn(this),Ks(n,this),this.finished=!0;const{buffer:s,view:t,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,on(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(t,0),o=0);for(let f=o;f<r;f++)s[f]=0;t.setBigUint64(r-8,BigInt(this.length*8),i),this.process(t,0);const l=Ze(n),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const d=a/4,h=this.get();if(d>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<d;f++)l.setUint32(4*f,h[f],i)}digest(){const{buffer:n,outputLen:s}=this;this.digestInto(n);const t=n.slice(0,s);return this.destroy(),t}_cloneInto(n){n||=new this.constructor,n.set(...this.get());const{blockLen:s,buffer:t,length:r,finished:i,destroyed:o,pos:l}=this;return n.destroyed=o,n.finished=i,n.length=r,n.pos=l,r%s&&n.buffer.set(t),n}clone(){return this._cloneInto()}}const ee=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ur=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ne=new Uint32Array(64);class fr extends cr{constructor(n){super(64,n,8,!1)}get(){const{A:n,B:s,C:t,D:r,E:i,F:o,G:l,H:a}=this;return[n,s,t,r,i,o,l,a]}set(n,s,t,r,i,o,l,a){this.A=n|0,this.B=s|0,this.C=t|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=l|0,this.H=a|0}process(n,s){for(let f=0;f<16;f++,s+=4)ne[f]=n.getUint32(s,!1);for(let f=16;f<64;f++){const c=ne[f-15],m=ne[f-2],y=K(c,7)^K(c,18)^c>>>3,w=K(m,17)^K(m,19)^m>>>10;ne[f]=w+ne[f-7]+y+ne[f-16]|0}let{A:t,B:r,C:i,D:o,E:l,F:a,G:d,H:h}=this;for(let f=0;f<64;f++){const c=K(l,6)^K(l,11)^K(l,25),m=h+c+lr(l,a,d)+ur[f]+ne[f]|0,w=(K(t,2)^K(t,13)^K(t,22))+dr(t,r,i)|0;h=d,d=a,a=l,l=o+m|0,o=i,i=r,r=t,t=m+w|0}t=t+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,l=l+this.E|0,a=a+this.F|0,d=d+this.G|0,h=h+this.H|0,this.set(t,r,i,o,l,a,d,h)}roundClean(){on(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),on(this.buffer)}}class pr extends fr{A=ee[0]|0;B=ee[1]|0;C=ee[2]|0;D=ee[3]|0;E=ee[4]|0;F=ee[5]|0;G=ee[6]|0;H=ee[7]|0;constructor(){super(32)}}const He=Ys(()=>new pr,Xs(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yn=BigInt(0),cn=BigInt(1);function Hn(e,n=""){if(typeof e!="boolean"){const s=n&&`"${n}" `;throw new Error(s+"expected boolean, got type="+typeof e)}return e}function mr(e){if(typeof e=="bigint"){if(!yr(e))throw new Error("positive bigint expected, got "+e)}else hn(e);return e}function mt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?yn:BigInt("0x"+e)}function bn(e){return mt(C(e))}function gt(e){return mt(C(gr($(e)).reverse()))}function vn(e,n){hn(n),e=mr(e);const s=Y(e.toString(16).padStart(n*2,"0"));if(s.length!==n)throw new Error("number too large");return s}function ht(e,n){return vn(e,n).reverse()}function gr(e){return Uint8Array.from(e)}function hr(e){return Uint8Array.from(e,(n,s)=>{const t=n.charCodeAt(0);if(n.length!==1||t>127)throw new Error(`string contains non-ASCII character "${e[s]}" with code ${t} at position ${s}`);return t})}const yr=e=>typeof e=="bigint"&&yn<=e;function br(e){let n;for(n=0;e>yn;e>>=cn,n+=1);return n}const yt=e=>(cn<<BigInt(e))-cn;function bt(e,n={},s={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function t(i,o,l){const a=e[i];if(l&&a===void 0)return;const d=typeof a;if(d!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${d}`)}const r=(i,o)=>Object.entries(i).forEach(([l,a])=>t(l,a,o));r(n,!1),r(s,!0)}function Dn(e){const n=new WeakMap;return(s,...t)=>{const r=n.get(s);if(r!==void 0)return r;const i=e(s,...t);return n.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const N=BigInt(0),B=BigInt(1),ie=BigInt(2),vt=BigInt(3),wt=BigInt(4),Et=BigInt(5),vr=BigInt(7),St=BigInt(8),wr=BigInt(9),Tt=BigInt(16);function V(e,n){const s=e%n;return s>=N?s:n+s}function F(e,n,s){let t=e;for(;n-- >N;)t*=t,t%=s;return t}function Bn(e,n){if(e===N)throw new Error("invert: expected non-zero number");if(n<=N)throw new Error("invert: expected positive modulus, got "+n);let s=V(e,n),t=n,r=N,i=B;for(;s!==N;){const l=t/s,a=t%s,d=r-i*l;t=s,s=a,r=i,i=d}if(t!==B)throw new Error("invert: does not exist");return V(r,n)}function wn(e,n,s){if(!e.eql(e.sqr(n),s))throw new Error("Cannot find square root")}function _t(e,n){const s=(e.ORDER+B)/wt,t=e.pow(n,s);return wn(e,t,n),t}function Er(e,n){const s=(e.ORDER-Et)/St,t=e.mul(n,ie),r=e.pow(t,s),i=e.mul(n,r),o=e.mul(e.mul(i,ie),r),l=e.mul(i,e.sub(o,e.ONE));return wn(e,l,n),l}function Sr(e){const n=Ge(e),s=Rt(e),t=s(n,n.neg(n.ONE)),r=s(n,t),i=s(n,n.neg(t)),o=(e+vr)/Tt;return(l,a)=>{let d=l.pow(a,o),h=l.mul(d,t);const f=l.mul(d,r),c=l.mul(d,i),m=l.eql(l.sqr(h),a),y=l.eql(l.sqr(f),a);d=l.cmov(d,h,m),h=l.cmov(c,f,y);const w=l.eql(l.sqr(h),a),P=l.cmov(d,h,w);return wn(l,P,a),P}}function Rt(e){if(e<vt)throw new Error("sqrt is not defined for small field");let n=e-B,s=0;for(;n%ie===N;)n/=ie,s++;let t=ie;const r=Ge(e);for(;Nn(r,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return _t;let i=r.pow(t,n);const o=(n+B)/ie;return function(a,d){if(a.is0(d))return d;if(Nn(a,d)!==1)throw new Error("Cannot find square root");let h=s,f=a.mul(a.ONE,i),c=a.pow(d,n),m=a.pow(d,o);for(;!a.eql(c,a.ONE);){if(a.is0(c))return a.ZERO;let y=1,w=a.sqr(c);for(;!a.eql(w,a.ONE);)if(y++,w=a.sqr(w),y===h)throw new Error("Cannot find square root");const P=B<<BigInt(h-y-1),q=a.pow(f,P);h=y,f=a.sqr(q),c=a.mul(c,f),m=a.mul(m,q)}return m}}function Tr(e){return e%wt===vt?_t:e%St===Et?Er:e%Tt===wr?Sr(e):Rt(e)}const _r=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rr(e){const n={ORDER:"bigint",BYTES:"number",BITS:"number"},s=_r.reduce((t,r)=>(t[r]="function",t),n);return bt(e,s),e}function Ir(e,n,s){if(s<N)throw new Error("invalid exponent, negatives unsupported");if(s===N)return e.ONE;if(s===B)return n;let t=e.ONE,r=n;for(;s>N;)s&B&&(t=e.mul(t,r)),r=e.sqr(r),s>>=B;return t}function It(e,n,s=!1){const t=new Array(n.length).fill(s?e.ZERO:void 0),r=n.reduce((o,l,a)=>e.is0(l)?o:(t[a]=o,e.mul(o,l)),e.ONE),i=e.inv(r);return n.reduceRight((o,l,a)=>e.is0(l)?o:(t[a]=e.mul(o,t[a]),e.mul(o,l)),i),t}function Nn(e,n){const s=(e.ORDER-B)/ie,t=e.pow(n,s),r=e.eql(t,e.ONE),i=e.eql(t,e.ZERO),o=e.eql(t,e.neg(e.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function kr(e,n){n!==void 0&&hn(n);const s=n!==void 0?n:e.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class xr{ORDER;BITS;BYTES;isLE;ZERO=N;ONE=B;_lengths;_sqrt;_mod;constructor(n,s={}){if(n<=N)throw new Error("invalid field: expected ORDER > 0, got "+n);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=s.allowedLengths?.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:r,nByteLength:i}=kr(n,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=n,this.BITS=r,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(n){return V(n,this.ORDER)}isValid(n){if(typeof n!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof n);return N<=n&&n<this.ORDER}is0(n){return n===N}isValidNot0(n){return!this.is0(n)&&this.isValid(n)}isOdd(n){return(n&B)===B}neg(n){return V(-n,this.ORDER)}eql(n,s){return n===s}sqr(n){return V(n*n,this.ORDER)}add(n,s){return V(n+s,this.ORDER)}sub(n,s){return V(n-s,this.ORDER)}mul(n,s){return V(n*s,this.ORDER)}pow(n,s){return Ir(this,n,s)}div(n,s){return V(n*Bn(s,this.ORDER),this.ORDER)}sqrN(n){return n*n}addN(n,s){return n+s}subN(n,s){return n-s}mulN(n,s){return n*s}inv(n){return Bn(n,this.ORDER)}sqrt(n){return this._sqrt||(this._sqrt=Tr(this.ORDER)),this._sqrt(this,n)}toBytes(n){return this.isLE?ht(n,this.BYTES):vn(n,this.BYTES)}fromBytes(n,s=!1){$(n);const{_lengths:t,BYTES:r,isLE:i,ORDER:o,_mod:l}=this;if(t){if(!t.includes(n.length)||n.length>r)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+n.length);const d=new Uint8Array(r);d.set(n,i?0:d.length-n.length),n=d}if(n.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+n.length);let a=i?gt(n):bn(n);if(l&&(a=V(a,o)),!s&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(n){return It(this,n)}cmov(n,s,t){return t?s:n}}function Ge(e,n={}){return new xr(e,n)}function kt(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function Mr(e){const n=kt(e);return n+Math.ceil(n/2)}function Ur(e,n,s=!1){$(e);const t=e.length,r=kt(n),i=Mr(n);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?gt(e):bn(e),l=V(o,n-B)+B;return s?ht(l,r):vn(l,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ue=BigInt(0),oe=BigInt(1);function De(e,n){const s=n.negate();return e?s:n}function $n(e,n){const s=It(e.Fp,n.map(t=>t.Z));return n.map((t,r)=>e.fromAffine(t.toAffine(s[r])))}function xt(e,n){if(!Number.isSafeInteger(e)||e<=0||e>n)throw new Error("invalid window size, expected [1.."+n+"], got W="+e)}function Xe(e,n){xt(e,n);const s=Math.ceil(n/e)+1,t=2**(e-1),r=2**e,i=yt(e),o=BigInt(e);return{windows:s,windowSize:t,mask:i,maxNumber:r,shiftBy:o}}function Ln(e,n,s){const{windowSize:t,mask:r,maxNumber:i,shiftBy:o}=s;let l=Number(e&r),a=e>>o;l>t&&(l-=i,a+=oe);const d=n*t,h=d+Math.abs(l)-1,f=l===0,c=l<0,m=n%2!==0;return{nextN:a,offset:h,isZero:f,isNeg:c,isNegF:m,offsetF:d}}const Je=new WeakMap,Mt=new WeakMap;function en(e){return Mt.get(e)||1}function Fn(e){if(e!==ue)throw new Error("invalid wNAF")}class Pr{BASE;ZERO;Fn;bits;constructor(n,s){this.BASE=n.BASE,this.ZERO=n.ZERO,this.Fn=n.Fn,this.bits=s}_unsafeLadder(n,s,t=this.ZERO){let r=n;for(;s>ue;)s&oe&&(t=t.add(r)),r=r.double(),s>>=oe;return t}precomputeWindow(n,s){const{windows:t,windowSize:r}=Xe(s,this.bits),i=[];let o=n,l=o;for(let a=0;a<t;a++){l=o,i.push(l);for(let d=1;d<r;d++)l=l.add(o),i.push(l);o=l.double()}return i}wNAF(n,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Xe(n,this.bits);for(let l=0;l<o.windows;l++){const{nextN:a,offset:d,isZero:h,isNeg:f,isNegF:c,offsetF:m}=Ln(t,l,o);t=a,h?i=i.add(De(c,s[m])):r=r.add(De(f,s[d]))}return Fn(t),{p:r,f:i}}wNAFUnsafe(n,s,t,r=this.ZERO){const i=Xe(n,this.bits);for(let o=0;o<i.windows&&t!==ue;o++){const{nextN:l,offset:a,isZero:d,isNeg:h}=Ln(t,o,i);if(t=l,!d){const f=s[a];r=r.add(h?f.negate():f)}}return Fn(t),r}getPrecomputes(n,s,t){let r=Je.get(s);return r||(r=this.precomputeWindow(s,n),n!==1&&(typeof t=="function"&&(r=t(r)),Je.set(s,r))),r}cached(n,s,t){const r=en(n);return this.wNAF(r,this.getPrecomputes(r,n,t),s)}unsafe(n,s,t,r){const i=en(n);return i===1?this._unsafeLadder(n,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,n,t),s,r)}createCache(n,s){xt(s,this.bits),Mt.set(n,s),Je.delete(n)}hasCache(n){return en(n)!==1}}function Ar(e,n,s,t){let r=n,i=e.ZERO,o=e.ZERO;for(;s>ue||t>ue;)s&oe&&(i=i.add(r)),t&oe&&(o=o.add(r)),r=r.double(),s>>=oe,t>>=oe;return{p1:i,p2:o}}function Wn(e,n,s){if(n){if(n.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rr(n),n}else return Ge(e,{isLE:s})}function jr(e,n,s={},t){if(t===void 0&&(t=e==="edwards"),!n||typeof n!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const d=n[a];if(!(typeof d=="bigint"&&d>ue))throw new Error(`CURVE.${a} must be positive bigint`)}const r=Wn(n.p,s.Fp,t),i=Wn(n.n,s.Fn,t),l=["Gx","Gy","a","b"];for(const a of l)if(!r.isValid(n[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return n=Object.freeze(Object.assign({},n)),{CURVE:n,Fp:r,Fn:i}}function qr(e,n){return function(t){const r=e(t);return{secretKey:r,publicKey:n(r)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gn=(e,n)=>(e+(e>=0?n:-n)/Cr)/n;function Or(e,n,s){const[[t,r],[i,o]]=n,l=Gn(o*e,s),a=Gn(-r*e,s);let d=e-l*t-a*i,h=-l*r-a*o;const f=d<he,c=h<he;f&&(d=-d),c&&(h=-h);const m=yt(Math.ceil(br(s)/2))+je;if(d<he||d>=m||h<he||h>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:d,k2neg:c,k2:h}}const he=BigInt(0),je=BigInt(1),Cr=BigInt(2),Ue=BigInt(3),Hr=BigInt(4);function Dr(e,n={}){const s=jr("weierstrass",e,n),{Fp:t,Fn:r}=s;let i=s.CURVE;const{h:o,n:l}=i;bt(n,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:a}=n;if(a&&(!t.is0(i.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const d=Nr(t,r);function h(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(k,g,b){const{x:E,y:S}=g.toAffine(),x=t.toBytes(E);if(Hn(b,"isCompressed"),b){h();const R=!t.isOdd(S);return Oe(Br(R),x)}else return Oe(Uint8Array.of(4),x,t.toBytes(S))}function c(k){$(k,void 0,"Point");const{publicKey:g,publicKeyUncompressed:b}=d,E=k.length,S=k[0],x=k.subarray(1);if(E===g&&(S===2||S===3)){const R=t.fromBytes(x);if(!t.isValid(R))throw new Error("bad point: is not on curve, wrong x");const T=w(R);let v;try{v=t.sqrt(T)}catch(L){const O=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+O)}h();const _=t.isOdd(v);return(S&1)===1!==_&&(v=t.neg(v)),{x:R,y:v}}else if(E===b&&S===4){const R=t.BYTES,T=t.fromBytes(x.subarray(0,R)),v=t.fromBytes(x.subarray(R,R*2));if(!P(T,v))throw new Error("bad point: is not on curve");return{x:T,y:v}}else throw new Error(`bad point: got length ${E}, expected compressed=${g} or uncompressed=${b}`)}const m=n.toBytes||f,y=n.fromBytes||c;function w(k){const g=t.sqr(k),b=t.mul(g,k);return t.add(t.add(b,t.mul(k,i.a)),i.b)}function P(k,g){const b=t.sqr(g),E=w(k);return t.eql(b,E)}if(!P(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const q=t.mul(t.pow(i.a,Ue),Hr),z=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(q,z)))throw new Error("bad curve params: a or b");function J(k,g,b=!1){if(!t.isValid(g)||b&&t.is0(g))throw new Error(`bad point coordinate ${k}`);return g}function Re(k){if(!(k instanceof U))throw new Error("Weierstrass Point expected")}function Ie(k){if(!a||!a.basises)throw new Error("no endo");return Or(k,a.basises,r.ORDER)}const ke=Dn((k,g)=>{const{X:b,Y:E,Z:S}=k;if(t.eql(S,t.ONE))return{x:b,y:E};const x=k.is0();g==null&&(g=x?t.ONE:t.inv(S));const R=t.mul(b,g),T=t.mul(E,g),v=t.mul(S,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:R,y:T}}),Ht=Dn(k=>{if(k.is0()){if(n.allowInfinityPoint&&!t.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:b}=k.toAffine();if(!t.isValid(g)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!P(g,b))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Tn(k,g,b,E,S){return b=new U(t.mul(b.X,k),b.Y,b.Z),g=De(E,g),b=De(S,b),g.add(b)}class U{static BASE=new U(i.Gx,i.Gy,t.ONE);static ZERO=new U(t.ZERO,t.ONE,t.ZERO);static Fp=t;static Fn=r;X;Y;Z;constructor(g,b,E){this.X=J("x",g),this.Y=J("y",b,!0),this.Z=J("z",E),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){const{x:b,y:E}=g||{};if(!g||!t.isValid(b)||!t.isValid(E))throw new Error("invalid affine point");if(g instanceof U)throw new Error("projective point not allowed");return t.is0(b)&&t.is0(E)?U.ZERO:new U(b,E,t.ONE)}static fromBytes(g){const b=U.fromAffine(y($(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return U.fromBytes(Y(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return pe.createCache(this,g),b||this.multiply(Ue),this}assertValidity(){Ht(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){Re(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:R,Z:T}=g,v=t.eql(t.mul(b,T),t.mul(x,S)),_=t.eql(t.mul(E,T),t.mul(R,S));return v&&_}negate(){return new U(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b}=i,E=t.mul(b,Ue),{X:S,Y:x,Z:R}=this;let T=t.ZERO,v=t.ZERO,_=t.ZERO,I=t.mul(S,S),L=t.mul(x,x),O=t.mul(R,R),M=t.mul(S,x);return M=t.add(M,M),_=t.mul(S,R),_=t.add(_,_),T=t.mul(g,_),v=t.mul(E,O),v=t.add(T,v),T=t.sub(L,v),v=t.add(L,v),v=t.mul(T,v),T=t.mul(M,T),_=t.mul(E,_),O=t.mul(g,O),M=t.sub(I,O),M=t.mul(g,M),M=t.add(M,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,O),I=t.mul(I,M),v=t.add(v,I),O=t.mul(x,R),O=t.add(O,O),I=t.mul(O,M),T=t.sub(T,I),_=t.mul(O,L),_=t.add(_,_),_=t.add(_,_),new U(T,v,_)}add(g){Re(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:R,Z:T}=g;let v=t.ZERO,_=t.ZERO,I=t.ZERO;const L=i.a,O=t.mul(i.b,Ue);let M=t.mul(b,x),W=t.mul(E,R),G=t.mul(S,T),ae=t.add(b,E),D=t.add(x,R);ae=t.mul(ae,D),D=t.add(M,W),ae=t.sub(ae,D),D=t.add(b,S);let Q=t.add(x,T);return D=t.mul(D,Q),Q=t.add(M,G),D=t.sub(D,Q),Q=t.add(E,S),v=t.add(R,T),Q=t.mul(Q,v),v=t.add(W,G),Q=t.sub(Q,v),I=t.mul(L,D),v=t.mul(O,G),I=t.add(v,I),v=t.sub(W,I),I=t.add(W,I),_=t.mul(v,I),W=t.add(M,M),W=t.add(W,M),G=t.mul(L,G),D=t.mul(O,D),W=t.add(W,G),G=t.sub(M,G),G=t.mul(L,G),D=t.add(D,G),M=t.mul(W,D),_=t.add(_,M),M=t.mul(Q,D),v=t.mul(ae,v),v=t.sub(v,M),M=t.mul(ae,W),I=t.mul(Q,I),I=t.add(I,M),new U(v,_,I)}subtract(g){return this.add(g.negate())}is0(){return this.equals(U.ZERO)}multiply(g){const{endo:b}=n;if(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let E,S;const x=R=>pe.cached(this,R,T=>$n(U,T));if(b){const{k1neg:R,k1:T,k2neg:v,k2:_}=Ie(g),{p:I,f:L}=x(T),{p:O,f:M}=x(_);S=L.add(M),E=Tn(b.beta,I,O,R,v)}else{const{p:R,f:T}=x(g);E=R,S=T}return $n(U,[E,S])[0]}multiplyUnsafe(g){const{endo:b}=n,E=this;if(!r.isValid(g))throw new Error("invalid scalar: out of range");if(g===he||E.is0())return U.ZERO;if(g===je)return E;if(pe.hasCache(this))return this.multiply(g);if(b){const{k1neg:S,k1:x,k2neg:R,k2:T}=Ie(g),{p1:v,p2:_}=Ar(U,E,x,T);return Tn(b.beta,v,_,S,R)}else return pe.unsafe(E,g)}toAffine(g){return ke(this,g)}isTorsionFree(){const{isTorsionFree:g}=n;return o===je?!0:g?g(U,this):pe.unsafe(this,l).is0()}clearCofactor(){const{clearCofactor:g}=n;return o===je?this:g?g(U,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(g=!0){return Hn(g,"isCompressed"),this.assertValidity(),m(U,this,g)}toHex(g=!0){return C(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const _n=r.BITS,pe=new Pr(U,n.endo?Math.ceil(_n/2):_n);return U.BASE.precompute(8),U}function Br(e){return Uint8Array.of(e?2:3)}function Nr(e,n){return{secretKey:n.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*n.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ve={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},$r={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Lr=BigInt(0),un=BigInt(2);function Fr(e){const n=Ve.p,s=BigInt(3),t=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),l=BigInt(44),a=BigInt(88),d=e*e*e%n,h=d*d*e%n,f=F(h,s,n)*h%n,c=F(f,s,n)*h%n,m=F(c,un,n)*d%n,y=F(m,r,n)*m%n,w=F(y,i,n)*y%n,P=F(w,l,n)*w%n,q=F(P,a,n)*P%n,z=F(q,l,n)*w%n,J=F(z,s,n)*h%n,Re=F(J,o,n)*y%n,Ie=F(Re,t,n)*d%n,ke=F(Ie,un,n);if(!Be.eql(Be.sqr(ke),e))throw new Error("Cannot find square root");return ke}const Be=Ge(Ve.p,{sqrt:Fr}),fe=Dr(Ve,{Fp:Be,endo:$r}),Vn={};function Ne(e,...n){let s=Vn[e];if(s===void 0){const t=He(hr(e));s=Oe(t,t),Vn[e]=s}return He(Oe(s,...n))}const En=e=>e.toBytes(!0).slice(1),Sn=e=>e%un===Lr;function fn(e){const{Fn:n,BASE:s}=fe,t=n.fromBytes(e),r=s.multiply(t);return{scalar:Sn(r.y)?t:n.neg(t),bytes:En(r)}}function Ut(e){const n=Be;if(!n.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const s=n.create(e*e),t=n.create(s*e+BigInt(7));let r=n.sqrt(t);Sn(r)||(r=n.neg(r));const i=fe.fromAffine({x:e,y:r});return i.assertValidity(),i}const ve=bn;function Pt(...e){return fe.Fn.create(ve(Ne("BIP0340/challenge",...e)))}function zn(e){return fn(e).bytes}function Wr(e,n,s=at(32)){const{Fn:t}=fe,r=$(e,void 0,"message"),{bytes:i,scalar:o}=fn(n),l=$(s,32,"auxRand"),a=t.toBytes(o^ve(Ne("BIP0340/aux",l))),d=Ne("BIP0340/nonce",a,i,r),{bytes:h,scalar:f}=fn(d),c=Pt(h,i,r),m=new Uint8Array(64);if(m.set(h,0),m.set(t.toBytes(t.create(f+c*o)),32),!At(m,r,i))throw new Error("sign: Invalid signature produced");return m}function At(e,n,s){const{Fp:t,Fn:r,BASE:i}=fe,o=$(e,64,"signature"),l=$(n,void 0,"message"),a=$(s,32,"publicKey");try{const d=Ut(ve(a)),h=ve(o.subarray(0,32));if(!t.isValidNot0(h))return!1;const f=ve(o.subarray(32,64));if(!r.isValidNot0(f))return!1;const c=Pt(r.toBytes(h),En(d),l),m=i.multiplyUnsafe(f).add(d.multiplyUnsafe(r.neg(c))),{x:y,y:w}=m.toAffine();return!(m.is0()||!Sn(w)||y!==h)}catch{return!1}}const Z=(()=>{const s=(t=at(48))=>Ur(t,Ve.n);return{keygen:qr(s,zn),getPublicKey:zn,sign:Wr,verify:At,Point:fe,utils:{randomSecretKey:s,taggedHash:Ne,lift_x:Ut,pointToBytes:En},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var re=Symbol("verified"),Gr=e=>e instanceof Object;function Vr(e){if(!Gr(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let s=e.tags[n];if(!Array.isArray(s))return!1;for(let t=0;t<s.length;t++)if(typeof s[t]!="string")return!1}return!0}new TextDecoder("utf-8");var zr=new TextEncoder;function ye(e){try{e.indexOf("://")===-1&&(e="wss://"+e);let n=new URL(e);return n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),n.pathname=n.pathname.replace(/\/+/g,"/"),n.pathname.endsWith("/")&&(n.pathname=n.pathname.slice(0,-1)),(n.port==="80"&&n.protocol==="ws:"||n.port==="443"&&n.protocol==="wss:")&&(n.port=""),n.searchParams.sort(),n.hash="",n.toString()}catch{throw new Error(`Invalid URL: ${e}`)}}var Qr=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(n){return C(Z.getPublicKey(n))}finalizeEvent(n,s){const t=n;return t.pubkey=C(Z.getPublicKey(s)),t.id=nn(t),t.sig=C(Z.sign(Y(nn(t)),s)),t[re]=!0,t}verifyEvent(n){if(typeof n[re]=="boolean")return n[re];try{const s=nn(n);if(s!==n.id)return n[re]=!1,!1;const t=Z.verify(Y(n.sig),Y(s),Y(n.pubkey));return n[re]=t,t}catch{return n[re]=!1,!1}}};function Kr(e){if(!Vr(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function nn(e){let n=He(zr.encode(Kr(e)));return C(n)}var ze=new Qr;ze.generateSecretKey;ze.getPublicKey;ze.finalizeEvent;var Zr=ze.verifyEvent,Yr=22242;function Xr(e,n){if(e.ids&&e.ids.indexOf(n.id)===-1||e.kinds&&e.kinds.indexOf(n.kind)===-1||e.authors&&e.authors.indexOf(n.pubkey)===-1)return!1;for(let s in e)if(s[0]==="#"){let t=s.slice(1),r=e[`#${t}`];if(r&&!n.tags.find(([i,o])=>i===s.slice(1)&&r.indexOf(o)!==-1))return!1}return!(e.since&&n.created_at<e.since||e.until&&n.created_at>e.until)}function Jr(e,n){for(let s=0;s<e.length;s++)if(Xr(e[s],n))return!0;return!1}function ei(e,n){let s=n.length+3,t=e.indexOf(`"${n}":`)+s,r=e.slice(t).indexOf('"')+t+1;return e.slice(r,r+64)}function ni(e){let n=e.slice(0,22).indexOf('"EVENT"');if(n===-1)return null;let s=e.slice(n+7+1).indexOf('"');if(s===-1)return null;let t=n+7+1+s,r=e.slice(t+1,80).indexOf('"');if(r===-1)return null;let i=t+1+r;return e.slice(t+1,i)}function ti(e,n){return{kind:Yr,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",n]],content:""}}var jt=class extends Error{constructor(e,n){super(`Tried to send message '${e} on a closed connection to ${n}.`),this.name="SendingOnClosedConnection"}},qt=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);onauth;baseEoseTimeout=4400;publishTimeout=4400;pingFrequency=29e3;pingTimeout=2e4;resubscribeBackoff=[1e4,1e4,1e4,2e4,2e4,3e4,6e4];openSubs=new Map;enablePing;enableReconnect;idleSince=Date.now();ongoingOperations=0;reconnectTimeoutHandle;pingIntervalHandle;reconnectAttempts=0;skipReconnection=!1;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;challenge;authPromise;serial=0;verifyEvent;_WebSocket;constructor(e,n){this.url=ye(e),this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation||WebSocket,this.enablePing=n.enablePing,this.enableReconnect=n.enableReconnect||!1}static async connect(e,n){const s=new qt(e,n);return await s.connect(n),s}closeAllSubscriptions(e){for(let[n,s]of this.openSubs)s.close(e);this.openSubs.clear();for(let[n,s]of this.openEventPublishes)s.reject(new Error(e));this.openEventPublishes.clear();for(let[n,s]of this.openCountRequests)s.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(e))}async connect(e){let n;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((s,t)=>{e?.timeout&&(n=setTimeout(()=>{t("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},e.timeout)),e?.abort&&(e.abort.onabort=t);try{this.ws=new this._WebSocket(this.url)}catch(r){clearTimeout(n),t(r);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(n),this._connected=!0;const r=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const i of this.openSubs.values()){if(i.eosed=!1,r)for(let o=0;o<i.filters.length;o++)i.lastEmitted&&(i.filters[o].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),s()},this.ws.onerror=()=>{clearTimeout(n),t("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=r=>{clearTimeout(n),t(r.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,n)=>{if(!this.connectionPromise)return n(new Error(`no connection to ${this.url}, can't ping`));try{const s=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),s.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(s){n(s)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(n=>setTimeout(()=>n(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(e){if(!this.connectionPromise)throw new jt(e,this.url);this.connectionPromise.then(()=>{this.ws?.send(e)})}async auth(e){const n=this.challenge;if(!n)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(s,t)=>{try{let r=await e(ti(this.url,n)),i=setTimeout(()=>{let o=this.openEventPublishes.get(r.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(r.id))},this.publishTimeout);this.openEventPublishes.set(r.id,{resolve:s,reject:t,timeout:i}),this.send('["AUTH",'+JSON.stringify(r)+"]")}catch(r){console.warn("subscribe auth function failed:",r)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.ongoingOperations++;const n=new Promise((s,t)=>{const r=setTimeout(()=>{const i=this.openEventPublishes.get(e.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:s,reject:t,timeout:r})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),n}async count(e,n){this.serial++;const s=n?.id||"count:"+this.serial,t=new Promise((r,i)=>{this.openCountRequests.set(s,{resolve:r,reject:i})});return this.send('["COUNT","'+s+'",'+JSON.stringify(e).substring(1)),t}subscribe(e,n){n.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const s=this.prepareSubscription(e,n);return s.fire(),n.abort&&(n.abort.onabort=()=>s.close(String(n.abort.reason||"<aborted>"))),s}prepareSubscription(e,n){this.serial++;const s=n.id||(n.label?n.label+":":"sub:")+this.serial,t=new si(this,s,e,n);return this.openSubs.set(s,t),t}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(e){const n=e.data;if(!n)return;const s=ni(n);if(s){const t=this.openSubs.get(s);if(!t)return;const r=ei(n,"id"),i=t.alreadyHaveEvent?.(r);if(t.receivedEvent?.(this,r),i)return}try{let t=JSON.parse(n);switch(t[0]){case"EVENT":{const r=this.openSubs.get(t[1]),i=t[2];this.verifyEvent(i)&&Jr(r.filters,i)?r.onevent(i):r.oninvalidevent?.(i),(!r.lastEmitted||r.lastEmitted<i.created_at)&&(r.lastEmitted=i.created_at);return}case"COUNT":{const r=t[1],i=t[2],o=this.openCountRequests.get(r);o&&(o.resolve(i.count),this.openCountRequests.delete(r));return}case"EOSE":{const r=this.openSubs.get(t[1]);if(!r)return;r.receivedEose();return}case"OK":{const r=t[1],i=t[2],o=t[3],l=this.openEventPublishes.get(r);l&&(clearTimeout(l.timeout),i?l.resolve(o):l.reject(new Error(o)),this.openEventPublishes.delete(r));return}case"CLOSED":{const r=t[1],i=this.openSubs.get(r);if(!i)return;i.closed=!0,i.close(t[2]);return}case"NOTICE":{this.onnotice(t[1]);return}case"AUTH":{this.challenge=t[1],this.onauth&&this.auth(this.onauth);return}default:{this.openSubs.get(t[1])?.oncustom?.(t);return}}}catch(t){try{const[r,i,o]=JSON.parse(n);console.warn(`[nostr] relay ${this.url} error processing message:`,t,o)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,t)}return}}},si=class{relay;id;lastEmitted;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oninvalidevent;oneose;onclose;oncustom;eoseTimeout;eoseTimeoutHandle;constructor(e,n,s,t){if(s.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=s,this.id=n,this.alreadyHaveEvent=t.alreadyHaveEvent,this.receivedEvent=t.receivedEvent,this.eoseTimeout=t.eoseTimeout||e.baseEoseTimeout,this.oneose=t.oneose,this.onclose=t.onclose,this.oninvalidevent=t.oninvalidevent,this.onevent=t.onevent||(r=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,r)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(n){if(!(n instanceof jt))throw n}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(e)}},ri=e=>(e[re]=!0,!0),ii=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;enablePing;enableReconnect;automaticallyAuth;trustedRelayURLs=new Set;onRelayConnectionFailure;onRelayConnectionSuccess;allowConnectingToRelay;maxWaitForConnection;_WebSocket;constructor(e){this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,n){e=ye(e);let s=this.relays.get(e);if(s||(s=new qt(e,{verifyEvent:this.trustedRelayURLs.has(e)?ri:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),s.onclose=()=>{this.relays.delete(e)},this.relays.set(e,s)),this.automaticallyAuth){const t=this.automaticallyAuth(e);t&&(s.onauth=t)}try{await s.connect({timeout:n?.connectionTimeout,abort:n?.abort})}catch(t){throw this.relays.delete(e),t}return s}close(e){e.map(ye).forEach(n=>{this.relays.get(n)?.close(),this.relays.delete(n)})}subscribe(e,n,s){const t=[],r=[];for(let i=0;i<e.length;i++){const o=ye(e[i]);t.find(l=>l.url===o)||r.indexOf(o)===-1&&(r.push(o),t.push({url:o,filter:n}))}return this.subscribeMap(t,s)}subscribeMany(e,n,s){return this.subscribe(e,n,s)}subscribeMap(e,n){const s=new Map;for(const c of e){const{url:m,filter:y}=c;s.has(m)||s.set(m,[]),s.get(m).push(y)}const t=Array.from(s.entries()).map(([c,m])=>({url:c,filters:m}));this.trackRelays&&(n.receivedEvent=(c,m)=>{let y=this.seenOn.get(m);y||(y=new Set,this.seenOn.set(m,y)),y.add(c)});const r=new Set,i=[],o=[];let l=c=>{o[c]||(o[c]=!0,o.filter(m=>m).length===t.length&&(n.oneose?.(),l=()=>{}))};const a=[];let d=(c,m)=>{a[c]||(l(c),a[c]=m,a.filter(y=>y).length===t.length&&(n.onclose?.(a),d=()=>{}))};const h=c=>{if(n.alreadyHaveEvent?.(c))return!0;const m=r.has(c);return r.add(c),m},f=Promise.all(t.map(async({url:c,filters:m},y)=>{if(this.allowConnectingToRelay?.(c,["read",m])===!1){d(y,"connection skipped by allowConnectingToRelay");return}let w;try{w=await this.ensureRelay(c,{connectionTimeout:this.maxWaitForConnection<(n.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n.abort})}catch(q){this.onRelayConnectionFailure?.(c),d(y,q?.message||String(q));return}this.onRelayConnectionSuccess?.(c);let P=w.subscribe(m,{...n,oneose:()=>l(y),onclose:q=>{q.startsWith("auth-required: ")&&n.onauth?w.auth(n.onauth).then(()=>{w.subscribe(m,{...n,oneose:()=>l(y),onclose:z=>{d(y,z)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort})}).catch(z=>{d(y,`auth was required and attempted, but failed with: ${z}`)}):d(y,q)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort});i.push(P)}));return{async close(c){await f,i.forEach(m=>{m.close(c)})}}}subscribeEose(e,n,s){let t;return t=this.subscribe(e,n,{...s,oneose(){const r="closed automatically on eose";t?t.close(r):s.onclose?.(e.map(i=>r))}}),t}subscribeManyEose(e,n,s){return this.subscribeEose(e,n,s)}async querySync(e,n,s){return new Promise(async t=>{const r=[];this.subscribeEose(e,n,{...s,onevent(i){r.push(i)},onclose(i){t(r)}})})}async get(e,n,s){n.limit=1;const t=await this.querySync(e,n,s);return t.sort((r,i)=>i.created_at-r.created_at),t[0]||null}publish(e,n,s){return e.map(ye).map(async(t,r,i)=>{if(i.indexOf(t)!==r)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(t,["write",n])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let o;try{o=await this.ensureRelay(t,{connectionTimeout:this.maxWaitForConnection<(s?.maxWait||0)?Math.max(s.maxWait*.8,s.maxWait-1e3):this.maxWaitForConnection,abort:s?.abort})}catch(l){return this.onRelayConnectionFailure?.(t),"connection failure: "+String(l)}return o.publish(n).catch(async l=>{if(l instanceof Error&&l.message.startsWith("auth-required: ")&&s?.onauth)return await o.auth(s.onauth),o.publish(n);throw l}).then(l=>{if(this.trackRelays){let a=this.seenOn.get(n.id);a||(a=new Set,this.seenOn.set(n.id,a)),a.add(o)}return l})})}listConnectionStatus(){const e=new Map;return this.relays.forEach((n,s)=>e.set(s,n.connected)),e}destroy(){this.relays.forEach(e=>e.close()),this.relays=new Map}pruneIdleRelays(e=1e4){const n=[];for(const[s,t]of this.relays)t.idleSince&&Date.now()-t.idleSince>=e&&(this.relays.delete(s),n.push(s),t.close());return n}},Ot;try{Ot=WebSocket}catch{}var oi=class extends ii{constructor(e){super({verifyEvent:Zr,websocketImplementation:Ot,maxWaitForConnection:3e3,...e})}},le=Symbol("verified"),ai=e=>e instanceof Object;function li(e){if(!ai(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let n=0;n<e.tags.length;n++){let s=e.tags[n];if(!Array.isArray(s))return!1;for(let t=0;t<s.length;t++)if(typeof s[t]!="string")return!1}return!0}new TextDecoder("utf-8");var di=new TextEncoder,ci=class{generateSecretKey(){return Z.utils.randomSecretKey()}getPublicKey(e){return C(Z.getPublicKey(e))}finalizeEvent(e,n){const s=e;return s.pubkey=C(Z.getPublicKey(n)),s.id=tn(s),s.sig=C(Z.sign(Y(tn(s)),n)),s[le]=!0,s}verifyEvent(e){if(typeof e[le]=="boolean")return e[le];try{const n=tn(e);if(n!==e.id)return e[le]=!1,!1;const s=Z.verify(Y(e.sig),Y(n),Y(e.pubkey));return e[le]=s,s}catch{return e[le]=!1,!1}}};function ui(e){if(!li(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function tn(e){let n=He(di.encode(ui(e)));return C(n)}var Qe=new ci;Qe.generateSecretKey;Qe.getPublicKey;Qe.finalizeEvent;var fi=Qe.verifyEvent;const pi=8e3;function mi(e){return typeof e=="number"&&gn.includes(e)}function gi(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function hi(e){const n=[];for(const s of e??[])try{const t=new URL(s);if(t.protocol!=="ws:"&&t.protocol!=="wss:")continue;n.push(t.href)}catch{}return[...new Set(n)]}function yi(e){const n=or(e.trim());if(n.type!=="nevent"&&n.type!=="naddr")throw new Error("Enter a NIP-19 nevent or naddr for a NIP-5D napplet manifest event");const s=hi(n.data.relays);if(s.length===0)throw new Error("The pointer does not include relay hints; include at least one relay in the nevent/naddr");if(n.type==="nevent"){if(n.data.kind!==void 0&&!mi(n.data.kind))throw new Error(`nevent points at kind ${n.data.kind}, not a NIP-5D napplet manifest kind`);return{type:"nevent",relays:s,filter:{ids:[n.data.id],kinds:n.data.kind===void 0?[...gn]:[n.data.kind],authors:n.data.author?[n.data.author]:void 0,limit:1}}}if(n.data.kind!==ce)throw new Error(`naddr kind ${n.data.kind} is not the named napplet kind ${ce}`);return{type:"naddr",relays:s,filter:{kinds:[ce],authors:[n.data.pubkey],"#d":[n.data.identifier],limit:1}}}function bi(e){return{id:e.id,pubkey:e.pubkey,kind:e.kind,tags:e.tags,content:e.content}}async function vi(e){const n=typeof e=="string"?new TextEncoder().encode(e):e,s=new Uint8Array(n.byteLength);s.set(n);const t=await crypto.subtle.digest("SHA-256",s.buffer);return[...new Uint8Array(t)].map(r=>r.toString(16).padStart(2,"0")).join("")}function wi(e){const n=[];for(const s of e.tags)if(!(s[0]!=="server"||!s[1]))try{const t=new URL(s[1]);(t.protocol==="http:"||t.protocol==="https:")&&n.push(t.href)}catch{}return[...new Set(n)]}function Ei(e,n){const s=e.endsWith("/")?e:`${e}/`;return new URL(n,s).href}async function Si(e,n=fetch){const s=We(e);if(!s.ok)throw new Error(s.errors.map(o=>o.message).join("; "));const t=e.tags.find(o=>o[0]==="x")[1],r=wi(e);if(r.length===0)throw new Error("Manifest does not include any usable Blossom server hints");const i=[];for(const o of r){const l=Ei(o,t);try{const a=await n(l,{mode:"cors"});if(!a.ok){i.push(`${l}: HTTP ${a.status}`);continue}const d=new Uint8Array(await a.arrayBuffer()),h=await vi(d);if(h!==t){i.push(`${l}: sha256 ${h} did not match manifest ${t}`);continue}return new TextDecoder().decode(d)}catch(a){i.push(`${l}: ${a instanceof Error?a.message:String(a)}`)}}throw new Error(`Unable to fetch verified /index.html from Blossom servers: ${i.join("; ")}`)}async function Ti(e,n){try{const t=await(await n(e,{mode:"cors"})).text();return{source:"url",input:e,label:e,bootUrl:e,html:t,fetched:!0,manifestEvent:null}}catch{return{source:"url",input:e,label:e,bootUrl:e,html:"",fetched:!1,manifestEvent:null}}}async function _i(e,n){const s=yi(e),t=!n.pool,r=n.pool??new oi;try{const i=await r.get(s.relays,{...s.filter},{maxWait:n.maxRelayWaitMs??pi});if(!i)throw new Error("No matching napplet manifest event was found on the pointer relay hints");if(!fi(i))throw new Error("Resolved manifest event signature is invalid");const o=bi(i),l=We(o);if(!l.ok)throw new Error(`Resolved event is not a valid NIP-5D napplet manifest: ${l.errors[0]?.message}`);const a=await Si(o,n.fetcher??fetch),d=(n.createObjectUrl??URL.createObjectURL)(new Blob([a],{type:"text/html;charset=utf-8"})),h=()=>(n.revokeObjectUrl??URL.revokeObjectURL)(d);return{source:"nostr",input:e,label:o.id??e,bootUrl:d,html:a,fetched:!0,manifestEvent:o,revoke:h}}finally{t&&r.destroy()}}async function Ri(e,n={}){const s=e.trim();if(!s)throw new Error("Enter a NIP-19 nevent/naddr, or an HTTP URL for local dev");return gi(s)?Ti(s,n.fetcher??fetch):_i(s,n)}const Ii=`"use strict";
147
11
  var NappletShimPrelude = (() => {
148
12
  var __defProp = Object.defineProperty;
149
13
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -173,7 +37,7 @@ var NappletShimPrelude = (() => {
173
37
  });
174
38
 
175
39
  // ../core/dist/index.js
176
- var NAP_DOMAINS = ["shell", "relay", "identity", "storage", "inc", "theme", "keys", "media", "notify", "config", "resource", "cvm", "outbox", "upload", "intent", "ble", "webrtc", "link", "count", "lists", "serial", "fs", "common", "dm", "gamepad"];
40
+ var NAP_DOMAINS = ["shell", "relay", "identity", "storage", "inc", "theme", "keys", "media", "notify", "config", "resource", "cvm", "outbox", "upload", "intent", "ble", "webrtc", "link", "count", "lists", "serial", "fs", "common", "dm", "gamepad", "llm"];
177
41
  function createDispatch() {
178
42
  const handlers3 = /* @__PURE__ */ new Map();
179
43
  function registerNap2(domain, handler) {
@@ -302,6 +166,134 @@ var NappletShimPrelude = (() => {
302
166
  sendEnvelope(window.parent, message);
303
167
  }
304
168
 
169
+ // ../nap/dist/chunk-WBYAVRXN.js
170
+ var REQUEST_TIMEOUT_MS = 3e4;
171
+ var SELECT_TIMEOUT_MS = 12e4;
172
+ var GENERATE_TIMEOUT_MS = 18e5;
173
+ var RESULT_FIELDS = {
174
+ "llm.select.result": "model",
175
+ "llm.describe.result": "model",
176
+ "llm.generate.result": "result",
177
+ "llm.cancel.result": "cancelled"
178
+ };
179
+ var pending = /* @__PURE__ */ new Map();
180
+ var installed = false;
181
+ var LlmError = class extends Error {
182
+ /** NAP-LLM error code; unknown codes are still failures. */
183
+ code;
184
+ /**
185
+ * @param failure The \`error\` record from a result envelope.
186
+ * @example throw new LlmError({ code: 'selection-expired', message: 'Select a model again.' });
187
+ */
188
+ constructor(failure) {
189
+ super(failure.message);
190
+ this.name = "LlmError";
191
+ this.code = failure.code;
192
+ }
193
+ };
194
+ function isFailure(value) {
195
+ if (!value || typeof value !== "object") return false;
196
+ const record = value;
197
+ return typeof record.code === "string" && record.code.length > 0 && typeof record.message === "string";
198
+ }
199
+ function settle(id, entry) {
200
+ pending.delete(id);
201
+ clearTimeout(entry.timeout);
202
+ entry.cleanup?.();
203
+ }
204
+ function sendRequest(type, payload, timeoutMs, id = crypto.randomUUID()) {
205
+ return new Promise((resolve, reject) => {
206
+ const timeout = setTimeout(() => {
207
+ const entry = pending.get(id);
208
+ if (entry) {
209
+ settle(id, entry);
210
+ reject(new Error(\`\${type} timed out\`));
211
+ }
212
+ }, timeoutMs);
213
+ pending.set(id, { type: \`\${type}.result\`, resolve, reject, timeout, nextSequence: 0 });
214
+ try {
215
+ postToShell({ type, id, ...payload });
216
+ } catch (error) {
217
+ settle(id, pending.get(id));
218
+ reject(error);
219
+ }
220
+ });
221
+ }
222
+ function handleDelta(message) {
223
+ if ("id" in message || typeof message.requestId !== "string" || typeof message.sequence !== "number" || typeof message.text !== "string") return;
224
+ const entry = pending.get(message.requestId);
225
+ if (!entry || entry.type !== "llm.generate.result") return;
226
+ if (message.sequence !== entry.nextSequence) {
227
+ entry.nextSequence = Number.POSITIVE_INFINITY;
228
+ return;
229
+ }
230
+ entry.nextSequence += 1;
231
+ entry.onDelta?.({ requestId: message.requestId, sequence: message.sequence, text: message.text });
232
+ }
233
+ function handleLlmMessage(message) {
234
+ if (message.type === "llm.delta") {
235
+ handleDelta(message);
236
+ return;
237
+ }
238
+ if (typeof message.id !== "string") return;
239
+ const entry = pending.get(message.id);
240
+ if (!entry || entry.type !== message.type) return;
241
+ settle(message.id, entry);
242
+ const field = RESULT_FIELDS[message.type];
243
+ const hasValue = message[field] !== void 0 && message[field] !== null;
244
+ const hasError = message.error !== void 0 && message.error !== null;
245
+ if (hasValue === hasError) {
246
+ entry.reject(new Error(\`\${message.type} must carry exactly one of \${field} or error\`));
247
+ } else if (hasError) {
248
+ entry.reject(isFailure(message.error) ? new LlmError(message.error) : new Error(\`\${message.type} returned a malformed error\`));
249
+ } else {
250
+ entry.resolve(message[field]);
251
+ }
252
+ }
253
+ function select(requirements) {
254
+ return sendRequest("llm.select", requirements === void 0 ? {} : { requirements }, SELECT_TIMEOUT_MS);
255
+ }
256
+ function describe(handle) {
257
+ return sendRequest("llm.describe", { handle }, REQUEST_TIMEOUT_MS);
258
+ }
259
+ function generate(request7, options = {}) {
260
+ const id = crypto.randomUUID();
261
+ const promise = sendRequest("llm.generate", { request: request7 }, GENERATE_TIMEOUT_MS, id);
262
+ const entry = pending.get(id);
263
+ if (entry) {
264
+ entry.onDelta = options.onDelta;
265
+ const signal = options.signal;
266
+ if (signal) {
267
+ const abort = () => {
268
+ void cancel(id).catch(() => void 0);
269
+ };
270
+ if (signal.aborted) abort();
271
+ else {
272
+ signal.addEventListener("abort", abort, { once: true });
273
+ entry.cleanup = () => signal.removeEventListener("abort", abort);
274
+ }
275
+ }
276
+ }
277
+ return Object.assign(promise, { requestId: id });
278
+ }
279
+ function cancel(requestId) {
280
+ return sendRequest("llm.cancel", { requestId }, REQUEST_TIMEOUT_MS);
281
+ }
282
+ function installLlmShim() {
283
+ if (installed) return () => void 0;
284
+ installed = true;
285
+ let disposed = false;
286
+ return () => {
287
+ if (disposed) return;
288
+ disposed = true;
289
+ for (const [id, entry] of pending) {
290
+ settle(id, entry);
291
+ entry.reject(new Error("llm shim disposed"));
292
+ }
293
+ installed = false;
294
+ };
295
+ }
296
+
305
297
  // ../nap/dist/chunk-LNFGQGQD.js
306
298
  function createGamepadStateTools() {
307
299
  function record(value) {
@@ -350,7 +342,7 @@ var NappletShimPrelude = (() => {
350
342
  return tools.copyGamepadState(state2);
351
343
  }
352
344
  var state = { available: true, focused: false, pads: [] };
353
- var installed = false;
345
+ var installed2 = false;
354
346
  var subscribed = false;
355
347
  var handlers = /* @__PURE__ */ new Set();
356
348
  function subscribe() {
@@ -409,8 +401,8 @@ var NappletShimPrelude = (() => {
409
401
  }
410
402
  }
411
403
  function installGamepadShim() {
412
- if (installed) return () => void 0;
413
- installed = true;
404
+ if (installed2) return () => void 0;
405
+ installed2 = true;
414
406
  let closed = false;
415
407
  return () => {
416
408
  if (closed) return;
@@ -419,7 +411,7 @@ var NappletShimPrelude = (() => {
419
411
  if (subscribed) postToShell({ type: "gamepad.unsubscribe" });
420
412
  } finally {
421
413
  subscribed = false;
422
- installed = false;
414
+ installed2 = false;
423
415
  handlers.clear();
424
416
  state = { available: true, focused: false, pads: [] };
425
417
  }
@@ -427,7 +419,7 @@ var NappletShimPrelude = (() => {
427
419
  }
428
420
 
429
421
  // ../nap/dist/chunk-ALQSWWJK.js
430
- var installed2 = false;
422
+ var installed3 = false;
431
423
  var environment;
432
424
  var readyHandlers = /* @__PURE__ */ new Set();
433
425
  var waiters = /* @__PURE__ */ new Set();
@@ -470,11 +462,11 @@ var NappletShimPrelude = (() => {
470
462
  for (const callback of callbacks) callback(environment);
471
463
  }
472
464
  function installShellShim() {
473
- if (installed2) return () => void 0;
474
- installed2 = true;
465
+ if (installed3) return () => void 0;
466
+ installed3 = true;
475
467
  postToShell({ type: "shell.ready" });
476
468
  return () => {
477
- installed2 = false;
469
+ installed3 = false;
478
470
  environment = void 0;
479
471
  readyHandlers.clear();
480
472
  waiters.clear();
@@ -485,7 +477,7 @@ var NappletShimPrelude = (() => {
485
477
  var suppressMap = /* @__PURE__ */ new Map();
486
478
  var actionHandlers = /* @__PURE__ */ new Map();
487
479
  var pendingRegistrations = /* @__PURE__ */ new Map();
488
- var installed3 = false;
480
+ var installed4 = false;
489
481
  var activeCleanup = null;
490
482
  var RESERVED_KEYS = /* @__PURE__ */ new Set(["Tab", "Shift+Tab", "Escape"]);
491
483
  function isMessageType(msg, type) {
@@ -537,14 +529,14 @@ var NappletShimPrelude = (() => {
537
529
  }
538
530
  }
539
531
  function handleRegisterResult(msg) {
540
- const pending4 = pendingRegistrations.get(msg.id);
541
- if (!pending4) return;
532
+ const pending5 = pendingRegistrations.get(msg.id);
533
+ if (!pending5) return;
542
534
  pendingRegistrations.delete(msg.id);
543
535
  if (msg.error) {
544
- pending4.reject(new Error(msg.error));
536
+ pending5.reject(new Error(msg.error));
545
537
  return;
546
538
  }
547
- pending4.resolve({
539
+ pending5.resolve({
548
540
  actionId: msg.actionId,
549
541
  binding: msg.binding
550
542
  });
@@ -632,17 +624,17 @@ var NappletShimPrelude = (() => {
632
624
  };
633
625
  }
634
626
  function installKeysShim() {
635
- if (installed3 && activeCleanup) {
627
+ if (installed4 && activeCleanup) {
636
628
  return activeCleanup;
637
629
  }
638
630
  document.addEventListener("keydown", handleKeydown, true);
639
- installed3 = true;
631
+ installed4 = true;
640
632
  activeCleanup = () => {
641
633
  document.removeEventListener("keydown", handleKeydown, true);
642
634
  suppressMap.clear();
643
635
  actionHandlers.clear();
644
636
  pendingRegistrations.clear();
645
- installed3 = false;
637
+ installed4 = false;
646
638
  activeCleanup = null;
647
639
  };
648
640
  return activeCleanup;
@@ -654,20 +646,20 @@ var NappletShimPrelude = (() => {
654
646
  var controlsHandlers = /* @__PURE__ */ new Map();
655
647
  var stateHandlers = /* @__PURE__ */ new Map();
656
648
  var capabilitiesHandlers = /* @__PURE__ */ new Map();
657
- var installed4 = false;
649
+ var installed5 = false;
658
650
  function isMessageType2(msg, type) {
659
651
  return msg.type === type;
660
652
  }
661
653
  function handleCreateResult(msg) {
662
- const pending4 = pendingCreates.get(msg.id);
663
- if (!pending4) return;
654
+ const pending5 = pendingCreates.get(msg.id);
655
+ if (!pending5) return;
664
656
  pendingCreates.delete(msg.id);
665
- clearTimeout(pending4.timeout);
657
+ clearTimeout(pending5.timeout);
666
658
  const result = {};
667
659
  if (msg.sessionId !== void 0) result.sessionId = msg.sessionId;
668
660
  if (msg.owner !== void 0) result.owner = msg.owner;
669
661
  if (msg.error !== void 0) result.error = msg.error;
670
- pending4.resolve(result);
662
+ pending5.resolve(result);
671
663
  }
672
664
  function handleCommand(msg) {
673
665
  const handlers3 = commandHandlers.get(msg.sessionId);
@@ -838,54 +830,54 @@ var NappletShimPrelude = (() => {
838
830
  };
839
831
  }
840
832
  function installMediaShim() {
841
- if (installed4) {
833
+ if (installed5) {
842
834
  return () => void 0;
843
835
  }
844
- installed4 = true;
836
+ installed5 = true;
845
837
  return () => {
846
- for (const pending4 of pendingCreates.values()) {
847
- clearTimeout(pending4.timeout);
838
+ for (const pending5 of pendingCreates.values()) {
839
+ clearTimeout(pending5.timeout);
848
840
  }
849
841
  pendingCreates.clear();
850
842
  commandHandlers.clear();
851
843
  controlsHandlers.clear();
852
844
  stateHandlers.clear();
853
845
  capabilitiesHandlers.clear();
854
- installed4 = false;
846
+ installed5 = false;
855
847
  };
856
848
  }
857
849
 
858
850
  // ../nap/dist/chunk-2THSWWB3.js
859
- var REQUEST_TIMEOUT_MS = 3e4;
851
+ var REQUEST_TIMEOUT_MS2 = 3e4;
860
852
  var pendingSends = /* @__PURE__ */ new Map();
861
853
  var pendingPermissions = /* @__PURE__ */ new Map();
862
854
  var actionHandlers2 = /* @__PURE__ */ new Set();
863
855
  var clickedHandlers = /* @__PURE__ */ new Set();
864
856
  var dismissedHandlers = /* @__PURE__ */ new Set();
865
857
  var controlsHandlers2 = /* @__PURE__ */ new Set();
866
- var installed5 = false;
858
+ var installed6 = false;
867
859
  function isMessageType3(msg, type) {
868
860
  return msg.type === type;
869
861
  }
870
862
  function handleSendResult(msg) {
871
- const pending4 = pendingSends.get(msg.id);
872
- if (!pending4) return;
863
+ const pending5 = pendingSends.get(msg.id);
864
+ if (!pending5) return;
873
865
  pendingSends.delete(msg.id);
874
866
  if (msg.error) {
875
- pending4.reject(new Error(msg.error));
867
+ pending5.reject(new Error(msg.error));
876
868
  return;
877
869
  }
878
870
  if (msg.notificationId) {
879
- pending4.resolve({ notificationId: msg.notificationId });
871
+ pending5.resolve({ notificationId: msg.notificationId });
880
872
  } else {
881
- pending4.reject(new Error("notify.send.result missing notificationId"));
873
+ pending5.reject(new Error("notify.send.result missing notificationId"));
882
874
  }
883
875
  }
884
876
  function handlePermissionResult(msg) {
885
- const pending4 = pendingPermissions.get(msg.id);
886
- if (!pending4) return;
877
+ const pending5 = pendingPermissions.get(msg.id);
878
+ if (!pending5) return;
887
879
  pendingPermissions.delete(msg.id);
888
- pending4.resolve({ granted: msg.granted });
880
+ pending5.resolve({ granted: msg.granted });
889
881
  }
890
882
  function handleAction2(msg) {
891
883
  for (const cb of actionHandlers2) {
@@ -936,7 +928,7 @@ var NappletShimPrelude = (() => {
936
928
  if (pendingSends.delete(id)) {
937
929
  reject(new Error("notify.send timed out"));
938
930
  }
939
- }, REQUEST_TIMEOUT_MS);
931
+ }, REQUEST_TIMEOUT_MS2);
940
932
  });
941
933
  }
942
934
  function dismiss(notificationId) {
@@ -974,7 +966,7 @@ var NappletShimPrelude = (() => {
974
966
  if (pendingPermissions.delete(id)) {
975
967
  reject(new Error("notify.permission.request timed out"));
976
968
  }
977
- }, REQUEST_TIMEOUT_MS);
969
+ }, REQUEST_TIMEOUT_MS2);
978
970
  });
979
971
  }
980
972
  function onAction2(callback) {
@@ -1010,10 +1002,10 @@ var NappletShimPrelude = (() => {
1010
1002
  };
1011
1003
  }
1012
1004
  function installNotifyShim() {
1013
- if (installed5) {
1005
+ if (installed6) {
1014
1006
  return () => void 0;
1015
1007
  }
1016
- installed5 = true;
1008
+ installed6 = true;
1017
1009
  return () => {
1018
1010
  pendingSends.clear();
1019
1011
  pendingPermissions.clear();
@@ -1021,13 +1013,13 @@ var NappletShimPrelude = (() => {
1021
1013
  clickedHandlers.clear();
1022
1014
  dismissedHandlers.clear();
1023
1015
  controlsHandlers2.clear();
1024
- installed5 = false;
1016
+ installed6 = false;
1025
1017
  };
1026
1018
  }
1027
1019
 
1028
1020
  // ../nap/dist/chunk-Q2OL6E2V.js
1029
1021
  var pendingResponses = /* @__PURE__ */ new Map();
1030
- var REQUEST_TIMEOUT_MS2 = 5e3;
1022
+ var REQUEST_TIMEOUT_MS3 = 5e3;
1031
1023
  function handleStateResponse(event) {
1032
1024
  if (event.source !== window.parent) return;
1033
1025
  const msg = event.data;
@@ -1035,14 +1027,14 @@ var NappletShimPrelude = (() => {
1035
1027
  if (!msg.type.startsWith("storage.") || !msg.type.endsWith(".result")) return;
1036
1028
  const id = msg.id;
1037
1029
  if (!id) return;
1038
- const pending4 = pendingResponses.get(id);
1039
- if (!pending4) return;
1030
+ const pending5 = pendingResponses.get(id);
1031
+ if (!pending5) return;
1040
1032
  pendingResponses.delete(id);
1041
1033
  if (msg.error) {
1042
- pending4.reject(new Error(msg.error));
1034
+ pending5.reject(new Error(msg.error));
1043
1035
  return;
1044
1036
  }
1045
- pending4.resolve(msg);
1037
+ pending5.resolve(msg);
1046
1038
  }
1047
1039
  function sendStorageRequest(message) {
1048
1040
  return new Promise((resolve, reject) => {
@@ -1052,7 +1044,7 @@ var NappletShimPrelude = (() => {
1052
1044
  if (pendingResponses.delete(message.id)) {
1053
1045
  reject(new Error("State request timed out"));
1054
1046
  }
1055
- }, REQUEST_TIMEOUT_MS2);
1047
+ }, REQUEST_TIMEOUT_MS3);
1056
1048
  });
1057
1049
  }
1058
1050
  async function getItemScoped(key, scope) {
@@ -1175,10 +1167,10 @@ var NappletShimPrelude = (() => {
1175
1167
  }
1176
1168
 
1177
1169
  // ../nap/dist/chunk-DMVIO3SO.js
1178
- var REQUEST_TIMEOUT_MS3 = 3e4;
1170
+ var REQUEST_TIMEOUT_MS4 = 3e4;
1179
1171
  var pendingRequests = /* @__PURE__ */ new Map();
1180
1172
  var changeHandlers = /* @__PURE__ */ new Set();
1181
- var installed6 = false;
1173
+ var installed7 = false;
1182
1174
  var IDENTITY_MESSAGE_TYPES = /* @__PURE__ */ new Set([
1183
1175
  "identity.getPublicKey.result",
1184
1176
  "identity.getRelays.result",
@@ -1253,21 +1245,21 @@ var NappletShimPrelude = (() => {
1253
1245
  }
1254
1246
  }
1255
1247
  function resolvePending(id, value) {
1256
- const pending4 = pendingRequests.get(id);
1257
- if (!pending4) return;
1248
+ const pending5 = pendingRequests.get(id);
1249
+ if (!pending5) return;
1258
1250
  pendingRequests.delete(id);
1259
- clearTimeout(pending4.timeout);
1260
- pending4.resolve(value);
1251
+ clearTimeout(pending5.timeout);
1252
+ pending5.resolve(value);
1261
1253
  }
1262
1254
  function resolveOrReject(id, value, error) {
1263
- const pending4 = pendingRequests.get(id);
1264
- if (!pending4) return;
1255
+ const pending5 = pendingRequests.get(id);
1256
+ if (!pending5) return;
1265
1257
  pendingRequests.delete(id);
1266
- clearTimeout(pending4.timeout);
1258
+ clearTimeout(pending5.timeout);
1267
1259
  if (error) {
1268
- pending4.reject(new Error(error));
1260
+ pending5.reject(new Error(error));
1269
1261
  } else {
1270
- pending4.resolve(value);
1262
+ pending5.resolve(value);
1271
1263
  }
1272
1264
  }
1273
1265
  function notifyChanged(pubkey) {
@@ -1276,13 +1268,13 @@ var NappletShimPrelude = (() => {
1276
1268
  handler(pubkey);
1277
1269
  }
1278
1270
  }
1279
- function sendRequest(msg) {
1271
+ function sendRequest2(msg) {
1280
1272
  return new Promise((resolve, reject) => {
1281
1273
  const timeout = setTimeout(() => {
1282
1274
  if (pendingRequests.delete(msg.id)) {
1283
1275
  reject(new Error(\`\${msg.type} timed out\`));
1284
1276
  }
1285
- }, REQUEST_TIMEOUT_MS3);
1277
+ }, REQUEST_TIMEOUT_MS4);
1286
1278
  pendingRequests.set(msg.id, {
1287
1279
  resolve,
1288
1280
  reject,
@@ -1298,7 +1290,7 @@ var NappletShimPrelude = (() => {
1298
1290
  type: "identity.getPublicKey",
1299
1291
  id: crypto.randomUUID()
1300
1292
  };
1301
- return sendRequest(msg);
1293
+ return sendRequest2(msg);
1302
1294
  }
1303
1295
  function onChanged(handler) {
1304
1296
  changeHandlers.add(handler);
@@ -1316,21 +1308,21 @@ var NappletShimPrelude = (() => {
1316
1308
  type: "identity.getRelays",
1317
1309
  id: crypto.randomUUID()
1318
1310
  };
1319
- return sendRequest(msg);
1311
+ return sendRequest2(msg);
1320
1312
  }
1321
1313
  function getProfile() {
1322
1314
  const msg = {
1323
1315
  type: "identity.getProfile",
1324
1316
  id: crypto.randomUUID()
1325
1317
  };
1326
- return sendRequest(msg);
1318
+ return sendRequest2(msg);
1327
1319
  }
1328
1320
  function getFollows() {
1329
1321
  const msg = {
1330
1322
  type: "identity.getFollows",
1331
1323
  id: crypto.randomUUID()
1332
1324
  };
1333
- return sendRequest(msg);
1325
+ return sendRequest2(msg);
1334
1326
  }
1335
1327
  function getList(listType) {
1336
1328
  const msg = {
@@ -1338,56 +1330,56 @@ var NappletShimPrelude = (() => {
1338
1330
  id: crypto.randomUUID(),
1339
1331
  listType
1340
1332
  };
1341
- return sendRequest(msg);
1333
+ return sendRequest2(msg);
1342
1334
  }
1343
1335
  function getZaps() {
1344
1336
  const msg = {
1345
1337
  type: "identity.getZaps",
1346
1338
  id: crypto.randomUUID()
1347
1339
  };
1348
- return sendRequest(msg);
1340
+ return sendRequest2(msg);
1349
1341
  }
1350
1342
  function getMutes() {
1351
1343
  const msg = {
1352
1344
  type: "identity.getMutes",
1353
1345
  id: crypto.randomUUID()
1354
1346
  };
1355
- return sendRequest(msg);
1347
+ return sendRequest2(msg);
1356
1348
  }
1357
1349
  function getBlocked() {
1358
1350
  const msg = {
1359
1351
  type: "identity.getBlocked",
1360
1352
  id: crypto.randomUUID()
1361
1353
  };
1362
- return sendRequest(msg);
1354
+ return sendRequest2(msg);
1363
1355
  }
1364
1356
  function getBadges() {
1365
1357
  const msg = {
1366
1358
  type: "identity.getBadges",
1367
1359
  id: crypto.randomUUID()
1368
1360
  };
1369
- return sendRequest(msg);
1361
+ return sendRequest2(msg);
1370
1362
  }
1371
1363
  function installIdentityShim() {
1372
- if (installed6) {
1364
+ if (installed7) {
1373
1365
  return () => void 0;
1374
1366
  }
1375
- installed6 = true;
1367
+ installed7 = true;
1376
1368
  return () => {
1377
- for (const pending4 of pendingRequests.values()) {
1378
- clearTimeout(pending4.timeout);
1369
+ for (const pending5 of pendingRequests.values()) {
1370
+ clearTimeout(pending5.timeout);
1379
1371
  }
1380
1372
  pendingRequests.clear();
1381
1373
  changeHandlers.clear();
1382
- installed6 = false;
1374
+ installed7 = false;
1383
1375
  };
1384
1376
  }
1385
1377
 
1386
1378
  // ../nap/dist/chunk-K4GHL555.js
1387
- var REQUEST_TIMEOUT_MS4 = 3e4;
1379
+ var REQUEST_TIMEOUT_MS5 = 3e4;
1388
1380
  var pendingRequests2 = /* @__PURE__ */ new Map();
1389
1381
  var changeHandlers2 = /* @__PURE__ */ new Set();
1390
- var installed7 = false;
1382
+ var installed8 = false;
1391
1383
  var THEME_MESSAGE_TYPES = /* @__PURE__ */ new Set([
1392
1384
  "theme.get.result",
1393
1385
  "theme.changed",
@@ -1413,14 +1405,14 @@ var NappletShimPrelude = (() => {
1413
1405
  }
1414
1406
  }
1415
1407
  function resolveOrReject2(id, value, error) {
1416
- const pending4 = pendingRequests2.get(id);
1417
- if (!pending4) return;
1408
+ const pending5 = pendingRequests2.get(id);
1409
+ if (!pending5) return;
1418
1410
  pendingRequests2.delete(id);
1419
- clearTimeout(pending4.timeout);
1411
+ clearTimeout(pending5.timeout);
1420
1412
  if (error) {
1421
- pending4.reject(new Error(error));
1413
+ pending5.reject(new Error(error));
1422
1414
  } else {
1423
- pending4.resolve(value);
1415
+ pending5.resolve(value);
1424
1416
  }
1425
1417
  }
1426
1418
  function notifyChanged2(theme) {
@@ -1428,13 +1420,13 @@ var NappletShimPrelude = (() => {
1428
1420
  handler(theme);
1429
1421
  }
1430
1422
  }
1431
- function sendRequest2(msg) {
1423
+ function sendRequest3(msg) {
1432
1424
  return new Promise((resolve, reject) => {
1433
1425
  const timeout = setTimeout(() => {
1434
1426
  if (pendingRequests2.delete(msg.id)) {
1435
1427
  reject(new Error(\`\${msg.type} timed out\`));
1436
1428
  }
1437
- }, REQUEST_TIMEOUT_MS4);
1429
+ }, REQUEST_TIMEOUT_MS5);
1438
1430
  pendingRequests2.set(msg.id, {
1439
1431
  resolve,
1440
1432
  reject,
@@ -1450,7 +1442,7 @@ var NappletShimPrelude = (() => {
1450
1442
  type: "theme.get",
1451
1443
  id: crypto.randomUUID()
1452
1444
  };
1453
- return sendRequest2(msg);
1445
+ return sendRequest3(msg);
1454
1446
  }
1455
1447
  function onChanged2(handler) {
1456
1448
  changeHandlers2.add(handler);
@@ -1464,17 +1456,17 @@ var NappletShimPrelude = (() => {
1464
1456
  };
1465
1457
  }
1466
1458
  function installThemeShim() {
1467
- if (installed7) {
1459
+ if (installed8) {
1468
1460
  return () => void 0;
1469
1461
  }
1470
- installed7 = true;
1462
+ installed8 = true;
1471
1463
  return () => {
1472
- for (const pending4 of pendingRequests2.values()) {
1473
- clearTimeout(pending4.timeout);
1464
+ for (const pending5 of pendingRequests2.values()) {
1465
+ clearTimeout(pending5.timeout);
1474
1466
  }
1475
1467
  pendingRequests2.clear();
1476
1468
  changeHandlers2.clear();
1477
- installed7 = false;
1469
+ installed8 = false;
1478
1470
  };
1479
1471
  }
1480
1472
 
@@ -1527,7 +1519,7 @@ var NappletShimPrelude = (() => {
1527
1519
  }
1528
1520
 
1529
1521
  // ../nap/dist/chunk-7SQ43TNY.js
1530
- var REQUEST_TIMEOUT_MS5 = 3e4;
1522
+ var REQUEST_TIMEOUT_MS6 = 3e4;
1531
1523
  var MAX_RETAINED_OPENED = 100;
1532
1524
  var MAX_RETAINED_EVENTS = 100;
1533
1525
  var topicHandlers = /* @__PURE__ */ new Map();
@@ -1672,7 +1664,7 @@ var NappletShimPrelude = (() => {
1672
1664
  return new Promise((resolve, reject) => {
1673
1665
  const timeout = setTimeout(() => {
1674
1666
  if (pendingOpen.delete(id)) reject(new Error("inc.channel.open timed out"));
1675
- }, REQUEST_TIMEOUT_MS5);
1667
+ }, REQUEST_TIMEOUT_MS6);
1676
1668
  pendingOpen.set(id, { target, resolve, reject, timeout });
1677
1669
  const message = {
1678
1670
  type: "inc.channel.open",
@@ -1699,7 +1691,7 @@ var NappletShimPrelude = (() => {
1699
1691
  return new Promise((resolve, reject) => {
1700
1692
  const timeout = setTimeout(() => {
1701
1693
  if (pendingList.delete(id)) reject(new Error("inc.channel.list timed out"));
1702
- }, REQUEST_TIMEOUT_MS5);
1694
+ }, REQUEST_TIMEOUT_MS6);
1703
1695
  pendingList.set(id, { resolve, reject, timeout });
1704
1696
  const message = {
1705
1697
  type: "inc.channel.list",
@@ -1731,15 +1723,15 @@ var NappletShimPrelude = (() => {
1731
1723
  for (const callback of handlers3) callback(event);
1732
1724
  }
1733
1725
  function handleOpenResult(msg) {
1734
- const pending4 = pendingOpen.get(msg.id);
1735
- if (!pending4) return;
1726
+ const pending5 = pendingOpen.get(msg.id);
1727
+ if (!pending5) return;
1736
1728
  pendingOpen.delete(msg.id);
1737
- clearTimeout(pending4.timeout);
1729
+ clearTimeout(pending5.timeout);
1738
1730
  if (!msg.channelId) {
1739
- pending4.reject(new Error(msg.error ?? "inc.channel.open failed"));
1731
+ pending5.reject(new Error(msg.error ?? "inc.channel.open failed"));
1740
1732
  return;
1741
1733
  }
1742
- pending4.resolve(createHandle(msg.channelId, msg.peer ?? pending4.target));
1734
+ pending5.resolve(createHandle(msg.channelId, msg.peer ?? pending5.target));
1743
1735
  }
1744
1736
  function handleOpened(msg) {
1745
1737
  retainOpened(createHandle(msg.channelId, msg.peer));
@@ -1763,11 +1755,11 @@ var NappletShimPrelude = (() => {
1763
1755
  state2.events.push(event);
1764
1756
  }
1765
1757
  function handleListResult(msg) {
1766
- const pending4 = pendingList.get(msg.id);
1767
- if (!pending4) return;
1758
+ const pending5 = pendingList.get(msg.id);
1759
+ if (!pending5) return;
1768
1760
  pendingList.delete(msg.id);
1769
- clearTimeout(pending4.timeout);
1770
- pending4.resolve(msg.channels);
1761
+ clearTimeout(pending5.timeout);
1762
+ pending5.resolve(msg.channels);
1771
1763
  }
1772
1764
  function handleClosed(msg) {
1773
1765
  const state2 = channels.get(msg.channelId);
@@ -1838,13 +1830,13 @@ var NappletShimPrelude = (() => {
1838
1830
  }
1839
1831
  function installIncShim() {
1840
1832
  return () => {
1841
- for (const pending4 of pendingOpen.values()) {
1842
- clearTimeout(pending4.timeout);
1843
- pending4.reject(new Error("INC shim disposed"));
1833
+ for (const pending5 of pendingOpen.values()) {
1834
+ clearTimeout(pending5.timeout);
1835
+ pending5.reject(new Error("INC shim disposed"));
1844
1836
  }
1845
- for (const pending4 of pendingList.values()) {
1846
- clearTimeout(pending4.timeout);
1847
- pending4.reject(new Error("INC shim disposed"));
1837
+ for (const pending5 of pendingList.values()) {
1838
+ clearTimeout(pending5.timeout);
1839
+ pending5.reject(new Error("INC shim disposed"));
1848
1840
  }
1849
1841
  for (const state2 of channels.values()) closeState(state2, "endpoint destroyed", true);
1850
1842
  pendingOpen.clear();
@@ -1860,14 +1852,14 @@ var NappletShimPrelude = (() => {
1860
1852
  function isMessageType4(msg, type) {
1861
1853
  return msg.type === type;
1862
1854
  }
1863
- var REQUEST_TIMEOUT_MS6 = 3e4;
1855
+ var REQUEST_TIMEOUT_MS7 = 3e4;
1864
1856
  var currentSchema = null;
1865
1857
  var lastValues = null;
1866
1858
  var subscribers = /* @__PURE__ */ new Set();
1867
1859
  var schemaErrorHandlers = /* @__PURE__ */ new Set();
1868
1860
  var pendingGets = /* @__PURE__ */ new Map();
1869
1861
  var pendingRegistrations2 = /* @__PURE__ */ new Map();
1870
- var installed8 = false;
1862
+ var installed9 = false;
1871
1863
  function handleConfigMessage(msg) {
1872
1864
  if (isMessageType4(msg, "config.registerSchema.result")) {
1873
1865
  handleRegisterSchemaResult(msg);
@@ -1878,25 +1870,25 @@ var NappletShimPrelude = (() => {
1878
1870
  }
1879
1871
  }
1880
1872
  function handleRegisterSchemaResult(msg) {
1881
- const pending4 = pendingRegistrations2.get(msg.id);
1882
- if (!pending4) return;
1873
+ const pending5 = pendingRegistrations2.get(msg.id);
1874
+ if (!pending5) return;
1883
1875
  pendingRegistrations2.delete(msg.id);
1884
1876
  if (msg.ok) {
1885
- currentSchema = pending4.schema;
1886
- pending4.resolve();
1877
+ currentSchema = pending5.schema;
1878
+ pending5.resolve();
1887
1879
  } else {
1888
1880
  const code = msg.code ?? "invalid-schema";
1889
1881
  const error = msg.error ?? "schema rejected";
1890
- pending4.reject(new Error(\`\${code}: \${error}\`));
1882
+ pending5.reject(new Error(\`\${code}: \${error}\`));
1891
1883
  }
1892
1884
  }
1893
1885
  function handleValues(msg) {
1894
1886
  lastValues = msg.values;
1895
1887
  if (typeof msg.id === "string") {
1896
- const pending4 = pendingGets.get(msg.id);
1897
- if (!pending4) return;
1888
+ const pending5 = pendingGets.get(msg.id);
1889
+ if (!pending5) return;
1898
1890
  pendingGets.delete(msg.id);
1899
- pending4.resolve(msg.values);
1891
+ pending5.resolve(msg.values);
1900
1892
  return;
1901
1893
  }
1902
1894
  for (const cb of subscribers) {
@@ -1925,7 +1917,7 @@ var NappletShimPrelude = (() => {
1925
1917
  if (pendingRegistrations2.delete(id)) {
1926
1918
  reject(new Error("config.registerSchema timed out"));
1927
1919
  }
1928
- }, REQUEST_TIMEOUT_MS6);
1920
+ }, REQUEST_TIMEOUT_MS7);
1929
1921
  });
1930
1922
  }
1931
1923
  function get2() {
@@ -1938,7 +1930,7 @@ var NappletShimPrelude = (() => {
1938
1930
  if (pendingGets.delete(id)) {
1939
1931
  reject(new Error("config.get timed out"));
1940
1932
  }
1941
- }, REQUEST_TIMEOUT_MS6);
1933
+ }, REQUEST_TIMEOUT_MS7);
1942
1934
  });
1943
1935
  }
1944
1936
  function subscribe2(callback) {
@@ -1980,7 +1972,7 @@ var NappletShimPrelude = (() => {
1980
1972
  };
1981
1973
  }
1982
1974
  function installConfigShim() {
1983
- if (installed8) {
1975
+ if (installed9) {
1984
1976
  return () => void 0;
1985
1977
  }
1986
1978
  const configWindow = window;
@@ -1998,7 +1990,7 @@ var NappletShimPrelude = (() => {
1998
1990
  configurable: false
1999
1991
  });
2000
1992
  napplet.config = api;
2001
- installed8 = true;
1993
+ installed9 = true;
2002
1994
  return () => {
2003
1995
  subscribers.clear();
2004
1996
  schemaErrorHandlers.clear();
@@ -2007,17 +1999,17 @@ var NappletShimPrelude = (() => {
2007
1999
  lastValues = null;
2008
2000
  currentSchema = null;
2009
2001
  if (napplet.config === api) delete napplet.config;
2010
- installed8 = false;
2002
+ installed9 = false;
2011
2003
  };
2012
2004
  }
2013
2005
 
2014
2006
  // ../nap/dist/chunk-UVOJ27SS.js
2015
- var REQUEST_TIMEOUT_MS7 = 3e4;
2007
+ var REQUEST_TIMEOUT_MS8 = 3e4;
2016
2008
  var inflight = /* @__PURE__ */ new Map();
2017
2009
  var pendingBytes = /* @__PURE__ */ new Map();
2018
2010
  var pendingInfo = /* @__PURE__ */ new Map();
2019
2011
  var pendingMany = /* @__PURE__ */ new Map();
2020
- var installed9 = false;
2012
+ var installed10 = false;
2021
2013
  function isMessageType5(msg, type) {
2022
2014
  return msg.type === type;
2023
2015
  }
@@ -2072,7 +2064,7 @@ var NappletShimPrelude = (() => {
2072
2064
  if (pendingInfo.delete(id)) {
2073
2065
  reject(new Error("resource.info timed out"));
2074
2066
  }
2075
- }, REQUEST_TIMEOUT_MS7);
2067
+ }, REQUEST_TIMEOUT_MS8);
2076
2068
  pendingInfo.set(id, { resolve, reject, timeout });
2077
2069
  const msg = {
2078
2070
  type: "resource.info",
@@ -2087,7 +2079,7 @@ var NappletShimPrelude = (() => {
2087
2079
  if (pendingBytes.delete(id)) {
2088
2080
  reject(new Error(\`resource.bytes timed out for \${url}\`));
2089
2081
  }
2090
- }, REQUEST_TIMEOUT_MS7);
2082
+ }, REQUEST_TIMEOUT_MS8);
2091
2083
  pendingBytes.set(id, { resolve, reject, timeout });
2092
2084
  const msg = {
2093
2085
  type: "resource.bytes",
@@ -2104,7 +2096,7 @@ var NappletShimPrelude = (() => {
2104
2096
  if (pendingMany.delete(id)) {
2105
2097
  reject(new Error(\`resource.bytesMany timed out for \${requests.length} requests\`));
2106
2098
  }
2107
- }, REQUEST_TIMEOUT_MS7);
2099
+ }, REQUEST_TIMEOUT_MS8);
2108
2100
  pendingMany.set(id, { resolve, reject, timeout });
2109
2101
  const msg = {
2110
2102
  type: "resource.bytesMany",
@@ -2250,16 +2242,16 @@ var NappletShimPrelude = (() => {
2250
2242
  });
2251
2243
  }
2252
2244
  function installResourceShim() {
2253
- if (installed9) {
2245
+ if (installed10) {
2254
2246
  return () => void 0;
2255
2247
  }
2256
- installed9 = true;
2248
+ installed10 = true;
2257
2249
  return () => {
2258
2250
  inflight.clear();
2259
2251
  pendingInfo.clear();
2260
2252
  pendingBytes.clear();
2261
2253
  pendingMany.clear();
2262
- installed9 = false;
2254
+ installed10 = false;
2263
2255
  };
2264
2256
  }
2265
2257
  function info() {
@@ -2342,7 +2334,7 @@ var NappletShimPrelude = (() => {
2342
2334
  }
2343
2335
 
2344
2336
  // ../nap/dist/chunk-BFHWB3MF.js
2345
- var REQUEST_TIMEOUT_MS8 = 3e4;
2337
+ var REQUEST_TIMEOUT_MS9 = 3e4;
2346
2338
  var pendingDiscover = /* @__PURE__ */ new Map();
2347
2339
  var pendingRequest = /* @__PURE__ */ new Map();
2348
2340
  var pendingClose = /* @__PURE__ */ new Map();
@@ -2351,9 +2343,9 @@ var NappletShimPrelude = (() => {
2351
2343
  var pendingRegistryDescribe = /* @__PURE__ */ new Map();
2352
2344
  var pendingRegistryCall = /* @__PURE__ */ new Map();
2353
2345
  var eventHandlers = /* @__PURE__ */ new Set();
2354
- var installed10 = false;
2346
+ var installed11 = false;
2355
2347
  function setInstalled(value) {
2356
- installed10 = value;
2348
+ installed11 = value;
2357
2349
  }
2358
2350
  function isMessageType6(msg, type) {
2359
2351
  return msg.type === type;
@@ -2477,7 +2469,7 @@ var NappletShimPrelude = (() => {
2477
2469
  return new Promise((resolve, reject) => {
2478
2470
  const timeout = setTimeout(() => {
2479
2471
  if (pendingDiscover.delete(id)) reject(new Error("cvm.discover timed out"));
2480
- }, REQUEST_TIMEOUT_MS8);
2472
+ }, REQUEST_TIMEOUT_MS9);
2481
2473
  pendingDiscover.set(id, { resolve, reject, timeout });
2482
2474
  const msg = {
2483
2475
  type: "cvm.discover",
@@ -2489,7 +2481,7 @@ var NappletShimPrelude = (() => {
2489
2481
  }
2490
2482
  function request(server, message, options) {
2491
2483
  const id = crypto.randomUUID();
2492
- const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS8;
2484
+ const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS9;
2493
2485
  return new Promise((resolve, reject) => {
2494
2486
  const timeout = setTimeout(() => {
2495
2487
  if (pendingRequest.delete(id)) reject(new Error("cvm.request timed out"));
@@ -2554,7 +2546,7 @@ var NappletShimPrelude = (() => {
2554
2546
  return new Promise((resolve, reject) => {
2555
2547
  const timeout = setTimeout(() => {
2556
2548
  if (pendingClose.delete(id)) reject(new Error("cvm.close timed out"));
2557
- }, REQUEST_TIMEOUT_MS8);
2549
+ }, REQUEST_TIMEOUT_MS9);
2558
2550
  pendingClose.set(id, { resolve, reject, timeout });
2559
2551
  const msg = {
2560
2552
  type: "cvm.close",
@@ -2577,7 +2569,7 @@ var NappletShimPrelude = (() => {
2577
2569
  return new Promise((resolve, reject) => {
2578
2570
  const timeout = setTimeout(() => {
2579
2571
  if (pendingRegistryList.delete(id)) reject(new Error("cvm.registry.list timed out"));
2580
- }, REQUEST_TIMEOUT_MS8);
2572
+ }, REQUEST_TIMEOUT_MS9);
2581
2573
  pendingRegistryList.set(id, { resolve, reject, timeout });
2582
2574
  const msg = {
2583
2575
  type: "cvm.registry.list",
@@ -2592,7 +2584,7 @@ var NappletShimPrelude = (() => {
2592
2584
  return new Promise((resolve, reject) => {
2593
2585
  const timeout = setTimeout(() => {
2594
2586
  if (pendingRegistryHas.delete(id)) reject(new Error("cvm.registry.has timed out"));
2595
- }, REQUEST_TIMEOUT_MS8);
2587
+ }, REQUEST_TIMEOUT_MS9);
2596
2588
  pendingRegistryHas.set(id, { resolve, reject, timeout });
2597
2589
  const msg = {
2598
2590
  type: "cvm.registry.has",
@@ -2608,7 +2600,7 @@ var NappletShimPrelude = (() => {
2608
2600
  return new Promise((resolve, reject) => {
2609
2601
  const timeout = setTimeout(() => {
2610
2602
  if (pendingRegistryDescribe.delete(id)) reject(new Error("cvm.registry.describe timed out"));
2611
- }, REQUEST_TIMEOUT_MS8);
2603
+ }, REQUEST_TIMEOUT_MS9);
2612
2604
  pendingRegistryDescribe.set(id, { resolve, reject, timeout });
2613
2605
  const msg = {
2614
2606
  type: "cvm.registry.describe",
@@ -2621,7 +2613,7 @@ var NappletShimPrelude = (() => {
2621
2613
  }
2622
2614
  function registryCall(family, tool, args, options) {
2623
2615
  const id = crypto.randomUUID();
2624
- const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS8;
2616
+ const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS9;
2625
2617
  return new Promise((resolve, reject) => {
2626
2618
  const timeout = setTimeout(() => {
2627
2619
  if (pendingRegistryCall.delete(id)) reject(new Error("cvm.registry.call timed out"));
@@ -2639,10 +2631,10 @@ var NappletShimPrelude = (() => {
2639
2631
  });
2640
2632
  }
2641
2633
  function installCvmShim() {
2642
- if (installed10) return () => void 0;
2634
+ if (installed11) return () => void 0;
2643
2635
  setInstalled(true);
2644
2636
  return () => {
2645
- for (const pending4 of [
2637
+ for (const pending5 of [
2646
2638
  ...pendingDiscover.values(),
2647
2639
  ...pendingRequest.values(),
2648
2640
  ...pendingClose.values(),
@@ -2650,7 +2642,7 @@ var NappletShimPrelude = (() => {
2650
2642
  ...pendingRegistryHas.values(),
2651
2643
  ...pendingRegistryDescribe.values(),
2652
2644
  ...pendingRegistryCall.values()
2653
- ]) clearTimeout(pending4.timeout);
2645
+ ]) clearTimeout(pending5.timeout);
2654
2646
  pendingDiscover.clear();
2655
2647
  pendingRequest.clear();
2656
2648
  pendingClose.clear();
@@ -2664,13 +2656,13 @@ var NappletShimPrelude = (() => {
2664
2656
  }
2665
2657
 
2666
2658
  // ../nap/dist/chunk-FPY43PPU.js
2667
- var REQUEST_TIMEOUT_MS9 = 3e4;
2659
+ var REQUEST_TIMEOUT_MS10 = 3e4;
2668
2660
  var pendingGetEvent = /* @__PURE__ */ new Map();
2669
2661
  var pendingQuery = /* @__PURE__ */ new Map();
2670
2662
  var pendingPublish = /* @__PURE__ */ new Map();
2671
2663
  var pendingResolve = /* @__PURE__ */ new Map();
2672
2664
  var subscriptions = /* @__PURE__ */ new Map();
2673
- var installed11 = false;
2665
+ var installed12 = false;
2674
2666
  function isMessageType7(msg, type) {
2675
2667
  return msg.type === type;
2676
2668
  }
@@ -2758,7 +2750,7 @@ var NappletShimPrelude = (() => {
2758
2750
  }
2759
2751
  function getEvent(eventId, options) {
2760
2752
  const id = crypto.randomUUID();
2761
- const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS9;
2753
+ const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS10;
2762
2754
  return new Promise((resolve, reject) => {
2763
2755
  const timeout = setTimeout(() => {
2764
2756
  if (pendingGetEvent.delete(id)) reject(new Error("outbox.getEvent timed out"));
@@ -2775,7 +2767,7 @@ var NappletShimPrelude = (() => {
2775
2767
  }
2776
2768
  function query(filters, options) {
2777
2769
  const id = crypto.randomUUID();
2778
- const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS9;
2770
+ const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS10;
2779
2771
  return new Promise((resolve, reject) => {
2780
2772
  const timeout = setTimeout(() => {
2781
2773
  if (pendingQuery.delete(id)) reject(new Error("outbox.query timed out"));
@@ -2828,7 +2820,7 @@ var NappletShimPrelude = (() => {
2828
2820
  return new Promise((resolve, reject) => {
2829
2821
  const timeout = setTimeout(() => {
2830
2822
  if (pendingPublish.delete(id)) reject(new Error("outbox.publish timed out"));
2831
- }, REQUEST_TIMEOUT_MS9);
2823
+ }, REQUEST_TIMEOUT_MS10);
2832
2824
  pendingPublish.set(id, { resolve, reject, timeout });
2833
2825
  const msg = {
2834
2826
  type: "outbox.publish",
@@ -2844,7 +2836,7 @@ var NappletShimPrelude = (() => {
2844
2836
  return new Promise((resolve, reject) => {
2845
2837
  const timeout = setTimeout(() => {
2846
2838
  if (pendingResolve.delete(id)) reject(new Error("outbox.resolveRelays timed out"));
2847
- }, REQUEST_TIMEOUT_MS9);
2839
+ }, REQUEST_TIMEOUT_MS10);
2848
2840
  pendingResolve.set(id, { resolve, reject, timeout });
2849
2841
  const msg = {
2850
2842
  type: "outbox.resolveRelays",
@@ -2855,10 +2847,10 @@ var NappletShimPrelude = (() => {
2855
2847
  });
2856
2848
  }
2857
2849
  function installOutboxShim() {
2858
- if (installed11) {
2850
+ if (installed12) {
2859
2851
  return () => void 0;
2860
2852
  }
2861
- installed11 = true;
2853
+ installed12 = true;
2862
2854
  return () => {
2863
2855
  for (const p of pendingGetEvent.values()) clearTimeout(p.timeout);
2864
2856
  for (const p of pendingQuery.values()) clearTimeout(p.timeout);
@@ -2869,17 +2861,17 @@ var NappletShimPrelude = (() => {
2869
2861
  pendingPublish.clear();
2870
2862
  pendingResolve.clear();
2871
2863
  subscriptions.clear();
2872
- installed11 = false;
2864
+ installed12 = false;
2873
2865
  };
2874
2866
  }
2875
2867
 
2876
2868
  // ../nap/dist/chunk-QCYYTDDB.js
2877
- var REQUEST_TIMEOUT_MS10 = 3e4;
2869
+ var REQUEST_TIMEOUT_MS11 = 3e4;
2878
2870
  var pendingInfo2 = /* @__PURE__ */ new Map();
2879
2871
  var pendingUpload = /* @__PURE__ */ new Map();
2880
2872
  var pendingStatus = /* @__PURE__ */ new Map();
2881
2873
  var statusHandlers = /* @__PURE__ */ new Set();
2882
- var installed12 = false;
2874
+ var installed13 = false;
2883
2875
  function isMessageType8(msg, type) {
2884
2876
  return msg.type === type;
2885
2877
  }
@@ -2936,7 +2928,7 @@ var NappletShimPrelude = (() => {
2936
2928
  return new Promise((resolve, reject) => {
2937
2929
  const timeout = setTimeout(() => {
2938
2930
  if (pendingInfo2.delete(id)) reject(new Error("upload.info timed out"));
2939
- }, REQUEST_TIMEOUT_MS10);
2931
+ }, REQUEST_TIMEOUT_MS11);
2940
2932
  pendingInfo2.set(id, { resolve, reject, timeout });
2941
2933
  const msg = {
2942
2934
  type: "upload.info",
@@ -2950,7 +2942,7 @@ var NappletShimPrelude = (() => {
2950
2942
  return new Promise((resolve, reject) => {
2951
2943
  const timeout = setTimeout(() => {
2952
2944
  if (pendingUpload.delete(id)) reject(new Error("upload.upload timed out"));
2953
- }, REQUEST_TIMEOUT_MS10);
2945
+ }, REQUEST_TIMEOUT_MS11);
2954
2946
  pendingUpload.set(id, { resolve, reject, timeout });
2955
2947
  const msg = {
2956
2948
  type: "upload.upload",
@@ -2965,7 +2957,7 @@ var NappletShimPrelude = (() => {
2965
2957
  return new Promise((resolve, reject) => {
2966
2958
  const timeout = setTimeout(() => {
2967
2959
  if (pendingStatus.delete(id)) reject(new Error("upload.status timed out"));
2968
- }, REQUEST_TIMEOUT_MS10);
2960
+ }, REQUEST_TIMEOUT_MS11);
2969
2961
  pendingStatus.set(id, { resolve, reject, timeout });
2970
2962
  const msg = {
2971
2963
  type: "upload.status",
@@ -2984,10 +2976,10 @@ var NappletShimPrelude = (() => {
2984
2976
  };
2985
2977
  }
2986
2978
  function installUploadShim() {
2987
- if (installed12) {
2979
+ if (installed13) {
2988
2980
  return () => void 0;
2989
2981
  }
2990
- installed12 = true;
2982
+ installed13 = true;
2991
2983
  return () => {
2992
2984
  for (const p of pendingInfo2.values()) clearTimeout(p.timeout);
2993
2985
  for (const p of pendingUpload.values()) clearTimeout(p.timeout);
@@ -2996,7 +2988,7 @@ var NappletShimPrelude = (() => {
2996
2988
  pendingUpload.clear();
2997
2989
  pendingStatus.clear();
2998
2990
  statusHandlers.clear();
2999
- installed12 = false;
2991
+ installed13 = false;
3000
2992
  };
3001
2993
  }
3002
2994
 
@@ -3558,14 +3550,14 @@ var NappletShimPrelude = (() => {
3558
3550
  ...handlerHint !== void 0 ? { handlerHint } : {}
3559
3551
  };
3560
3552
  }
3561
- var REQUEST_TIMEOUT_MS11 = 3e4;
3553
+ var REQUEST_TIMEOUT_MS12 = 3e4;
3562
3554
  var pendingInvoke = /* @__PURE__ */ new Map();
3563
3555
  var pendingAvailable = /* @__PURE__ */ new Map();
3564
3556
  var pendingHandlers = /* @__PURE__ */ new Map();
3565
3557
  var deliveryHandlers = /* @__PURE__ */ new Set();
3566
3558
  var deliveries = [];
3567
3559
  var changedHandlers = /* @__PURE__ */ new Set();
3568
- var installed13 = false;
3560
+ var installed14 = false;
3569
3561
  function isMessageType9(msg, type) {
3570
3562
  return msg.type === type;
3571
3563
  }
@@ -3576,37 +3568,37 @@ var NappletShimPrelude = (() => {
3576
3568
  return result.ok === true && typeof result.archetype === "string" && typeof result.action === "string" && typeof result.convention === "string" && typeof result.handler === "string";
3577
3569
  }
3578
3570
  function handleInvokeResult(msg) {
3579
- const pending4 = pendingInvoke.get(msg.id);
3580
- if (!pending4) return;
3571
+ const pending5 = pendingInvoke.get(msg.id);
3572
+ if (!pending5) return;
3581
3573
  pendingInvoke.delete(msg.id);
3582
- clearTimeout(pending4.timeout);
3574
+ clearTimeout(pending5.timeout);
3583
3575
  if (isIntentResult(msg.result)) {
3584
- pending4.resolve(msg.result);
3576
+ pending5.resolve(msg.result);
3585
3577
  return;
3586
3578
  }
3587
- pending4.reject(new Error("invalid intent.invoke.result"));
3579
+ pending5.reject(new Error("invalid intent.invoke.result"));
3588
3580
  }
3589
3581
  function handleAvailableResult(msg) {
3590
- const pending4 = pendingAvailable.get(msg.id);
3591
- if (!pending4) return;
3582
+ const pending5 = pendingAvailable.get(msg.id);
3583
+ if (!pending5) return;
3592
3584
  pendingAvailable.delete(msg.id);
3593
- clearTimeout(pending4.timeout);
3585
+ clearTimeout(pending5.timeout);
3594
3586
  if (msg.availability !== void 0) {
3595
- pending4.resolve(msg.availability);
3587
+ pending5.resolve(msg.availability);
3596
3588
  return;
3597
3589
  }
3598
- pending4.reject(new Error(msg.error ?? "intent availability unavailable"));
3590
+ pending5.reject(new Error(msg.error ?? "intent availability unavailable"));
3599
3591
  }
3600
3592
  function handleHandlersResult(msg) {
3601
- const pending4 = pendingHandlers.get(msg.id);
3602
- if (!pending4) return;
3593
+ const pending5 = pendingHandlers.get(msg.id);
3594
+ if (!pending5) return;
3603
3595
  pendingHandlers.delete(msg.id);
3604
- clearTimeout(pending4.timeout);
3596
+ clearTimeout(pending5.timeout);
3605
3597
  if (msg.handlers !== void 0) {
3606
- pending4.resolve(msg.handlers);
3598
+ pending5.resolve(msg.handlers);
3607
3599
  return;
3608
3600
  }
3609
- pending4.reject(new Error(msg.error ?? "intent handlers unavailable"));
3601
+ pending5.reject(new Error(msg.error ?? "intent handlers unavailable"));
3610
3602
  }
3611
3603
  function handleChanged(msg) {
3612
3604
  if (!msg.availability) return;
@@ -3632,7 +3624,7 @@ var NappletShimPrelude = (() => {
3632
3624
  return new Promise((resolve, reject) => {
3633
3625
  const timeout = setTimeout(() => {
3634
3626
  if (pendingInvoke.delete(id)) reject(new Error("intent.invoke timed out"));
3635
- }, REQUEST_TIMEOUT_MS11);
3627
+ }, REQUEST_TIMEOUT_MS12);
3636
3628
  pendingInvoke.set(id, { resolve, reject, timeout });
3637
3629
  const msg = {
3638
3630
  type: "intent.invoke",
@@ -3653,7 +3645,7 @@ var NappletShimPrelude = (() => {
3653
3645
  return new Promise((resolve, reject) => {
3654
3646
  const timeout = setTimeout(() => {
3655
3647
  if (pendingAvailable.delete(id)) reject(new Error("intent.available timed out"));
3656
- }, REQUEST_TIMEOUT_MS11);
3648
+ }, REQUEST_TIMEOUT_MS12);
3657
3649
  pendingAvailable.set(id, { resolve, reject, timeout });
3658
3650
  const msg = {
3659
3651
  type: "intent.available",
@@ -3668,7 +3660,7 @@ var NappletShimPrelude = (() => {
3668
3660
  return new Promise((resolve, reject) => {
3669
3661
  const timeout = setTimeout(() => {
3670
3662
  if (pendingHandlers.delete(id)) reject(new Error("intent.handlers timed out"));
3671
- }, REQUEST_TIMEOUT_MS11);
3663
+ }, REQUEST_TIMEOUT_MS12);
3672
3664
  pendingHandlers.set(id, { resolve, reject, timeout });
3673
3665
  const msg = {
3674
3666
  type: "intent.handlers",
@@ -3694,27 +3686,27 @@ var NappletShimPrelude = (() => {
3694
3686
  } };
3695
3687
  }
3696
3688
  function installIntentShim() {
3697
- if (installed13) return () => void 0;
3698
- installed13 = true;
3689
+ if (installed14) return () => void 0;
3690
+ installed14 = true;
3699
3691
  return () => {
3700
- for (const pending4 of pendingInvoke.values()) clearTimeout(pending4.timeout);
3701
- for (const pending4 of pendingAvailable.values()) clearTimeout(pending4.timeout);
3702
- for (const pending4 of pendingHandlers.values()) clearTimeout(pending4.timeout);
3692
+ for (const pending5 of pendingInvoke.values()) clearTimeout(pending5.timeout);
3693
+ for (const pending5 of pendingAvailable.values()) clearTimeout(pending5.timeout);
3694
+ for (const pending5 of pendingHandlers.values()) clearTimeout(pending5.timeout);
3703
3695
  pendingInvoke.clear();
3704
3696
  pendingAvailable.clear();
3705
3697
  pendingHandlers.clear();
3706
3698
  changedHandlers.clear();
3707
3699
  deliveryHandlers.clear();
3708
3700
  deliveries.length = 0;
3709
- installed13 = false;
3701
+ installed14 = false;
3710
3702
  };
3711
3703
  }
3712
3704
 
3713
3705
  // ../nap/dist/chunk-5QWBBZC6.js
3714
- var REQUEST_TIMEOUT_MS12 = 3e4;
3715
- var pending = /* @__PURE__ */ new Map();
3706
+ var REQUEST_TIMEOUT_MS13 = 3e4;
3707
+ var pending2 = /* @__PURE__ */ new Map();
3716
3708
  var eventHandlers2 = /* @__PURE__ */ new Set();
3717
- var installed14 = false;
3709
+ var installed15 = false;
3718
3710
  var WEBRTC_MESSAGE_TYPES = /* @__PURE__ */ new Set([
3719
3711
  "webrtc.open",
3720
3712
  "webrtc.open.result",
@@ -3730,9 +3722,9 @@ var NappletShimPrelude = (() => {
3730
3722
  function request2(msg, resultType, project) {
3731
3723
  return new Promise((resolve, reject) => {
3732
3724
  const timeout = setTimeout(() => {
3733
- if (pending.delete(msg.id)) reject(new Error(\`\${msg.type} timed out\`));
3734
- }, REQUEST_TIMEOUT_MS12);
3735
- pending.set(msg.id, {
3725
+ if (pending2.delete(msg.id)) reject(new Error(\`\${msg.type} timed out\`));
3726
+ }, REQUEST_TIMEOUT_MS13);
3727
+ pending2.set(msg.id, {
3736
3728
  resolve,
3737
3729
  reject,
3738
3730
  timeout,
@@ -3756,9 +3748,9 @@ var NappletShimPrelude = (() => {
3756
3748
  return;
3757
3749
  }
3758
3750
  if (!("id" in msg) || typeof msg.id !== "string") return;
3759
- const entry = pending.get(msg.id);
3751
+ const entry = pending2.get(msg.id);
3760
3752
  if (!entry || msg.type !== entry.resultType) return;
3761
- pending.delete(msg.id);
3753
+ pending2.delete(msg.id);
3762
3754
  clearTimeout(entry.timeout);
3763
3755
  try {
3764
3756
  entry.resolve(entry.project(msg));
@@ -3805,21 +3797,21 @@ var NappletShimPrelude = (() => {
3805
3797
  };
3806
3798
  }
3807
3799
  function installWebrtcShim() {
3808
- if (installed14) return () => void 0;
3809
- installed14 = true;
3800
+ if (installed15) return () => void 0;
3801
+ installed15 = true;
3810
3802
  return () => {
3811
- for (const entry of pending.values()) clearTimeout(entry.timeout);
3812
- pending.clear();
3803
+ for (const entry of pending2.values()) clearTimeout(entry.timeout);
3804
+ pending2.clear();
3813
3805
  eventHandlers2.clear();
3814
- installed14 = false;
3806
+ installed15 = false;
3815
3807
  };
3816
3808
  }
3817
3809
 
3818
3810
  // ../nap/dist/chunk-23C42MT6.js
3819
- var REQUEST_TIMEOUT_MS13 = 3e4;
3820
- var pending2 = /* @__PURE__ */ new Map();
3811
+ var REQUEST_TIMEOUT_MS14 = 3e4;
3812
+ var pending3 = /* @__PURE__ */ new Map();
3821
3813
  var eventHandlers3 = /* @__PURE__ */ new Set();
3822
- var installed15 = false;
3814
+ var installed16 = false;
3823
3815
  var BLE_MESSAGE_TYPES = /* @__PURE__ */ new Set([
3824
3816
  "ble.open",
3825
3817
  "ble.open.result",
@@ -3843,9 +3835,9 @@ var NappletShimPrelude = (() => {
3843
3835
  function request3(msg, resultType, project) {
3844
3836
  return new Promise((resolve, reject) => {
3845
3837
  const timeout = setTimeout(() => {
3846
- if (pending2.delete(msg.id)) reject(new Error(\`\${msg.type} timed out\`));
3847
- }, REQUEST_TIMEOUT_MS13);
3848
- pending2.set(msg.id, {
3838
+ if (pending3.delete(msg.id)) reject(new Error(\`\${msg.type} timed out\`));
3839
+ }, REQUEST_TIMEOUT_MS14);
3840
+ pending3.set(msg.id, {
3849
3841
  resolve,
3850
3842
  reject,
3851
3843
  timeout,
@@ -3869,9 +3861,9 @@ var NappletShimPrelude = (() => {
3869
3861
  return;
3870
3862
  }
3871
3863
  if (!("id" in msg) || typeof msg.id !== "string") return;
3872
- const entry = pending2.get(msg.id);
3864
+ const entry = pending3.get(msg.id);
3873
3865
  if (!entry || msg.type !== entry.resultType) return;
3874
- pending2.delete(msg.id);
3866
+ pending3.delete(msg.id);
3875
3867
  clearTimeout(entry.timeout);
3876
3868
  try {
3877
3869
  entry.resolve(entry.project(msg));
@@ -3958,20 +3950,20 @@ var NappletShimPrelude = (() => {
3958
3950
  };
3959
3951
  }
3960
3952
  function installBleShim() {
3961
- if (installed15) return () => void 0;
3962
- installed15 = true;
3953
+ if (installed16) return () => void 0;
3954
+ installed16 = true;
3963
3955
  return () => {
3964
- for (const entry of pending2.values()) clearTimeout(entry.timeout);
3965
- pending2.clear();
3956
+ for (const entry of pending3.values()) clearTimeout(entry.timeout);
3957
+ pending3.clear();
3966
3958
  eventHandlers3.clear();
3967
- installed15 = false;
3959
+ installed16 = false;
3968
3960
  };
3969
3961
  }
3970
3962
 
3971
3963
  // ../nap/dist/chunk-A6WF7BXA.js
3972
- var REQUEST_TIMEOUT_MS14 = 3e4;
3964
+ var REQUEST_TIMEOUT_MS15 = 3e4;
3973
3965
  var pendingOpen2 = /* @__PURE__ */ new Map();
3974
- var installed16 = false;
3966
+ var installed17 = false;
3975
3967
  function isMessageType10(msg, type) {
3976
3968
  return msg.type === type;
3977
3969
  }
@@ -3996,7 +3988,7 @@ var NappletShimPrelude = (() => {
3996
3988
  return new Promise((resolve, reject) => {
3997
3989
  const timeout = setTimeout(() => {
3998
3990
  if (pendingOpen2.delete(id)) reject(new Error("link.open timed out"));
3999
- }, REQUEST_TIMEOUT_MS14);
3991
+ }, REQUEST_TIMEOUT_MS15);
4000
3992
  pendingOpen2.set(id, { resolve, reject, timeout });
4001
3993
  const msg = {
4002
3994
  type: "link.open",
@@ -4008,24 +4000,24 @@ var NappletShimPrelude = (() => {
4008
4000
  });
4009
4001
  }
4010
4002
  function installLinkShim() {
4011
- if (installed16) {
4003
+ if (installed17) {
4012
4004
  return () => void 0;
4013
4005
  }
4014
- installed16 = true;
4006
+ installed17 = true;
4015
4007
  return () => {
4016
4008
  for (const p of pendingOpen2.values()) {
4017
4009
  clearTimeout(p.timeout);
4018
4010
  p.reject(new Error("link shim uninstalled"));
4019
4011
  }
4020
4012
  pendingOpen2.clear();
4021
- installed16 = false;
4013
+ installed17 = false;
4022
4014
  };
4023
4015
  }
4024
4016
 
4025
4017
  // ../nap/dist/chunk-HNGITPFS.js
4026
- var REQUEST_TIMEOUT_MS15 = 3e4;
4018
+ var REQUEST_TIMEOUT_MS16 = 3e4;
4027
4019
  var pendingQuery2 = /* @__PURE__ */ new Map();
4028
- var installed17 = false;
4020
+ var installed18 = false;
4029
4021
  function isMessageType11(msg, type) {
4030
4022
  return msg.type === type;
4031
4023
  }
@@ -4033,11 +4025,11 @@ var NappletShimPrelude = (() => {
4033
4025
  return Array.isArray(filters) ? filters : [filters];
4034
4026
  }
4035
4027
  function handleQueryResult2(msg) {
4036
- const pending4 = pendingQuery2.get(msg.id);
4037
- if (!pending4) return;
4028
+ const pending5 = pendingQuery2.get(msg.id);
4029
+ if (!pending5) return;
4038
4030
  pendingQuery2.delete(msg.id);
4039
- clearTimeout(pending4.timeout);
4040
- pending4.resolve({
4031
+ clearTimeout(pending5.timeout);
4032
+ pending5.resolve({
4041
4033
  ok: msg.ok,
4042
4034
  ...msg.count === void 0 ? {} : { count: msg.count },
4043
4035
  ...msg.approximate === void 0 ? {} : { approximate: msg.approximate },
@@ -4061,7 +4053,7 @@ var NappletShimPrelude = (() => {
4061
4053
  return new Promise((resolve, reject) => {
4062
4054
  const timeout = setTimeout(() => {
4063
4055
  if (pendingQuery2.delete(id)) reject(new Error("count.query timed out"));
4064
- }, REQUEST_TIMEOUT_MS15);
4056
+ }, REQUEST_TIMEOUT_MS16);
4065
4057
  pendingQuery2.set(id, { resolve, reject, timeout });
4066
4058
  const msg = {
4067
4059
  type: "count.query",
@@ -4073,30 +4065,30 @@ var NappletShimPrelude = (() => {
4073
4065
  });
4074
4066
  }
4075
4067
  function installCountShim() {
4076
- if (installed17) {
4068
+ if (installed18) {
4077
4069
  return () => void 0;
4078
4070
  }
4079
- installed17 = true;
4071
+ installed18 = true;
4080
4072
  return () => {
4081
- for (const pending4 of pendingQuery2.values()) clearTimeout(pending4.timeout);
4073
+ for (const pending5 of pendingQuery2.values()) clearTimeout(pending5.timeout);
4082
4074
  pendingQuery2.clear();
4083
- installed17 = false;
4075
+ installed18 = false;
4084
4076
  };
4085
4077
  }
4086
4078
 
4087
4079
  // ../nap/dist/chunk-ESEMRW4T.js
4088
- var REQUEST_TIMEOUT_MS16 = 3e4;
4080
+ var REQUEST_TIMEOUT_MS17 = 3e4;
4089
4081
  var pendingSupported = /* @__PURE__ */ new Map();
4090
4082
  var pendingAdd = /* @__PURE__ */ new Map();
4091
4083
  var pendingRemove = /* @__PURE__ */ new Map();
4092
- var installed18 = false;
4084
+ var installed19 = false;
4093
4085
  function isMessageType12(msg, type) {
4094
4086
  return msg.type === type;
4095
4087
  }
4096
- function settle(pending4, id, resolveValue, fallbackError, error) {
4097
- const p = pending4.get(id);
4088
+ function settle2(pending5, id, resolveValue, fallbackError, error) {
4089
+ const p = pending5.get(id);
4098
4090
  if (!p) return;
4099
- pending4.delete(id);
4091
+ pending5.delete(id);
4100
4092
  clearTimeout(p.timeout);
4101
4093
  if (resolveValue !== void 0) {
4102
4094
  p.resolve(resolveValue);
@@ -4125,7 +4117,7 @@ var NappletShimPrelude = (() => {
4125
4117
  return result;
4126
4118
  }
4127
4119
  function handleSupportedResult(msg) {
4128
- settle(
4120
+ settle2(
4129
4121
  pendingSupported,
4130
4122
  msg.id,
4131
4123
  msg.lists,
@@ -4134,10 +4126,10 @@ var NappletShimPrelude = (() => {
4134
4126
  );
4135
4127
  }
4136
4128
  function handleAddResult(msg) {
4137
- settle(pendingAdd, msg.id, addResultFrom(msg), "lists.add failed");
4129
+ settle2(pendingAdd, msg.id, addResultFrom(msg), "lists.add failed");
4138
4130
  }
4139
4131
  function handleRemoveResult(msg) {
4140
- settle(pendingRemove, msg.id, removeResultFrom(msg), "lists.remove failed");
4132
+ settle2(pendingRemove, msg.id, removeResultFrom(msg), "lists.remove failed");
4141
4133
  }
4142
4134
  function handleListsMessage(msg) {
4143
4135
  if (isMessageType12(msg, "lists.supported.result")) {
@@ -4148,13 +4140,13 @@ var NappletShimPrelude = (() => {
4148
4140
  handleRemoveResult(msg);
4149
4141
  }
4150
4142
  }
4151
- function request4(type, pending4, payload) {
4143
+ function request4(type, pending5, payload) {
4152
4144
  const id = crypto.randomUUID();
4153
4145
  return new Promise((resolve, reject) => {
4154
4146
  const timeout = setTimeout(() => {
4155
- if (pending4.delete(id)) reject(new Error(\`\${type} timed out\`));
4156
- }, REQUEST_TIMEOUT_MS16);
4157
- pending4.set(id, { resolve, reject, timeout });
4147
+ if (pending5.delete(id)) reject(new Error(\`\${type} timed out\`));
4148
+ }, REQUEST_TIMEOUT_MS17);
4149
+ pending5.set(id, { resolve, reject, timeout });
4158
4150
  postToShell({
4159
4151
  type,
4160
4152
  id,
@@ -4180,10 +4172,10 @@ var NappletShimPrelude = (() => {
4180
4172
  });
4181
4173
  }
4182
4174
  function installListsShim() {
4183
- if (installed18) {
4175
+ if (installed19) {
4184
4176
  return () => void 0;
4185
4177
  }
4186
- installed18 = true;
4178
+ installed19 = true;
4187
4179
  return () => {
4188
4180
  for (const p of pendingSupported.values()) {
4189
4181
  clearTimeout(p.timeout);
@@ -4200,12 +4192,12 @@ var NappletShimPrelude = (() => {
4200
4192
  pendingSupported.clear();
4201
4193
  pendingAdd.clear();
4202
4194
  pendingRemove.clear();
4203
- installed18 = false;
4195
+ installed19 = false;
4204
4196
  };
4205
4197
  }
4206
4198
 
4207
4199
  // ../nap/dist/chunk-EALGKE7J.js
4208
- var REQUEST_TIMEOUT_MS17 = 3e4;
4200
+ var REQUEST_TIMEOUT_MS18 = 3e4;
4209
4201
  var pendingEncode = /* @__PURE__ */ new Map();
4210
4202
  var pendingDecode = /* @__PURE__ */ new Map();
4211
4203
  var pendingProfile = /* @__PURE__ */ new Map();
@@ -4214,7 +4206,7 @@ var NappletShimPrelude = (() => {
4214
4206
  var pendingUnfollow = /* @__PURE__ */ new Map();
4215
4207
  var pendingReact = /* @__PURE__ */ new Map();
4216
4208
  var pendingReport = /* @__PURE__ */ new Map();
4217
- var installed19 = false;
4209
+ var installed20 = false;
4218
4210
  function isMessageType13(msg, type) {
4219
4211
  return msg.type === type;
4220
4212
  }
@@ -4222,10 +4214,10 @@ var NappletShimPrelude = (() => {
4222
4214
  const { type: _type, id: _id, ...result } = msg;
4223
4215
  return result;
4224
4216
  }
4225
- function resolveResult(pending4, msg, fallback) {
4226
- const p = pending4.get(msg.id);
4217
+ function resolveResult(pending5, msg, fallback) {
4218
+ const p = pending5.get(msg.id);
4227
4219
  if (!p) return;
4228
- pending4.delete(msg.id);
4220
+ pending5.delete(msg.id);
4229
4221
  clearTimeout(p.timeout);
4230
4222
  if (typeof msg.ok === "boolean") {
4231
4223
  p.resolve(withoutEnvelope(msg));
@@ -4233,13 +4225,13 @@ var NappletShimPrelude = (() => {
4233
4225
  }
4234
4226
  p.reject(new Error(msg.error ?? fallback));
4235
4227
  }
4236
- function request5(pending4, timeoutMessage, message) {
4228
+ function request5(pending5, timeoutMessage, message) {
4237
4229
  const id = crypto.randomUUID();
4238
4230
  return new Promise((resolve, reject) => {
4239
4231
  const timeout = setTimeout(() => {
4240
- if (pending4.delete(id)) reject(new Error(timeoutMessage));
4241
- }, REQUEST_TIMEOUT_MS17);
4242
- pending4.set(id, { resolve, reject, timeout });
4232
+ if (pending5.delete(id)) reject(new Error(timeoutMessage));
4233
+ }, REQUEST_TIMEOUT_MS18);
4234
+ pending5.set(id, { resolve, reject, timeout });
4243
4235
  postToShell(message(id));
4244
4236
  });
4245
4237
  }
@@ -4322,12 +4314,12 @@ var NappletShimPrelude = (() => {
4322
4314
  }));
4323
4315
  }
4324
4316
  function installCommonShim() {
4325
- if (installed19) {
4317
+ if (installed20) {
4326
4318
  return () => void 0;
4327
4319
  }
4328
- installed19 = true;
4320
+ installed20 = true;
4329
4321
  return () => {
4330
- for (const pending4 of [
4322
+ for (const pending5 of [
4331
4323
  pendingEncode,
4332
4324
  pendingDecode,
4333
4325
  pendingProfile,
@@ -4337,55 +4329,55 @@ var NappletShimPrelude = (() => {
4337
4329
  pendingReact,
4338
4330
  pendingReport
4339
4331
  ]) {
4340
- for (const p of pending4.values()) clearTimeout(p.timeout);
4341
- pending4.clear();
4332
+ for (const p of pending5.values()) clearTimeout(p.timeout);
4333
+ pending5.clear();
4342
4334
  }
4343
- installed19 = false;
4335
+ installed20 = false;
4344
4336
  };
4345
4337
  }
4346
4338
 
4347
4339
  // ../nap/dist/chunk-6GWPHINR.js
4348
- var REQUEST_TIMEOUT_MS18 = 3e4;
4340
+ var REQUEST_TIMEOUT_MS19 = 3e4;
4349
4341
  var pendingOpen3 = /* @__PURE__ */ new Map();
4350
4342
  var pendingWrite = /* @__PURE__ */ new Map();
4351
4343
  var pendingClose2 = /* @__PURE__ */ new Map();
4352
4344
  var eventHandlers4 = /* @__PURE__ */ new Set();
4353
- var installed20 = false;
4345
+ var installed21 = false;
4354
4346
  function isMessageType14(msg, type) {
4355
4347
  return msg.type === type;
4356
4348
  }
4357
4349
  function handleOpenResult3(msg) {
4358
- const pending4 = pendingOpen3.get(msg.id);
4359
- if (!pending4) return;
4350
+ const pending5 = pendingOpen3.get(msg.id);
4351
+ if (!pending5) return;
4360
4352
  pendingOpen3.delete(msg.id);
4361
- clearTimeout(pending4.timeout);
4353
+ clearTimeout(pending5.timeout);
4362
4354
  if (msg.session !== void 0) {
4363
- pending4.resolve({ session: msg.session });
4355
+ pending5.resolve({ session: msg.session });
4364
4356
  return;
4365
4357
  }
4366
- pending4.reject(new Error(msg.error ?? "serial open failed"));
4358
+ pending5.reject(new Error(msg.error ?? "serial open failed"));
4367
4359
  }
4368
4360
  function handleWriteResult(msg) {
4369
- const pending4 = pendingWrite.get(msg.id);
4370
- if (!pending4) return;
4361
+ const pending5 = pendingWrite.get(msg.id);
4362
+ if (!pending5) return;
4371
4363
  pendingWrite.delete(msg.id);
4372
- clearTimeout(pending4.timeout);
4364
+ clearTimeout(pending5.timeout);
4373
4365
  if (msg.error) {
4374
- pending4.reject(new Error(msg.error));
4366
+ pending5.reject(new Error(msg.error));
4375
4367
  return;
4376
4368
  }
4377
- pending4.resolve();
4369
+ pending5.resolve();
4378
4370
  }
4379
4371
  function handleCloseResult2(msg) {
4380
- const pending4 = pendingClose2.get(msg.id);
4381
- if (!pending4) return;
4372
+ const pending5 = pendingClose2.get(msg.id);
4373
+ if (!pending5) return;
4382
4374
  pendingClose2.delete(msg.id);
4383
- clearTimeout(pending4.timeout);
4375
+ clearTimeout(pending5.timeout);
4384
4376
  if (msg.error) {
4385
- pending4.reject(new Error(msg.error));
4377
+ pending5.reject(new Error(msg.error));
4386
4378
  return;
4387
4379
  }
4388
- pending4.resolve();
4380
+ pending5.resolve();
4389
4381
  }
4390
4382
  function handleEvent4(msg) {
4391
4383
  if (!msg.event) return;
@@ -4407,7 +4399,7 @@ var NappletShimPrelude = (() => {
4407
4399
  return new Promise((resolve, reject) => {
4408
4400
  const timeout = setTimeout(() => {
4409
4401
  if (pendingOpen3.delete(id)) reject(new Error("serial.open timed out"));
4410
- }, REQUEST_TIMEOUT_MS18);
4402
+ }, REQUEST_TIMEOUT_MS19);
4411
4403
  pendingOpen3.set(id, { resolve, reject, timeout });
4412
4404
  const msg = {
4413
4405
  type: "serial.open",
@@ -4422,7 +4414,7 @@ var NappletShimPrelude = (() => {
4422
4414
  return new Promise((resolve, reject) => {
4423
4415
  const timeout = setTimeout(() => {
4424
4416
  if (pendingWrite.delete(id)) reject(new Error("serial.write timed out"));
4425
- }, REQUEST_TIMEOUT_MS18);
4417
+ }, REQUEST_TIMEOUT_MS19);
4426
4418
  pendingWrite.set(id, { resolve, reject, timeout });
4427
4419
  const msg = {
4428
4420
  type: "serial.write",
@@ -4438,7 +4430,7 @@ var NappletShimPrelude = (() => {
4438
4430
  return new Promise((resolve, reject) => {
4439
4431
  const timeout = setTimeout(() => {
4440
4432
  if (pendingClose2.delete(id)) reject(new Error("serial.close timed out"));
4441
- }, REQUEST_TIMEOUT_MS18);
4433
+ }, REQUEST_TIMEOUT_MS19);
4442
4434
  pendingClose2.set(id, { resolve, reject, timeout });
4443
4435
  const msg = {
4444
4436
  type: "serial.close",
@@ -4458,27 +4450,27 @@ var NappletShimPrelude = (() => {
4458
4450
  };
4459
4451
  }
4460
4452
  function installSerialShim() {
4461
- if (installed20) {
4453
+ if (installed21) {
4462
4454
  return () => void 0;
4463
4455
  }
4464
- installed20 = true;
4456
+ installed21 = true;
4465
4457
  return () => {
4466
- for (const pending4 of pendingOpen3.values()) clearTimeout(pending4.timeout);
4467
- for (const pending4 of pendingWrite.values()) clearTimeout(pending4.timeout);
4468
- for (const pending4 of pendingClose2.values()) clearTimeout(pending4.timeout);
4458
+ for (const pending5 of pendingOpen3.values()) clearTimeout(pending5.timeout);
4459
+ for (const pending5 of pendingWrite.values()) clearTimeout(pending5.timeout);
4460
+ for (const pending5 of pendingClose2.values()) clearTimeout(pending5.timeout);
4469
4461
  pendingOpen3.clear();
4470
4462
  pendingWrite.clear();
4471
4463
  pendingClose2.clear();
4472
4464
  eventHandlers4.clear();
4473
- installed20 = false;
4465
+ installed21 = false;
4474
4466
  };
4475
4467
  }
4476
4468
 
4477
4469
  // ../nap/dist/chunk-PONXETIR.js
4478
- var REQUEST_TIMEOUT_MS19 = 3e4;
4479
- var pending3 = /* @__PURE__ */ new Map();
4470
+ var REQUEST_TIMEOUT_MS20 = 3e4;
4471
+ var pending4 = /* @__PURE__ */ new Map();
4480
4472
  var changeHandlers3 = /* @__PURE__ */ new Set();
4481
- var installed21 = false;
4473
+ var installed22 = false;
4482
4474
  var RESULT_TYPES = /* @__PURE__ */ new Set([
4483
4475
  "fs.info.result",
4484
4476
  "fs.pickFile.result",
@@ -4499,9 +4491,9 @@ var NappletShimPrelude = (() => {
4499
4491
  const id = crypto.randomUUID();
4500
4492
  return new Promise((resolve, reject) => {
4501
4493
  const timeout = setTimeout(() => {
4502
- if (pending3.delete(id)) reject(new Error(\`\${type} timed out\`));
4503
- }, REQUEST_TIMEOUT_MS19);
4504
- pending3.set(id, { resolve, reject, timeout });
4494
+ if (pending4.delete(id)) reject(new Error(\`\${type} timed out\`));
4495
+ }, REQUEST_TIMEOUT_MS20);
4496
+ pending4.set(id, { resolve, reject, timeout });
4505
4497
  postToShell({ type, id, ...payload });
4506
4498
  });
4507
4499
  }
@@ -4515,9 +4507,9 @@ var NappletShimPrelude = (() => {
4515
4507
  function handleResult(msg) {
4516
4508
  const id = msg.id;
4517
4509
  if (typeof id !== "string") return;
4518
- const entry = pending3.get(id);
4510
+ const entry = pending4.get(id);
4519
4511
  if (!entry) return;
4520
- pending3.delete(id);
4512
+ pending4.delete(id);
4521
4513
  clearTimeout(entry.timeout);
4522
4514
  if (typeof msg.error === "string") {
4523
4515
  entry.reject(new Error(msg.error));
@@ -4602,20 +4594,20 @@ var NappletShimPrelude = (() => {
4602
4594
  };
4603
4595
  }
4604
4596
  function installFsShim() {
4605
- if (installed21) {
4597
+ if (installed22) {
4606
4598
  return () => void 0;
4607
4599
  }
4608
- installed21 = true;
4600
+ installed22 = true;
4609
4601
  return () => {
4610
- for (const entry of pending3.values()) clearTimeout(entry.timeout);
4611
- pending3.clear();
4602
+ for (const entry of pending4.values()) clearTimeout(entry.timeout);
4603
+ pending4.clear();
4612
4604
  changeHandlers3.clear();
4613
- installed21 = false;
4605
+ installed22 = false;
4614
4606
  };
4615
4607
  }
4616
4608
 
4617
4609
  // ../nap/dist/chunk-DNUVIJ5U.js
4618
- var REQUEST_TIMEOUT_MS20 = 3e4;
4610
+ var REQUEST_TIMEOUT_MS21 = 3e4;
4619
4611
  var pendingStatus2 = /* @__PURE__ */ new Map();
4620
4612
  var pendingConversations = /* @__PURE__ */ new Map();
4621
4613
  var pendingMessages = /* @__PURE__ */ new Map();
@@ -4623,7 +4615,7 @@ var NappletShimPrelude = (() => {
4623
4615
  var pendingSubscribe = /* @__PURE__ */ new Map();
4624
4616
  var pendingUnsubscribe = /* @__PURE__ */ new Map();
4625
4617
  var messageHandlers = /* @__PURE__ */ new Set();
4626
- var installed22 = false;
4618
+ var installed23 = false;
4627
4619
  function isMessageType15(msg, type) {
4628
4620
  return msg.type === type;
4629
4621
  }
@@ -4631,28 +4623,28 @@ var NappletShimPrelude = (() => {
4631
4623
  return new Promise((resolve, reject) => {
4632
4624
  const timeout = setTimeout(() => {
4633
4625
  if (map.delete(id)) reject(new Error(\`\${action} timed out\`));
4634
- }, REQUEST_TIMEOUT_MS20);
4626
+ }, REQUEST_TIMEOUT_MS21);
4635
4627
  map.set(id, { resolve, reject, timeout });
4636
4628
  });
4637
4629
  }
4638
- function settle2(map, id, error, fallbackError, getValue) {
4639
- const pending4 = map.get(id);
4640
- if (!pending4) return;
4630
+ function settle3(map, id, error, fallbackError, getValue) {
4631
+ const pending5 = map.get(id);
4632
+ if (!pending5) return;
4641
4633
  map.delete(id);
4642
- clearTimeout(pending4.timeout);
4634
+ clearTimeout(pending5.timeout);
4643
4635
  if (error) {
4644
- pending4.reject(new Error(error));
4636
+ pending5.reject(new Error(error));
4645
4637
  return;
4646
4638
  }
4647
4639
  const value = getValue();
4648
4640
  if (value === void 0) {
4649
- pending4.reject(new Error(fallbackError));
4641
+ pending5.reject(new Error(fallbackError));
4650
4642
  return;
4651
4643
  }
4652
- pending4.resolve(value);
4644
+ pending5.resolve(value);
4653
4645
  }
4654
4646
  function handleStatusResult2(msg) {
4655
- settle2(
4647
+ settle3(
4656
4648
  pendingStatus2,
4657
4649
  msg.id,
4658
4650
  msg.error,
@@ -4671,7 +4663,7 @@ var NappletShimPrelude = (() => {
4671
4663
  );
4672
4664
  }
4673
4665
  function handleConversationsResult(msg) {
4674
- settle2(
4666
+ settle3(
4675
4667
  pendingConversations,
4676
4668
  msg.id,
4677
4669
  msg.error,
@@ -4686,7 +4678,7 @@ var NappletShimPrelude = (() => {
4686
4678
  );
4687
4679
  }
4688
4680
  function handleMessagesResult(msg) {
4689
- settle2(
4681
+ settle3(
4690
4682
  pendingMessages,
4691
4683
  msg.id,
4692
4684
  msg.error,
@@ -4701,7 +4693,7 @@ var NappletShimPrelude = (() => {
4701
4693
  );
4702
4694
  }
4703
4695
  function handleSendResult2(msg) {
4704
- settle2(
4696
+ settle3(
4705
4697
  pendingSend,
4706
4698
  msg.id,
4707
4699
  msg.error,
@@ -4713,7 +4705,7 @@ var NappletShimPrelude = (() => {
4713
4705
  );
4714
4706
  }
4715
4707
  function handleSubscribeResult(msg) {
4716
- settle2(
4708
+ settle3(
4717
4709
  pendingSubscribe,
4718
4710
  msg.id,
4719
4711
  msg.error,
@@ -4725,7 +4717,7 @@ var NappletShimPrelude = (() => {
4725
4717
  );
4726
4718
  }
4727
4719
  function handleUnsubscribeResult(msg) {
4728
- settle2(
4720
+ settle3(
4729
4721
  pendingUnsubscribe,
4730
4722
  msg.id,
4731
4723
  msg.error,
@@ -4828,17 +4820,17 @@ var NappletShimPrelude = (() => {
4828
4820
  };
4829
4821
  }
4830
4822
  function installDmShim() {
4831
- if (installed22) {
4823
+ if (installed23) {
4832
4824
  return () => void 0;
4833
4825
  }
4834
- installed22 = true;
4826
+ installed23 = true;
4835
4827
  return () => {
4836
- for (const pending4 of pendingStatus2.values()) clearTimeout(pending4.timeout);
4837
- for (const pending4 of pendingConversations.values()) clearTimeout(pending4.timeout);
4838
- for (const pending4 of pendingMessages.values()) clearTimeout(pending4.timeout);
4839
- for (const pending4 of pendingSend.values()) clearTimeout(pending4.timeout);
4840
- for (const pending4 of pendingSubscribe.values()) clearTimeout(pending4.timeout);
4841
- for (const pending4 of pendingUnsubscribe.values()) clearTimeout(pending4.timeout);
4828
+ for (const pending5 of pendingStatus2.values()) clearTimeout(pending5.timeout);
4829
+ for (const pending5 of pendingConversations.values()) clearTimeout(pending5.timeout);
4830
+ for (const pending5 of pendingMessages.values()) clearTimeout(pending5.timeout);
4831
+ for (const pending5 of pendingSend.values()) clearTimeout(pending5.timeout);
4832
+ for (const pending5 of pendingSubscribe.values()) clearTimeout(pending5.timeout);
4833
+ for (const pending5 of pendingUnsubscribe.values()) clearTimeout(pending5.timeout);
4842
4834
  pendingStatus2.clear();
4843
4835
  pendingConversations.clear();
4844
4836
  pendingMessages.clear();
@@ -4846,7 +4838,7 @@ var NappletShimPrelude = (() => {
4846
4838
  pendingSubscribe.clear();
4847
4839
  pendingUnsubscribe.clear();
4848
4840
  messageHandlers.clear();
4849
- installed22 = false;
4841
+ installed23 = false;
4850
4842
  };
4851
4843
  }
4852
4844
 
@@ -5087,6 +5079,14 @@ var NappletShimPrelude = (() => {
5087
5079
 
5088
5080
  // src/runtime-globals-services.ts
5089
5081
  function installServiceDomains(domains, napplet) {
5082
+ if (domains.has("llm")) {
5083
+ napplet.llm = {
5084
+ select,
5085
+ describe,
5086
+ generate,
5087
+ cancel
5088
+ };
5089
+ }
5090
5090
  installNetworkDomains(domains, napplet);
5091
5091
  installDeviceDomains(domains, napplet);
5092
5092
  installFilesystemDomains(domains, napplet);
@@ -5251,6 +5251,7 @@ var NappletShimPrelude = (() => {
5251
5251
  var installedDomainShims = /* @__PURE__ */ new Set();
5252
5252
  var messageListenerInstalled = false;
5253
5253
  var DOMAIN_ROUTERS = [
5254
+ ["llm.", handleLlmMessage],
5254
5255
  ["gamepad.", handleGamepadMessage],
5255
5256
  ["shell.", handleShellMessage],
5256
5257
  ["keys.", handleKeysMessage],
@@ -5297,6 +5298,9 @@ var NappletShimPrelude = (() => {
5297
5298
  if (installedDomainShims.has(domain)) return;
5298
5299
  installedDomainShims.add(domain);
5299
5300
  switch (domain) {
5301
+ case "llm":
5302
+ installLlmShim();
5303
+ return;
5300
5304
  case "gamepad":
5301
5305
  installGamepadShim();
5302
5306
  return;
@@ -5417,9 +5421,9 @@ var NappletShimPrelude = (() => {
5417
5421
  @scure/base/index.js:
5418
5422
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
5419
5423
  */
5420
- //# sourceMappingURL=prelude.global.js.map`,Kr=/\bwindow\s*\.\s*nostr\b|\bglobalThis\s*\.\s*nostr\b/,Zr="/__conformance__/events",an=new URLSearchParams(location.search),_t=an.get("live")==="1";function te(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const se=document.getElementById("app");function Yr(){return se.innerHTML=`
5424
+ //# sourceMappingURL=prelude.global.js.map`,ki=/\bwindow\s*\.\s*nostr\b|\bglobalThis\s*\.\s*nostr\b/,xi="/__conformance__/events",pn=new URLSearchParams(location.search),Ct=pn.get("live")==="1";function te(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const se=document.getElementById("app");function Mi(){return se.innerHTML=`
5421
5425
  <header class="masthead">
5422
- <h1>napplet conformance ${_t?'<span class="live-badge" id="live-badge">● live</span>':""}</h1>
5426
+ <h1>napplet conformance ${Ct?'<span class="live-badge" id="live-badge">● live</span>':""}</h1>
5423
5427
  <p>Load a napplet by <code>nevent</code> or <code>naddr</code> and run NAP protocol conformance live. Same engine as <code>napplet-conformance</code> CI.</p>
5424
5428
  </header>
5425
5429
  <form id="run-form" class="runbar">
@@ -5429,22 +5433,22 @@ var NappletShimPrelude = (() => {
5429
5433
  </form>
5430
5434
  <p id="status" class="status" role="status"></p>
5431
5435
  <section id="output" class="output"></section>
5432
- `,{targetInput:se.querySelector("#target"),runButton:se.querySelector("#run"),rerunButton:se.querySelector("#rerun"),liveBadge:se.querySelector("#live-badge")??document.createElement("span"),status:se.querySelector("#status"),output:se.querySelector("#output")}}const H=Yr();let ve="",ln=0;function ke(e,n="info"){H.status.textContent=e,H.status.dataset.kind=n}function Ye(e){return String(e).padStart(2,"0")}function Xr(e){const n=new Date(e);return`${Ye(n.getHours())}:${Ye(n.getMinutes())}:${Ye(n.getSeconds())}`}function Jr(e){const n=e.ok?"conformant":"non-conformant",t=[...new Set(e.checks.map(o=>o.area))].map(o=>{const l=e.checks.filter(a=>a.area===o).map(a=>{const d=a.severity==="warning"&&a.status==="fail"?' <span class="tag warn">warning</span>':"",h=a.detail?`<span class="detail">${te(a.detail)}</span>`:"";return`<li class="check ${a.status}"><span class="badge ${a.status}">${a.status}</span><span class="id">${te(a.id)}</span>${d}${h}</li>`}).join("");return`<div class="area"><h3>${te(o)}</h3><ul>${l}</ul></div>`}).join(""),r=e.summary,i=ln>1?`<span class="run-stamp">run #${ln} · ${Xr(e.finishedAt)}</span>`:"";return`
5436
+ `,{targetInput:se.querySelector("#target"),runButton:se.querySelector("#run"),rerunButton:se.querySelector("#rerun"),liveBadge:se.querySelector("#live-badge")??document.createElement("span"),status:se.querySelector("#status"),output:se.querySelector("#output")}}const H=Mi();let Te="",mn=0;function Pe(e,n="info"){H.status.textContent=e,H.status.dataset.kind=n}function sn(e){return String(e).padStart(2,"0")}function Ui(e){const n=new Date(e);return`${sn(n.getHours())}:${sn(n.getMinutes())}:${sn(n.getSeconds())}`}function Pi(e){const n=e.ok?"conformant":"non-conformant",t=[...new Set(e.checks.map(o=>o.area))].map(o=>{const l=e.checks.filter(a=>a.area===o).map(a=>{const d=a.severity==="warning"&&a.status==="fail"?' <span class="tag warn">warning</span>':"",h=a.detail?`<span class="detail">${te(a.detail)}</span>`:"";return`<li class="check ${a.status}"><span class="badge ${a.status}">${a.status}</span><span class="id">${te(a.id)}</span>${d}${h}</li>`}).join("");return`<div class="area"><h3>${te(o)}</h3><ul>${l}</ul></div>`}).join(""),r=e.summary,i=mn>1?`<span class="run-stamp">run #${mn} · ${Ui(e.finishedAt)}</span>`:"";return`
5433
5437
  <div class="verdict ${n}">
5434
5438
  <span class="result">${e.ok?"CONFORMANT":"NON-CONFORMANT"}</span>
5435
5439
  <span class="counts">${r.passed} passed · ${r.failed} failed · ${r.skipped} skipped${r.warnings?` · ${r.warnings} warning(s)`:""}</span>
5436
5440
  ${i}
5437
5441
  </div>
5438
5442
  <div class="checks">${t}</div>
5439
- `}function ei(e){return e.length===0?'<p class="empty">No envelopes were emitted.</p>':`<ul class="envlog">${e.map(s=>{const t=s.verdict.ok?"ok":"bad",r=s.verdict.ok?"":`<div class="errs">${s.verdict.errors.map(i=>te(`${i.code}: ${i.message}`)).join("<br>")}</div>`;return`<li class="env ${t}"><code>${te(JSON.stringify(s.envelope))}</code>${r}</li>`}).join("")}</ul>`}function ni(e){const n=(s,t)=>`<tr><th>${te(s)}</th><td>${t?te(String(t)):"<em>—</em>"}</td></tr>`;if(e.manifestEvent){const s=e.manifestEvent,t=Be(s);return`
5443
+ `}function Ai(e){return e.length===0?'<p class="empty">No envelopes were emitted.</p>':`<ul class="envlog">${e.map(s=>{const t=s.verdict.ok?"ok":"bad",r=s.verdict.ok?"":`<div class="errs">${s.verdict.errors.map(i=>te(`${i.code}: ${i.message}`)).join("<br>")}</div>`;return`<li class="env ${t}"><code>${te(JSON.stringify(s.envelope))}</code>${r}</li>`}).join("")}</ul>`}function ji(e){const n=(s,t)=>`<tr><th>${te(s)}</th><td>${t?te(String(t)):"<em>—</em>"}</td></tr>`;if(e.manifestEvent){const s=e.manifestEvent,t=We(s);return`
5440
5444
  <table class="manifest">
5441
- ${gs(s,t).map(([r,i])=>n(r,i)).join("")}
5445
+ ${zs(s,t).map(([r,i])=>n(r,i)).join("")}
5442
5446
  </table>
5443
5447
  ${t.errors.length?`<div class="errs">${t.errors.map(r=>te(`${r.code}: ${r.message}`)).join("<br>")}</div>`:""}
5444
- `}return e.fetched?'<p class="empty">Local URL mode booted raw HTML. It does not include a signed NIP-5D manifest event, so manifest-event checks are skipped.</p>':`<p class="empty">Couldn't fetch the local URL HTML, likely because of CORS. Use a NIP-19 <code>nevent</code>/<code>naddr</code> for authoritative manifest checks, or use the CLI for local URL runs.</p>`}function ti(e,n,s){H.output.innerHTML=`
5445
- ${Jr(e)}
5448
+ `}return e.fetched?'<p class="empty">Local URL mode booted raw HTML. It does not include a signed NIP-5D manifest event, so manifest-event checks are skipped.</p>':`<p class="empty">Couldn't fetch the local URL HTML, likely because of CORS. Use a NIP-19 <code>nevent</code>/<code>naddr</code> for authoritative manifest checks, or use the CLI for local URL runs.</p>`}function qi(e,n,s){H.output.innerHTML=`
5449
+ ${Pi(e)}
5446
5450
  <div class="panels">
5447
- <section class="panel"><h2>Emitted envelopes (${n.length})</h2>${ei(n)}</section>
5448
- <section class="panel"><h2>Manifest</h2>${ni(s)}</section>
5451
+ <section class="panel"><h2>Emitted envelopes (${n.length})</h2>${Ai(n)}</section>
5452
+ <section class="panel"><h2>Manifest</h2>${ji(s)}</section>
5449
5453
  </div>
5450
- `}async function Fe(e){ve=e,H.runButton.disabled=!0,H.rerunButton.disabled=!0;let n=null;try{ke(`Resolving ${e} …`),n=await Qr(e);const s=Kr.test(n.html)?["window.nostr"]:[];ke("Booting napplet in a sandboxed iframe …");const t=await ls({url:n.bootUrl,html:n.html,readyTimeoutMs:5e3,settleMs:800,runDegraded:!0,runtimePreludeSource:zr}),r=es({manifestHtml:n.html,manifestEvent:n.manifestEvent,boot:t,forbiddenGlobals:s}),i=ms(r);ln+=1,ke(i.ok?"Done — conformant.":"Done — non-conformant.",i.ok?"info":"error"),ti(i,t.emitted,n),H.rerunButton.hidden=!1}catch(s){ke(`Error: ${s instanceof Error?s.message:String(s)}`,"error")}finally{n?.revoke?.(),H.runButton.disabled=!1,H.rerunButton.disabled=!1}}function si(){if(!_t||typeof EventSource>"u")return;let e=!1;const n=new EventSource(Zr);n.addEventListener("rerun",()=>{!ve||e||(e=!0,setTimeout(()=>{e=!1,Fe(ve)},50))}),n.addEventListener("open",()=>{H.liveBadge&&(H.liveBadge.dataset.state="connected")}),n.addEventListener("error",()=>{H.liveBadge&&(H.liveBadge.dataset.state="disconnected")})}H.runButton.parentElement.addEventListener("submit",e=>{e.preventDefault();const n=H.targetInput.value.trim();if(n){const s=new URL(location.href);s.searchParams.set("target",n),s.searchParams.delete("url"),history.replaceState(null,"",s),Fe(n)}});H.rerunButton.addEventListener("click",()=>{ve&&Fe(ve)});si();const Xe=an.get("target")??an.get("url");Xe&&(H.targetInput.value=Xe,Fe(Xe));
5454
+ `}async function Ke(e){Te=e,H.runButton.disabled=!0,H.rerunButton.disabled=!0;let n=null;try{Pe(`Resolving ${e} …`),n=await Ri(e);const s=ki.test(n.html)?["window.nostr"]:[];Pe("Booting napplet in a sandboxed iframe …");const t=await Ns({url:n.bootUrl,html:n.html,readyTimeoutMs:5e3,settleMs:800,runDegraded:!0,runtimePreludeSource:Ii}),r=js({manifestHtml:n.html,manifestEvent:n.manifestEvent,boot:t,forbiddenGlobals:s}),i=Vs(r);mn+=1,Pe(i.ok?"Done — conformant.":"Done — non-conformant.",i.ok?"info":"error"),qi(i,t.emitted,n),H.rerunButton.hidden=!1}catch(s){Pe(`Error: ${s instanceof Error?s.message:String(s)}`,"error")}finally{n?.revoke?.(),H.runButton.disabled=!1,H.rerunButton.disabled=!1}}function Oi(){if(!Ct||typeof EventSource>"u")return;let e=!1;const n=new EventSource(xi);n.addEventListener("rerun",()=>{!Te||e||(e=!0,setTimeout(()=>{e=!1,Ke(Te)},50))}),n.addEventListener("open",()=>{H.liveBadge&&(H.liveBadge.dataset.state="connected")}),n.addEventListener("error",()=>{H.liveBadge&&(H.liveBadge.dataset.state="disconnected")})}H.runButton.parentElement.addEventListener("submit",e=>{e.preventDefault();const n=H.targetInput.value.trim();if(n){const s=new URL(location.href);s.searchParams.set("target",n),s.searchParams.delete("url"),history.replaceState(null,"",s),Ke(n)}});H.rerunButton.addEventListener("click",()=>{Te&&Ke(Te)});Oi();const rn=pn.get("target")??pn.get("url");rn&&(H.targetInput.value=rn,Ke(rn));