@napplet/conformance-cli 0.4.2 → 0.4.3

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,13 +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 $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`(() => {
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"],Oe={shell:{proposal:{url:"https://github.com/napplet/naps/pull/101",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Optional readiness and environment binding has focused shim and reference-runtime coverage.",evidence:["packages/nap/src/shell/shim.test.ts"]},relay:{proposal:{url:"https://github.com/napplet/naps/pull/2",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Relay reads, publishing, and subscription lifecycle have maintained shim and integration tests; upstream naming remains under review.",evidence:["packages/nap/src/relay/shim.test.ts"],implementationReference:{revision:"cb8f8eabb2d09439e9d174cb9eb6ef2caad0eca1",evidence:".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md",scope:"RelayEventResult sidecar migration; subsequent changes are not covered."}},identity:{proposal:{url:"https://github.com/napplet/naps/pull/102",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Read-only identity queries and updates have focused binding and reference-runtime coverage.",evidence:["packages/nap/src/identity/shim.test.ts"]},storage:{proposal:{url:"https://github.com/napplet/naps/pull/3",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Key-value binding has focused request/result tests and tutorial usage; host storage isolation remains the host responsibility.",evidence:["packages/nap/src/storage/shim.test.ts"]},inc:{proposal:{url:"https://github.com/napplet/naps/pull/104",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Topic and channel bindings have compatibility tests and authenticated-endpoint reference-runtime coverage.",evidence:["packages/nap/src/inc/shim.ts","packages/conformance-cli/src/browser.test.ts"]},theme:{proposal:{url:"https://github.com/napplet/naps/pull/103",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Theme queries and pushed updates have focused binding and opaque-iframe integration coverage.",evidence:["packages/nap/src/theme/shim.test.ts","packages/conformance-cli/src/browser.test.ts"]},keys:{proposal:{url:"https://github.com/napplet/naps/pull/9",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Keyboard binding ships, but dedicated domain regression coverage is limited; retain explicit evaluation opt-in.",evidence:["packages/nap/src/keys/shim.ts"]},media:{proposal:{url:"https://github.com/napplet/naps/pull/10",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Session creation and playback binding have focused regression coverage; proposed torrent playback amendments are not implied.",evidence:["packages/nap/src/media/shim.test.ts"]},notify:{proposal:{url:"https://github.com/napplet/naps/pull/11",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Notification binding ships with limited dedicated domain regression evidence; broader host integration confidence is unverified.",evidence:["packages/nap/src/notify/shim.ts"]},config:{proposal:{url:"https://github.com/napplet/naps/pull/14",status:"draft",checkedAt:"2026-10-31"},maturity:"exploratory",rationale:"Configuration binding is tested, but the upstream draft is marked MAY DEFER; use for design exploration.",evidence:["packages/nap/src/config/shim.test.ts"]},resource:{proposal:{url:"https://github.com/napplet/naps/pull/80",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Resource fetching has focused shim and type tests; the reverted merge and reopened proposal do not change that implementation assessment.",evidence:["packages/nap/src/resource/shim.test.ts"],implementationReference:{revision:"8e75eadf317d7fe809415e4755cd48f63cfb63f3",evidence:".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md",scope:"Shared ResourceSidecarEntry types during the sidecar migration; subsequent resource changes are not covered."}},cvm:{proposal:{url:"https://github.com/napplet/naps/pull/31",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Session and registry bindings are tested; upstream explicitly marks the contract NEEDS WORK.",evidence:["packages/nap/src/cvm/shim.test.ts"]},outbox:{proposal:{url:"https://github.com/napplet/naps/pull/32",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Routing and subscription bindings have focused tests and an integration regression for structured-clone boundaries.",evidence:["packages/nap/src/outbox/shim.test.ts","packages/nap/src/boundary-integration.test.ts"],implementationReference:{revision:"57db924bac022cc14c67d9fca1a4d92cf1bd4725",evidence:".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md",scope:"RelayEventResult and stream lifecycle migration; subsequent changes are not covered."}},upload:{proposal:{url:"https://github.com/napplet/naps/pull/33",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Upload binding has focused tests for request/result behavior; host rail support remains runtime-specific.",evidence:["packages/nap/src/upload/shim.test.ts"]},intent:{proposal:{url:"https://github.com/napplet/naps/pull/91",status:"merged",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Convention normalization and dispatch have focused binding and reference-runtime integration tests.",evidence:["packages/nap/src/intent/shim.test.ts"]},ble:{proposal:{url:"https://github.com/napplet/naps/pull/62",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"GATT binding has unit coverage; real-device behavior across host backends is not established by these tests.",evidence:["packages/nap/src/ble/shim.test.ts"]},webrtc:{proposal:{url:"https://github.com/napplet/naps/pull/59",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Signaling and session binding have unit coverage; interoperable live peer sessions remain unverified here.",evidence:["packages/nap/src/webrtc/shim.test.ts"]},link:{proposal:{url:"https://github.com/napplet/naps/pull/53",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"The small link-opening binding has focused regression coverage; navigation authorization stays with the host.",evidence:["packages/nap/src/link/shim.test.ts"]},count:{proposal:{url:"https://github.com/napplet/naps/pull/69",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Count binding is tested, but accuracy and aggregation across real relay backends remain outside that evidence.",evidence:["packages/nap/src/count/shim.test.ts"]},lists:{proposal:{url:"https://github.com/napplet/naps/pull/68",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"List mutation binding is tested; concurrent real-host mutation behavior is not established by binding tests.",evidence:["packages/nap/src/lists/shim.test.ts"]},serial:{proposal:{url:"https://github.com/napplet/naps/pull/61",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Serial binding has unit coverage; device and native-host integration evidence is limited.",evidence:["packages/nap/src/serial/shim.test.ts"]},fs:{proposal:{url:"https://github.com/napplet/naps/pull/88",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Filesystem binding has MVP coverage; portability and authorization across storage backends remain under evaluation.",evidence:["packages/nap/src/fs/shim.test.ts"]},common:{proposal:{url:"https://github.com/napplet/naps/pull/67",status:"in-review",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Social action binding is tested; broader host integration and evolving action semantics warrant explicit opt-in.",evidence:["packages/nap/src/common/shim.test.ts"]},dm:{proposal:{url:"https://github.com/napplet/naps/pull/74",status:"draft",checkedAt:"2026-10-31"},maturity:"experimental",rationale:"Direct-message binding has shim and type coverage; transport interoperability is not established by those tests.",evidence:["packages/nap/src/dm/shim.test.ts"]},gamepad:{proposal:{url:"https://github.com/napplet/naps/pull/130",status:"in-review",checkedAt:"2026-10-31"},maturity:"supported",rationale:"Cross-repository delivery includes binding, security, runtime, and conformance verification; the reopened proposal is still subject to change.",evidence:["packages/nap/src/gamepad/shim.test.ts",".planning/phases/163-nap-gamepad-across-repositories/163-VERIFICATION.md"],implementationReference:{revision:"0b28f77e3dfa0f07dd7c0f9d61a7090ee99f3a5e",evidence:".planning/phases/163-nap-gamepad-across-repositories/163-SECURITY.md",scope:"Phase 163 binding, runtime isolation, and conformance verification."}},llm:{proposal:{url:"https://github.com/napplet/naps/pull/134",status:"draft",checkedAt:"2026-10-31"},maturity:"exploratory",rationale:"Early published draft has binding and mock-runtime tests; provider behavior and API design remain exploratory.",evidence:["packages/nap/src/llm/shim.test.ts","packages/conformance-cli/src/browser.test.ts"]}};for(const e of Object.values(Oe))Object.freeze(e.proposal),Object.freeze(e.evidence),e.implementationReference&&Object.freeze(e.implementationReference),Object.freeze(e);Object.freeze(Oe);function Dt(e){return Object.hasOwn(Oe,e)?Oe[e]:void 0}function Bt(e){const n=new Set(e.allowedMaturities??["supported"]),s=new Set(e.optIn??[]),t=[],r=[];for(const i of new Set(e.candidates)){const o=Dt(i);o?!o.maturity||!["supported","experimental","exploratory"].includes(o.maturity)?r.push({domain:i,reason:"unclassified"}):n.has(o.maturity)||s.has(i)?t.push(i):r.push({domain:i,reason:"maturity-not-allowed",maturity:o.maturity}):r.push({domain:i,reason:"unknown-domain"})}return{domains:t,excluded:r}}var u={id:"string"},Lt={"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"}},$t=e=>typeof e=="string",we=e=>typeof e=="string"&&e.length>0,kn=e=>typeof e=="boolean",Ee=(...e)=>n=>typeof n=="string"&&e.includes(n),Ft=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 Te(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 Kn=e=>n=>Array.isArray(n)&&n.length>0&&n.every(e),Wt=Te({type:Ee("text"),text:$t}),zt=Te({type:Ee("image"),mimeType:Ee("image/png","image/jpeg","image/webp"),data:Ft}),Gt=e=>Wt(e)||zt(e),Vt=Te({role:Ee("system","user","assistant"),content:Kn(Gt)}),Qt=Te({},{model:we,images:kn,json:kn}),Kt=Te({handle:we,messages:Kn(Vt)},{format:Ee("text","json")}),Yt={"llm.select":{optional:{requirements:Qt}},"llm.describe":{required:{handle:we}},"llm.generate":{required:{request:Kt}},"llm.cancel":{required:{requestId:we}}};function Zt(e,n,s){const t=Yt[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 Fe(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 Xt(e,n){return n==="present"?e!=null:Fe(e)===n}function Jt(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&&Fe(s.behavior)!=="object"&&n.push({code:"wrong-type",message:'Intent request field "behavior" must be an object',field:"request.behavior"}),s.handlerHint!==void 0&&es(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 es(e,n){if(Fe(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 Yn(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 ns(e,n){e.servers!==void 0&&Yn(e.servers,"servers",n)}function ts(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&&Yn(i.servers,`${r}.servers`,n)}}}function ss(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=Lt[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,c]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}Xt(s[a],c)||n.push({code:"wrong-type",message:`Field "${a}" should be ${c} but is ${Fe(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"&&Zt(t,s,n),t==="intent.invoke"&&Jt(s.request,n),t==="resource.bytes"&&ns(s,n),t==="resource.bytesMany"&&ts(s.requests,n),{ok:n.length===0,type:t,domain:i,direction:"out",errors:n}}var Zn=5129,rs=15129,ce=35129,hn=[Zn,rs,ce],Xn=["image/png","image/jpeg","image/webp"],Jn=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function et(e,n){return e.tags.find(s=>s[0]===n)}function is(e){return hn.includes(e)}function We(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function nt(e){return et(e,"d")?.[1]||void 0}function os(e){return e.tags.filter(n=>n[0]==="R").map(n=>n[1]?.trim()??"").filter(Boolean)}function tt(e){return nt(e)??et(e,"title")?.[1]??e.id}function as(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=d=>{n.push({code:"invalid-presentation-media",message:`Ignore ${s} tag: ${d} (NIP-5D §Presentation media)`})},r=new Map;for(const d of e.slice(1)){const f=typeof d=="string"?d.indexOf(" "):-1,y=f<0?d:d.slice(0,f),w=f<0?void 0:d.slice(f+1),A=r.get(y)??[];w!==void 0?A.push(w):A.push(""),r.set(y,A)}const i=r.get("x");if(!i||i.length!==1||!We(i[0]))return t("exactly one x field with a lowercase sha256 is required");const o={sha256:i[0]},l=(d,f)=>{const y=r.get(d);if(y){if(y.length!==1||!f(y[0])){n.push({code:"invalid-presentation-media",message:`Ignore ${d} field on ${s} ${o.sha256}: malformed or repeated (NIP-5D §Presentation media)`});return}return y[0]}},a=l("m",d=>Jn.test(d));if(a!==void 0){if(!(s==="preview"?a.toLowerCase().startsWith("video/"):Xn.includes(a.toLowerCase())))return t(`${a} cannot match a decodable ${s==="preview"?"video":"PNG, JPEG or WebP"} format`);o.mimeType=a}const c=l("dim",d=>/^[1-9][0-9]*x[1-9][0-9]*$/.test(d));if(c!==void 0){const[d,f]=c.split("x").map(Number);o.dim={width:d,height:f}}const h=l("size",d=>/^(?:0|[1-9][0-9]*)$/.test(d));if(h!==void 0&&(o.size=Number(h)),s==="preview"){const d=l("duration",f=>/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(f));d!==void 0&&(o.duration=Number(d))}const p=l("alt",d=>d.trim().length>0);return p!==void 0&&(o.alt=p),o}function ze(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=nt(e),r=os(e);is(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||!We(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"}),ls(e,n,s),ds(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 ls(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 ds(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||!xn(i[1]))&&n.push({code:"invalid-metadata",message:"source must contain one HTTP(S), SSH, Git, SCP, or nostr repository location"});cs(e,t.length===1&&t[0].length===2&&xn(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||!We(i[1])||!Xn.includes(i[2])))&&s.push({code:"invalid-icon",message:"Ignore invalid icon metadata and use generic artwork (NIP-5D §Icon)"}),s.push(...as(e).warnings)}function cs(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||!us(o[1])||!We(o[2])||!Jn.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 us(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 xn(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),ps={id:"reference-source-endpoint",catalogId:"reference-source"},ms="https://reference.invalid/blob",fs=`named:${de}:reference-handler`,gs={kind:35129,pubkey:de,id:"0".repeat(64),tags:[["d","reference-handler"],["z","note"],["i","napplet:note/open","event"]]},hs="reference-subscriber",ys="napplet:note/open";function xe(e,n,s){return m({type:e,id:n,result:{entries:[s]}})}var m=e=>[e],j=()=>[];function Mn(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,c=>c.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 bs={"gamepad.subscribe":()=>m({type:"gamepad.state",available:!1,reason:"unavailable",focused:!1,pads:[]}),"gamepad.unsubscribe":j,"relay.subscribe":e=>m({type:"relay.eose",subId:e.subId}),"relay.close":j,"relay.publish":e=>m({type:"relay.publish.result",id:e.id,ok:!0,event:e.event}),"relay.publishEncrypted":e=>m({type:"relay.publishEncrypted.result",id:e.id,ok:!0,event:e.event}),"relay.query":e=>m({type:"relay.query.result",id:e.id,events:[]}),"identity.getPublicKey":e=>m({type:"identity.getPublicKey.result",id:e.id,pubkey:de}),"identity.getRelays":e=>m({type:"identity.getRelays.result",id:e.id,relays:{}}),"identity.getProfile":e=>m({type:"identity.getProfile.result",id:e.id,profile:null}),"identity.getFollows":e=>m({type:"identity.getFollows.result",id:e.id,pubkeys:[]}),"identity.getList":e=>m({type:"identity.getList.result",id:e.id,entries:[]}),"identity.getZaps":e=>m({type:"identity.getZaps.result",id:e.id,zaps:[]}),"identity.getMutes":e=>m({type:"identity.getMutes.result",id:e.id,pubkeys:[]}),"identity.getBlocked":e=>m({type:"identity.getBlocked.result",id:e.id,pubkeys:[]}),"identity.getBadges":e=>m({type:"identity.getBadges.result",id:e.id,badges:[]}),"storage.get":e=>m({type:"storage.get.result",id:e.id,value:null}),"storage.set":e=>m({type:"storage.set.result",id:e.id}),"storage.remove":e=>m({type:"storage.remove.result",id:e.id}),"storage.keys":e=>m({type:"storage.keys.result",id:e.id,keys:[]}),"inc.emit":j,"inc.subscribe":e=>m({type:"inc.subscribe.result",id:e.id}),"inc.unsubscribe":j,"inc.channel.open":e=>m({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=>m({type:"inc.channel.list.result",id:e.id,channels:[]}),"inc.channel.close":j,"theme.get":e=>m({type:"theme.get.result",id:e.id,theme:{colors:{background:"#000000",text:"#ffffff",primary:"#663399"}}}),"keys.forward":j,"keys.registerAction":e=>m({type:"keys.registerAction.result",id:e.id,actionId:`action-${String(e.id)}`}),"keys.unregisterAction":j,"media.session.create":e=>m({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=>m({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=>m({type:"notify.permission.result",id:e.id,granted:!0}),"config.registerSchema":e=>m({type:"config.registerSchema.result",id:e.id,ok:!0}),"config.get":e=>m({type:"config.values",id:e.id,values:{}}),"config.subscribe":()=>m({type:"config.values",values:{}}),"config.unsubscribe":j,"config.openSettings":j,"resource.bytes":e=>{const n=Mn(e.url);return m(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=>m({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=Mn(s);return{url:typeof s=="string"?s:"",ok:!0,blob:t?.blob??new Blob([]),mime:t?.mime??"application/octet-stream"}}):[]}),"resource.info":e=>m({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=>m({type:"cvm.discover.result",id:e.id,servers:[]}),"cvm.request":e=>m({type:"cvm.request.result",id:e.id,message:{}}),"cvm.close":e=>m({type:"cvm.close.result",id:e.id}),"outbox.getEvent":e=>m({type:"outbox.getEvent.result",id:e.id}),"outbox.query":e=>m({type:"outbox.query.result",id:e.id,events:[]}),"outbox.subscribe":e=>m({type:"outbox.closed",subId:e.subId,reason:"reference shell complete"}),"outbox.close":j,"outbox.publish":e=>m({type:"outbox.publish.result",id:e.id,ok:!0}),"outbox.resolveRelays":e=>m({type:"outbox.resolveRelays.result",id:e.id,plan:{}}),"upload.info":e=>m({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=>m({type:"upload.upload.result",id:e.id,result:{url:ms}}),"upload.status":e=>m({type:"upload.status.result",id:e.id,status:{}}),"ble.open":e=>m({type:"ble.open.result",id:e.id,session:{id:"ble-reference",state:"open",device:{id:"reference-device",name:"Reference BLE"}}}),"ble.services":e=>m({type:"ble.services.result",id:e.id,services:[]}),"ble.read":e=>m({type:"ble.read.result",id:e.id,data:[]}),"ble.write":e=>m({type:"ble.write.result",id:e.id}),"ble.subscribe":e=>m({type:"ble.subscribe.result",id:e.id}),"ble.unsubscribe":e=>m({type:"ble.unsubscribe.result",id:e.id}),"ble.close":e=>m({type:"ble.close.result",id:e.id}),"common.encodeNip19":e=>m({type:"common.encodeNip19.result",id:e.id,ok:!0,value:"npub1reference",nip19Type:"npub"}),"common.decodeNip19":e=>m({type:"common.decodeNip19.result",id:e.id,ok:!0,nip19Type:"npub",hex:de}),"common.getProfile":e=>m({type:"common.getProfile.result",id:e.id,ok:!0,pubkey:de,profile:null}),"common.follows":e=>m({type:"common.follows.result",id:e.id,ok:!0,pubkeys:[]}),"common.follow":e=>m({type:"common.follow.result",id:e.id,ok:!0}),"common.unfollow":e=>m({type:"common.unfollow.result",id:e.id,ok:!0}),"common.react":e=>m({type:"common.react.result",id:e.id,ok:!0,eventId:"0".repeat(64)}),"common.report":e=>m({type:"common.report.result",id:e.id,ok:!0,eventId:"1".repeat(64)}),"webrtc.open":e=>m({type:"webrtc.open.result",id:e.id,session:{id:"webrtc-reference",scope:{type:"direct",pubkey:de},channel:"default",state:"connecting"}}),"webrtc.send":e=>m({type:"webrtc.send.result",id:e.id}),"webrtc.close":e=>m({type:"webrtc.close.result",id:e.id}),"link.open":e=>m({type:"link.open.result",id:e.id,status:"opened"}),"count.query":e=>m({type:"count.query.result",id:e.id,ok:!0,count:0}),"lists.supported":e=>m({type:"lists.supported.result",id:e.id,lists:[]}),"lists.add":e=>m({type:"lists.add.result",id:e.id,ok:!0,added:0,skipped:0}),"lists.remove":e=>m({type:"lists.remove.result",id:e.id,ok:!0,removed:0,skipped:0}),"serial.open":e=>m({type:"serial.open.result",id:e.id,session:{id:`serial-${String(e.id)}`,state:"open"}}),"serial.write":e=>m({type:"serial.write.result",id:e.id}),"serial.close":e=>m({type:"serial.close.result",id:e.id}),"fs.info":e=>m({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=>m({type:"fs.stat.result",id:e.id,metadata:{path:e.path,kind:"file",size:0}}),"fs.list":e=>m({type:"fs.list.result",id:e.id,entries:[]}),"fs.read":e=>m({type:"fs.read.result",id:e.id,result:{data:"",offset:0,bytesRead:0,eof:!0,size:0}}),"fs.write":e=>m({type:"fs.write.result",id:e.id,result:{bytesWritten:0,size:0}}),"fs.mkdir":e=>m({type:"fs.mkdir.result",id:e.id}),"fs.remove":e=>m({type:"fs.remove.result",id:e.id}),"fs.move":e=>m({type:"fs.move.result",id:e.id}),"fs.watch":e=>m({type:"fs.watch.result",id:e.id,watchId:`watch-${String(e.id)}`}),"fs.unwatch":e=>m({type:"fs.unwatch.result",id:e.id})},st={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 vs(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 rt(e){return{handle:e,...st}}function ws(e,n){const s=qe(n.requirements);if(s.model!==void 0&&s.model!==st.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:rt(t)}}function Es(e,n){const s=String(n.handle);return e.handles.has(s)?{model:rt(s)}:be("selection-expired","Select a model again")}function Ss(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 Rs(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=Ss(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 Ts(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 _s(e,n,s){const t=String(s.type),r=String(s.id),i=vs(e,n);switch(t){case"llm.select":return[{type:"llm.select.result",id:r,...ws(i,s)}];case"llm.describe":return[{type:"llm.describe.result",id:r,...Es(i,s)}];case"llm.generate":return structuredClone(Rs(i,r,s));case"llm.cancel":return Ts(i,r,s);default:return[{type:`${t}.result`,id:r,error:{code:"invalid-request",message:`Unknown operation ${t}`}}]}}function ks(){const e=new Map;return{handle:(n,s)=>_s(e,n,s),reset(){e.clear()}}}function Is(e){const n=new Set,s=e.domains?new Set(e.domains):null,t=ks();return Object.assign((i,o)=>{const l=xs(o),a=ss(o);if(e.records.push({envelope:o,verdict:a,timestamp:e.now()}),!l||!a.ok)return[];const c=i.domains??$e,h=s?c.filter(f=>s.has(f)):c;if(!h.includes(l.slice(0,l.indexOf("."))))return[];if(l==="shell.ready")return n.has(i.id)?[]:(n.add(i.id),m({type:"shell.init",capabilities:{domains:[...h]},services:[]}));const p=o;if(l.startsWith("llm."))return t.handle(i,p);if(l==="intent.invoke")return e.intents.handleInvoke(i,p);if(l==="intent.available")return m({type:"intent.available.result",id:p.id,availability:e.intents.availability(p.archetype)});if(l==="intent.handlers")return m({type:"intent.handlers.result",id:p.id,handlers:e.intents.handlers()});if(l==="inc.emit")return Ms(i,p,e.queueDelivery);const d=bs[l];return d?d(p):[]},{reset(){t.reset()}})}function xs(e){if(!e||typeof e!="object")return;const n=e.type;return typeof n=="string"?n:void 0}function Ms(e,n,s){if(n.topic!==ys)return[];const t={type:"inc.event",topic:n.topic,sender:e.id};return"payload"in n&&(t.payload=n.payload),s(hs,t),[]}function Us(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 As(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 Ps(e,n,s){const t=[];for(const r of e){const i=As(r,n);if(!i.length)continue;const o=r.tags.find(a=>a[0]==="title")?.[1],l=Us(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 js(e,n=[gs],s={note:fs}){const t=r=>Ps(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(f=>f.conventions.includes(o.convention)),a=o.handler&&!["default","choose"].includes(o.handler),c=o.handler==="choose"?void 0:a?l.find(f=>f.id===o.handler):l.find(f=>f.isDefault)??l[0];if(!c)return m({type:"intent.invoke.result",id:i.id,result:{ok:!1,error:"no handler"}});const{archetype:h,action:p,convention:d}=o;return e(c.id,structuredClone({type:"intent.deliver",delivery:{sender:r.catalogId,archetype:h,action:p,convention:d,..."payload"in o?{payload:o.payload}:{}}})),m({type:"intent.invoke.result",id:i.id,result:{ok:!0,archetype:h,action:p,convention:d,handler:c.id}})}}}function Os(e={}){const n=[],s=qs(),t=Is({now:e.now??Date.now,records:n,domains:e.domains,queueDelivery:s.queue,intents:js(s.queue,e.manifests,e.defaults)});return{get records(){return n},handle:r=>t(ps,r),handleFrom:t,takeDeliveries:s.take,reset(){n.length=0,t.reset(),s.clear()}}}function qs(){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 Cs(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 it="__nappletConformance.error",ot="__nappletConformance.installed";function Un(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;")}function Hs(){return`(() => {
2
2
  const report = (reason) => {
3
- try { window.parent.postMessage({ type: '${rt}', reason: String(reason && reason.message || reason) }, '*'); }
3
+ try { window.parent.postMessage({ type: '${it}', reason: String(reason && reason.message || reason) }, '*'); }
4
4
  catch {}
5
5
  };
6
6
  window.addEventListener('error', (event) => report(event.error || event.message));
7
7
  window.addEventListener('unhandledrejection', (event) => report(event.reason));
8
- })();`}function Cs(e,n){const s=`window.parent.postMessage({ type: '${it}', installed: !!window.napplet }, '*');`;return`${n}
8
+ })();`}function Ds(e,n){const s=`window.parent.postMessage({ type: '${ot}', installed: !!window.napplet }, '*');`;return`${n}
9
9
  ;globalThis.NappletShimPrelude.install(${JSON.stringify({domains:e})});
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";
10
+ ${s}`}function Bs(e,n,s,t){const r=`<base href="${Ns(n)}">`,i=Ds(s,t).replace(/<\/script/gi,"<\\/script"),o=`<script>${Hs()}<\/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 Ls(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 $s(e){if(e==="about:blank")return"<!doctype html><html><head></head><body></body></html>";const n=Ls(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 An(e,n,s,t){const r=Os({domains:e}),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=p=>{if(p.source!==i.contentWindow)return;const d=p.data;if(d&&typeof d=="object"&&d.type===ot){l=d.installed===!0;return}if(d&&typeof d=="object"&&d.type===it){o=`napplet boot error: ${String(d.reason??"unknown error")}`;return}const f=r.handle(p.data),y=p.source;for(const w of f)y?.postMessage(w,"*")};let c=!1;const h=new Promise(p=>{i.addEventListener("load",()=>{c=!0,p()},{once:!0})});t.addEventListener("message",a);try{const p=n.html??await $s(n.url);i.srcdoc=Bs(p,n.url,e,n.runtimePreludeSource),(s.body??s.documentElement).appendChild(i)}catch(p){o=p instanceof Error?p.message:String(p)}if(!o){const p=Symbol("timeout");await Promise.race([h.then(()=>"loaded"),Un(n.readyTimeoutMs).then(()=>p)])===p||!c?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 Un(n.settleMs)}t.removeEventListener("message",a);try{i.remove()}catch{}return{installedGlobal:l,bootError:o,emitted:[...r.records]}}async function Fs(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=e.domains??$e,i=e.maturity?Bt({...e.maturity,candidates:r}).domains:r,o=await An(i,t,n,s);let l=null;{const a=await An([],t,n,s);l={bootError:a.bootError,emitted:a.emitted}}return{installedGlobal:o.installedGlobal,bootError:o.bootError,emitted:o.emitted,degraded:l}}var Ws=e=>({status:"pass",detail:e}),zs=(e,n)=>({status:"fail",detail:e,diagnostics:n}),Gs=e=>({status:"skip",detail:e}),P={pass:Ws,fail:zs,skip:Gs};function Vs(e,n){const s=ze(e.manifestEvent);return[...s.errors,...s.warnings].filter(t=>n.includes(t.code))}function fe(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=Vs(r,s);return i.length?P.fail(i[0].message,i):P.pass()}}}var Qs=[fe("manifest/event-kind","Resolved event is a NIP-5D napplet manifest",["invalid-napplet-kind","missing-d-tag","unexpected-d-tag"]),fe("manifest/index-html","Manifest declares a hashed /index.html",["invalid-artifact-hash","missing-description","invalid-metadata"]),fe("manifest/requires","R/O tags name bare NAP domains",["invalid-required-nap","invalid-optional-nap"]),fe("manifest/requires-known","R/O domains are in this toolchain registry (advisory)",["unknown-required-nap"],"warning"),fe("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?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 Ks(e,n={}){const s=n.now??(()=>Date.now()),t=n.checks??Qs,r=s(),i=t.map(a=>{const c=a.run(e);return{id:a.id,area:a.area,severity:a.severity,title:a.title,status:c.status,detail:c.detail,diagnostics:c.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?tt(e.manifestEvent):void 0,startedAt:r,finishedAt:s(),checks:i,summary:o,ok:o.errors===0}}function Ys(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",tt(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 Zs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function yn(e,n=""){if(!Number.isSafeInteger(e)||e<0){const s=n&&`"${n}" `;throw new Error(`${s}expected integer >= 0, got ${e}`)}}function L(e,n,s=""){const t=Zs(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 Xs(e,n){L(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 an(...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 at=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Js=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function C(e){if(L(e),at)return e.toHex();let n="";for(let s=0;s<e.length;s++)n+=Js[e[s]];return n}const X={_0:48,_9:57,A:65,F:70,a:97,f:102};function jn(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 Z(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(at)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=jn(e.charCodeAt(i)),l=jn(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 Ce(...e){let n=0;for(let t=0;t<e.length;t++){const r=e[t];L(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 er(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 lt(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 nr=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 dt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ct(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 tr(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 ut(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function ln(e){if(!Array.isArray(e))throw new Error("array expected")}function pt(e,n){if(!ct(!0,n))throw new Error(`${e}: array of strings expected`)}function mt(e,n){if(!ct(!1,n))throw new Error(`${e}: array of numbers expected`)}function sr(...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 rr(e){const n=typeof e=="string"?e.split(""):e,s=n.length;pt("alphabet",n);const t=new Map(n.map((r,i)=>[r,i]));return{encode:r=>(ln(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=>(ln(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 ir(e=""){return Se("join",e),{encode:n=>(pt("join.decode",n),n.join(e)),decode:n=>(Se("join.decode",n),n.split(e))}}const ft=(e,n)=>n===0?e:ft(n,e%n),Ne=(e,n)=>e+(n-ft(e,n)),Pe=(()=>{let e=[];for(let n=0;n<40;n++)e.push(2**n);return e})();function dn(e,n,s,t){if(ln(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(Ne(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${Ne(n,s)}`);let r=0,i=0;const o=Pe[n],l=Pe[s]-1,a=[];for(const c of e){if(ut(c),c>=o)throw new Error(`convertRadix2: invalid data word=${c} from=${n}`);if(r=r<<n|c,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=Pe[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 or(e,n=!1){if(ut(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Ne(8,e)>32||Ne(e,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!dt(s))throw new Error("radix2.encode input should be Uint8Array");return dn(Array.from(s),8,e,!n)},decode:s=>(mt("radix2.decode",s),Uint8Array.from(dn(s,e,8,n)))}}function On(e){return tr(e),function(...n){try{return e.apply(null,n)}catch{}}}const cn=sr(rr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ir("")),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 Cn(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,cn.encode(dn([r%Pe[30]],30,5,!1))}function ar(e){const n=e==="bech32"?1:734539939,s=or(5),t=s.decode,r=s.encode,i=On(t);function o(p,d,f=90){Se("bech32.encode prefix",p),dt(d)&&(d=Array.from(d)),mt("bech32.encode",d);const y=p.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);const w=y+7+d.length;if(f!==!1&&w>f)throw new TypeError(`Length ${w} exceeds limit ${f}`);const A=p.toLowerCase(),O=Cn(A,d,n);return`${A}1${cn.encode(d)}${O}`}function l(p,d=90){Se("bech32.decode input",p);const f=p.length;if(f<8||d!==!1&&f>d)throw new TypeError(`invalid string length: ${f} (${p}). Expected (8..${d})`);const y=p.toLowerCase();if(p!==y&&p!==p.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 A=y.slice(0,w),O=y.slice(w+1);if(O.length<6)throw new Error("Data must be at least 6 characters long");const V=cn.decode(O).slice(0,-6),J=Cn(A,V,n);if(!O.endsWith(J))throw new Error(`Invalid checksum in ${p}: expected "${J}"`);return{prefix:A,words:V}}const a=On(l);function c(p){const{prefix:d,words:f}=l(p,!1);return{prefix:d,words:f,bytes:t(f)}}function h(p,d){return o(p,r(d))}return{encode:o,decode:l,encodeFromBytes:h,decodeToBytes:c,decodeUnsafe:a,fromWords:t,fromWordsUnsafe:i,toWords:r}}const Nn=ar("bech32");var Me=new TextDecoder("utf-8");new TextEncoder;var lr=5e3;function dr(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),cr(e)}catch{return{type:"invalid",data:null}}}function cr(e){let{prefix:n,words:s}=Nn.decode(e,lr),t=new Uint8Array(Nn.fromWords(s));switch(n){case"nprofile":{let r=Xe(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=Xe(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=Xe(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 Xe(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 ur(e,n,s){return e&n^~e&s}function pr(e,n,s){return e&n^e&s^n&s}class mr{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),L(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),Xs(n,this),this.finished=!0;const{buffer:s,view:t,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,an(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(t,0),o=0);for(let p=o;p<r;p++)s[p]=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 c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<c;p++)l.setUint32(4*p,h[p],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]),fr=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 gr extends mr{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 p=0;p<16;p++,s+=4)ne[p]=n.getUint32(s,!1);for(let p=16;p<64;p++){const d=ne[p-15],f=ne[p-2],y=K(d,7)^K(d,18)^d>>>3,w=K(f,17)^K(f,19)^f>>>10;ne[p]=w+ne[p-7]+y+ne[p-16]|0}let{A:t,B:r,C:i,D:o,E:l,F:a,G:c,H:h}=this;for(let p=0;p<64;p++){const d=K(l,6)^K(l,11)^K(l,25),f=h+d+ur(l,a,c)+fr[p]+ne[p]|0,w=(K(t,2)^K(t,13)^K(t,22))+pr(t,r,i)|0;h=c,c=a,a=l,l=o+f|0,o=i,i=r,r=t,t=f+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,c=c+this.G|0,h=h+this.H|0,this.set(t,r,i,o,l,a,c,h)}roundClean(){an(ne)}destroy(){this.set(0,0,0,0,0,0,0,0),an(this.buffer)}}class hr extends gr{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=er(()=>new hr,nr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bn=BigInt(0),un=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 yr(e){if(typeof e=="bigint"){if(!wr(e))throw new Error("positive bigint expected, got "+e)}else yn(e);return e}function gt(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?bn:BigInt("0x"+e)}function vn(e){return gt(C(e))}function ht(e){return gt(C(br(L(e)).reverse()))}function wn(e,n){yn(n),e=yr(e);const s=Z(e.toString(16).padStart(n*2,"0"));if(s.length!==n)throw new Error("number too large");return s}function yt(e,n){return wn(e,n).reverse()}function br(e){return Uint8Array.from(e)}function vr(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 wr=e=>typeof e=="bigint"&&bn<=e;function Er(e){let n;for(n=0;e>bn;e>>=un,n+=1);return n}const bt=e=>(un<<BigInt(e))-un;function vt(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 c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}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 B=BigInt(0),D=BigInt(1),ie=BigInt(2),wt=BigInt(3),Et=BigInt(4),St=BigInt(5),Sr=BigInt(7),Rt=BigInt(8),Rr=BigInt(9),Tt=BigInt(16);function G(e,n){const s=e%n;return s>=B?s:n+s}function F(e,n,s){let t=e;for(;n-- >B;)t*=t,t%=s;return t}function Bn(e,n){if(e===B)throw new Error("invert: expected non-zero number");if(n<=B)throw new Error("invert: expected positive modulus, got "+n);let s=G(e,n),t=n,r=B,i=D;for(;s!==B;){const l=t/s,a=t%s,c=r-i*l;t=s,s=a,r=i,i=c}if(t!==D)throw new Error("invert: does not exist");return G(r,n)}function En(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+D)/Et,t=e.pow(n,s);return En(e,t,n),t}function Tr(e,n){const s=(e.ORDER-St)/Rt,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 En(e,l,n),l}function _r(e){const n=Ge(e),s=kt(e),t=s(n,n.neg(n.ONE)),r=s(n,t),i=s(n,n.neg(t)),o=(e+Sr)/Tt;return(l,a)=>{let c=l.pow(a,o),h=l.mul(c,t);const p=l.mul(c,r),d=l.mul(c,i),f=l.eql(l.sqr(h),a),y=l.eql(l.sqr(p),a);c=l.cmov(c,h,f),h=l.cmov(d,p,y);const w=l.eql(l.sqr(h),a),A=l.cmov(c,h,w);return En(l,A,a),A}}function kt(e){if(e<wt)throw new Error("sqrt is not defined for small field");let n=e-D,s=0;for(;n%ie===B;)n/=ie,s++;let t=ie;const r=Ge(e);for(;Ln(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+D)/ie;return function(a,c){if(a.is0(c))return c;if(Ln(a,c)!==1)throw new Error("Cannot find square root");let h=s,p=a.mul(a.ONE,i),d=a.pow(c,n),f=a.pow(c,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let y=1,w=a.sqr(d);for(;!a.eql(w,a.ONE);)if(y++,w=a.sqr(w),y===h)throw new Error("Cannot find square root");const A=D<<BigInt(h-y-1),O=a.pow(p,A);h=y,p=a.sqr(O),d=a.mul(d,p),f=a.mul(f,O)}return f}}function kr(e){return e%Et===wt?_t:e%Rt===St?Tr:e%Tt===Rr?_r(e):kt(e)}const Ir=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xr(e){const n={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ir.reduce((t,r)=>(t[r]="function",t),n);return vt(e,s),e}function Mr(e,n,s){if(s<B)throw new Error("invalid exponent, negatives unsupported");if(s===B)return e.ONE;if(s===D)return n;let t=e.ONE,r=n;for(;s>B;)s&D&&(t=e.mul(t,r)),r=e.sqr(r),s>>=D;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 Ln(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 Ur(e,n){n!==void 0&&yn(n);const s=n!==void 0?n:e.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ar{ORDER;BITS;BYTES;isLE;ZERO=B;ONE=D;_lengths;_sqrt;_mod;constructor(n,s={}){if(n<=B)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}=Ur(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 G(n,this.ORDER)}isValid(n){if(typeof n!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof n);return B<=n&&n<this.ORDER}is0(n){return n===B}isValidNot0(n){return!this.is0(n)&&this.isValid(n)}isOdd(n){return(n&D)===D}neg(n){return G(-n,this.ORDER)}eql(n,s){return n===s}sqr(n){return G(n*n,this.ORDER)}add(n,s){return G(n+s,this.ORDER)}sub(n,s){return G(n-s,this.ORDER)}mul(n,s){return G(n*s,this.ORDER)}pow(n,s){return Mr(this,n,s)}div(n,s){return G(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=kr(this.ORDER)),this._sqrt(this,n)}toBytes(n){return this.isLE?yt(n,this.BYTES):wn(n,this.BYTES)}fromBytes(n,s=!1){L(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 c=new Uint8Array(r);c.set(n,i?0:c.length-n.length),n=c}if(n.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+n.length);let a=i?ht(n):vn(n);if(l&&(a=G(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 Ar(e,n)}function xt(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 Pr(e){const n=xt(e);return n+Math.ceil(n/2)}function jr(e,n,s=!1){L(e);const t=e.length,r=xt(n),i=Pr(n);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?ht(e):vn(e),l=G(o,n-D)+D;return s?yt(l,r):wn(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 Mt(e,n){if(!Number.isSafeInteger(e)||e<=0||e>n)throw new Error("invalid window size, expected [1.."+n+"], got W="+e)}function Je(e,n){Mt(e,n);const s=Math.ceil(n/e)+1,t=2**(e-1),r=2**e,i=bt(e),o=BigInt(e);return{windows:s,windowSize:t,mask:i,maxNumber:r,shiftBy:o}}function Fn(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 c=n*t,h=c+Math.abs(l)-1,p=l===0,d=l<0,f=n%2!==0;return{nextN:a,offset:h,isZero:p,isNeg:d,isNegF:f,offsetF:c}}const en=new WeakMap,Ut=new WeakMap;function nn(e){return Ut.get(e)||1}function Wn(e){if(e!==ue)throw new Error("invalid wNAF")}class Or{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}=Je(s,this.bits),i=[];let o=n,l=o;for(let a=0;a<t;a++){l=o,i.push(l);for(let c=1;c<r;c++)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=Je(n,this.bits);for(let l=0;l<o.windows;l++){const{nextN:a,offset:c,isZero:h,isNeg:p,isNegF:d,offsetF:f}=Fn(t,l,o);t=a,h?i=i.add(De(d,s[f])):r=r.add(De(p,s[c]))}return Wn(t),{p:r,f:i}}wNAFUnsafe(n,s,t,r=this.ZERO){const i=Je(n,this.bits);for(let o=0;o<i.windows&&t!==ue;o++){const{nextN:l,offset:a,isZero:c,isNeg:h}=Fn(t,o,i);if(t=l,!c){const p=s[a];r=r.add(h?p.negate():p)}}return Wn(t),r}getPrecomputes(n,s,t){let r=en.get(s);return r||(r=this.precomputeWindow(s,n),n!==1&&(typeof t=="function"&&(r=t(r)),en.set(s,r))),r}cached(n,s,t){const r=nn(n);return this.wNAF(r,this.getPrecomputes(r,n,t),s)}unsafe(n,s,t,r){const i=nn(n);return i===1?this._unsafeLadder(n,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,n,t),s,r)}createCache(n,s){Mt(s,this.bits),Ut.set(n,s),en.delete(n)}hasCache(n){return nn(n)!==1}}function qr(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 zn(e,n,s){if(n){if(n.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xr(n),n}else return Ge(e,{isLE:s})}function Cr(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 c=n[a];if(!(typeof c=="bigint"&&c>ue))throw new Error(`CURVE.${a} must be positive bigint`)}const r=zn(n.p,s.Fp,t),i=zn(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 Nr(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)/Dr)/n;function Hr(e,n,s){const[[t,r],[i,o]]=n,l=Gn(o*e,s),a=Gn(-r*e,s);let c=e-l*t-a*i,h=-l*r-a*o;const p=c<he,d=h<he;p&&(c=-c),d&&(h=-h);const f=bt(Math.ceil(Er(s)/2))+je;if(c<he||c>=f||h<he||h>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:c,k2neg:d,k2:h}}const he=BigInt(0),je=BigInt(1),Dr=BigInt(2),Ue=BigInt(3),Br=BigInt(4);function Lr(e,n={}){const s=Cr("weierstrass",e,n),{Fp:t,Fn:r}=s;let i=s.CURVE;const{h:o,n:l}=i;vt(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 c=Fr(t,r);function h(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(I,g,b){const{x:E,y:S}=g.toAffine(),x=t.toBytes(E);if(Hn(b,"isCompressed"),b){h();const _=!t.isOdd(S);return Ce($r(_),x)}else return Ce(Uint8Array.of(4),x,t.toBytes(S))}function d(I){L(I,void 0,"Point");const{publicKey:g,publicKeyUncompressed:b}=c,E=I.length,S=I[0],x=I.subarray(1);if(E===g&&(S===2||S===3)){const _=t.fromBytes(x);if(!t.isValid(_))throw new Error("bad point: is not on curve, wrong x");const R=w(_);let v;try{v=t.sqrt(R)}catch($){const q=$ instanceof Error?": "+$.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:_,y:v}}else if(E===b&&S===4){const _=t.BYTES,R=t.fromBytes(x.subarray(0,_)),v=t.fromBytes(x.subarray(_,_*2));if(!A(R,v))throw new Error("bad point: is not on curve");return{x:R,y:v}}else throw new Error(`bad point: got length ${E}, expected compressed=${g} or uncompressed=${b}`)}const f=n.toBytes||p,y=n.fromBytes||d;function w(I){const g=t.sqr(I),b=t.mul(g,I);return t.add(t.add(b,t.mul(I,i.a)),i.b)}function A(I,g){const b=t.sqr(g),E=w(I);return t.eql(b,E)}if(!A(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const O=t.mul(t.pow(i.a,Ue),Br),V=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(O,V)))throw new Error("bad curve params: a or b");function J(I,g,b=!1){if(!t.isValid(g)||b&&t.is0(g))throw new Error(`bad point coordinate ${I}`);return g}function _e(I){if(!(I instanceof U))throw new Error("Weierstrass Point expected")}function ke(I){if(!a||!a.basises)throw new Error("no endo");return Hr(I,a.basises,r.ORDER)}const Ie=Dn((I,g)=>{const{X:b,Y:E,Z:S}=I;if(t.eql(S,t.ONE))return{x:b,y:E};const x=I.is0();g==null&&(g=x?t.ONE:t.inv(S));const _=t.mul(b,g),R=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:_,y:R}}),Ht=Dn(I=>{if(I.is0()){if(n.allowInfinityPoint&&!t.is0(I.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:b}=I.toAffine();if(!t.isValid(g)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!A(g,b))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Tn(I,g,b,E,S){return b=new U(t.mul(b.X,I),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(L(g,void 0,"point")));return b.assertValidity(),b}static fromHex(g){return U.fromBytes(Z(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){return me.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){_e(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:_,Z:R}=g,v=t.eql(t.mul(b,R),t.mul(x,S)),T=t.eql(t.mul(E,R),t.mul(_,S));return v&&T}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:_}=this;let R=t.ZERO,v=t.ZERO,T=t.ZERO,k=t.mul(S,S),$=t.mul(x,x),q=t.mul(_,_),M=t.mul(S,x);return M=t.add(M,M),T=t.mul(S,_),T=t.add(T,T),R=t.mul(g,T),v=t.mul(E,q),v=t.add(R,v),R=t.sub($,v),v=t.add($,v),v=t.mul(R,v),R=t.mul(M,R),T=t.mul(E,T),q=t.mul(g,q),M=t.sub(k,q),M=t.mul(g,M),M=t.add(M,T),T=t.add(k,k),k=t.add(T,k),k=t.add(k,q),k=t.mul(k,M),v=t.add(v,k),q=t.mul(x,_),q=t.add(q,q),k=t.mul(q,M),R=t.sub(R,k),T=t.mul(q,$),T=t.add(T,T),T=t.add(T,T),new U(R,v,T)}add(g){_e(g);const{X:b,Y:E,Z:S}=this,{X:x,Y:_,Z:R}=g;let v=t.ZERO,T=t.ZERO,k=t.ZERO;const $=i.a,q=t.mul(i.b,Ue);let M=t.mul(b,x),W=t.mul(E,_),z=t.mul(S,R),ae=t.add(b,E),H=t.add(x,_);ae=t.mul(ae,H),H=t.add(M,W),ae=t.sub(ae,H),H=t.add(b,S);let Q=t.add(x,R);return H=t.mul(H,Q),Q=t.add(M,z),H=t.sub(H,Q),Q=t.add(E,S),v=t.add(_,R),Q=t.mul(Q,v),v=t.add(W,z),Q=t.sub(Q,v),k=t.mul($,H),v=t.mul(q,z),k=t.add(v,k),v=t.sub(W,k),k=t.add(W,k),T=t.mul(v,k),W=t.add(M,M),W=t.add(W,M),z=t.mul($,z),H=t.mul(q,H),W=t.add(W,z),z=t.sub(M,z),z=t.mul($,z),H=t.add(H,z),M=t.mul(W,H),T=t.add(T,M),M=t.mul(Q,H),v=t.mul(ae,v),v=t.sub(v,M),M=t.mul(ae,W),k=t.mul(Q,k),k=t.add(k,M),new U(v,T,k)}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=_=>me.cached(this,_,R=>$n(U,R));if(b){const{k1neg:_,k1:R,k2neg:v,k2:T}=ke(g),{p:k,f:$}=x(R),{p:q,f:M}=x(T);S=$.add(M),E=Tn(b.beta,k,q,_,v)}else{const{p:_,f:R}=x(g);E=_,S=R}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(me.hasCache(this))return this.multiply(g);if(b){const{k1neg:S,k1:x,k2neg:_,k2:R}=ke(g),{p1:v,p2:T}=qr(U,E,x,R);return Tn(b.beta,v,T,S,_)}else return me.unsafe(E,g)}toAffine(g){return Ie(this,g)}isTorsionFree(){const{isTorsionFree:g}=n;return o===je?!0:g?g(U,this):me.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(),f(U,this,g)}toHex(g=!0){return C(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const _n=r.BITS,me=new Or(U,n.endo?Math.ceil(_n/2):_n);return U.BASE.precompute(8),U}function $r(e){return Uint8Array.of(e?2:3)}function Fr(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")},Wr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},zr=BigInt(0),pn=BigInt(2);function Gr(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),c=e*e*e%n,h=c*c*e%n,p=F(h,s,n)*h%n,d=F(p,s,n)*h%n,f=F(d,pn,n)*c%n,y=F(f,r,n)*f%n,w=F(y,i,n)*y%n,A=F(w,l,n)*w%n,O=F(A,a,n)*A%n,V=F(O,l,n)*w%n,J=F(V,s,n)*h%n,_e=F(J,o,n)*y%n,ke=F(_e,t,n)*c%n,Ie=F(ke,pn,n);if(!Be.eql(Be.sqr(Ie),e))throw new Error("Cannot find square root");return Ie}const Be=Ge(Ve.p,{sqrt:Gr}),pe=Lr(Ve,{Fp:Be,endo:Wr}),Vn={};function Le(e,...n){let s=Vn[e];if(s===void 0){const t=He(vr(e));s=Ce(t,t),Vn[e]=s}return He(Ce(s,...n))}const Sn=e=>e.toBytes(!0).slice(1),Rn=e=>e%pn===zr;function mn(e){const{Fn:n,BASE:s}=pe,t=n.fromBytes(e),r=s.multiply(t);return{scalar:Rn(r.y)?t:n.neg(t),bytes:Sn(r)}}function At(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);Rn(r)||(r=n.neg(r));const i=pe.fromAffine({x:e,y:r});return i.assertValidity(),i}const ve=vn;function Pt(...e){return pe.Fn.create(ve(Le("BIP0340/challenge",...e)))}function Qn(e){return mn(e).bytes}function Vr(e,n,s=lt(32)){const{Fn:t}=pe,r=L(e,void 0,"message"),{bytes:i,scalar:o}=mn(n),l=L(s,32,"auxRand"),a=t.toBytes(o^ve(Le("BIP0340/aux",l))),c=Le("BIP0340/nonce",a,i,r),{bytes:h,scalar:p}=mn(c),d=Pt(h,i,r),f=new Uint8Array(64);if(f.set(h,0),f.set(t.toBytes(t.create(p+d*o)),32),!jt(f,r,i))throw new Error("sign: Invalid signature produced");return f}function jt(e,n,s){const{Fp:t,Fn:r,BASE:i}=pe,o=L(e,64,"signature"),l=L(n,void 0,"message"),a=L(s,32,"publicKey");try{const c=At(ve(a)),h=ve(o.subarray(0,32));if(!t.isValidNot0(h))return!1;const p=ve(o.subarray(32,64));if(!r.isValidNot0(p))return!1;const d=Pt(r.toBytes(h),Sn(c),l),f=i.multiplyUnsafe(p).add(c.multiplyUnsafe(r.neg(d))),{x:y,y:w}=f.toAffine();return!(f.is0()||!Rn(w)||y!==h)}catch{return!1}}const Y=(()=>{const s=(t=lt(48))=>jr(t,Ve.n);return{keygen:Nr(s,Qn),getPublicKey:Qn,sign:Vr,verify:jt,Point:pe,utils:{randomSecretKey:s,taggedHash:Le,lift_x:At,pointToBytes:Sn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var re=Symbol("verified"),Qr=e=>e instanceof Object;function Kr(e){if(!Qr(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 Yr=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 Zr=class{generateSecretKey(){return Y.utils.randomSecretKey()}getPublicKey(n){return C(Y.getPublicKey(n))}finalizeEvent(n,s){const t=n;return t.pubkey=C(Y.getPublicKey(s)),t.id=tn(t),t.sig=C(Y.sign(Z(tn(t)),s)),t[re]=!0,t}verifyEvent(n){if(typeof n[re]=="boolean")return n[re];try{const s=tn(n);if(s!==n.id)return n[re]=!1,!1;const t=Y.verify(Z(n.sig),Z(s),Z(n.pubkey));return n[re]=t,t}catch{return n[re]=!1,!1}}};function Xr(e){if(!Kr(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(Yr.encode(Xr(e)));return C(n)}var Qe=new Zr;Qe.generateSecretKey;Qe.getPublicKey;Qe.finalizeEvent;var Jr=Qe.verifyEvent,ei=22242;function ni(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 ti(e,n){for(let s=0;s<e.length;s++)if(ni(e[s],n))return!0;return!1}function si(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 ri(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 ii(e,n){return{kind:ei,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",n]],content:""}}var Ot=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 Ot(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(ii(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 oi(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=ri(n);if(s){const t=this.openSubs.get(s);if(!t)return;const r=si(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)&&ti(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}}},oi=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 Ot))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)}},ai=e=>(e[re]=!0,!0),li=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)?ai: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 d of e){const{url:f,filter:y}=d;s.has(f)||s.set(f,[]),s.get(f).push(y)}const t=Array.from(s.entries()).map(([d,f])=>({url:d,filters:f}));this.trackRelays&&(n.receivedEvent=(d,f)=>{let y=this.seenOn.get(f);y||(y=new Set,this.seenOn.set(f,y)),y.add(d)});const r=new Set,i=[],o=[];let l=d=>{o[d]||(o[d]=!0,o.filter(f=>f).length===t.length&&(n.oneose?.(),l=()=>{}))};const a=[];let c=(d,f)=>{a[d]||(l(d),a[d]=f,a.filter(y=>y).length===t.length&&(n.onclose?.(a),c=()=>{}))};const h=d=>{if(n.alreadyHaveEvent?.(d))return!0;const f=r.has(d);return r.add(d),f},p=Promise.all(t.map(async({url:d,filters:f},y)=>{if(this.allowConnectingToRelay?.(d,["read",f])===!1){c(y,"connection skipped by allowConnectingToRelay");return}let w;try{w=await this.ensureRelay(d,{connectionTimeout:this.maxWaitForConnection<(n.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n.abort})}catch(O){this.onRelayConnectionFailure?.(d),c(y,O?.message||String(O));return}this.onRelayConnectionSuccess?.(d);let A=w.subscribe(f,{...n,oneose:()=>l(y),onclose:O=>{O.startsWith("auth-required: ")&&n.onauth?w.auth(n.onauth).then(()=>{w.subscribe(f,{...n,oneose:()=>l(y),onclose:V=>{c(y,V)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort})}).catch(V=>{c(y,`auth was required and attempted, but failed with: ${V}`)}):c(y,O)},alreadyHaveEvent:h,eoseTimeout:n.maxWait,abort:n.abort});i.push(A)}));return{async close(d){await p,i.forEach(f=>{f.close(d)})}}}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}},Ct;try{Ct=WebSocket}catch{}var di=class extends li{constructor(e){super({verifyEvent:Jr,websocketImplementation:Ct,maxWaitForConnection:3e3,...e})}},le=Symbol("verified"),ci=e=>e instanceof Object;function ui(e){if(!ci(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 pi=new TextEncoder,mi=class{generateSecretKey(){return Y.utils.randomSecretKey()}getPublicKey(e){return C(Y.getPublicKey(e))}finalizeEvent(e,n){const s=e;return s.pubkey=C(Y.getPublicKey(n)),s.id=sn(s),s.sig=C(Y.sign(Z(sn(s)),n)),s[le]=!0,s}verifyEvent(e){if(typeof e[le]=="boolean")return e[le];try{const n=sn(e);if(n!==e.id)return e[le]=!1,!1;const s=Y.verify(Z(e.sig),Z(n),Z(e.pubkey));return e[le]=s,s}catch{return e[le]=!1,!1}}};function fi(e){if(!ui(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 sn(e){let n=He(pi.encode(fi(e)));return C(n)}var Ke=new mi;Ke.generateSecretKey;Ke.getPublicKey;Ke.finalizeEvent;var gi=Ke.verifyEvent;const hi=8e3;function yi(e){return typeof e=="number"&&hn.includes(e)}function bi(e){try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function vi(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 wi(e){const n=dr(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=vi(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&&!yi(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?[...hn]:[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 Ei(e){return{id:e.id,pubkey:e.pubkey,kind:e.kind,tags:e.tags,content:e.content}}async function Si(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 Ri(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 Ti(e,n){const s=e.endsWith("/")?e:`${e}/`;return new URL(n,s).href}async function _i(e,n=fetch){const s=ze(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=Ri(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=Ti(o,t);try{const a=await n(l,{mode:"cors"});if(!a.ok){i.push(`${l}: HTTP ${a.status}`);continue}const c=new Uint8Array(await a.arrayBuffer()),h=await Si(c);if(h!==t){i.push(`${l}: sha256 ${h} did not match manifest ${t}`);continue}return new TextDecoder().decode(c)}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 ki(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 Ii(e,n){const s=wi(e),t=!n.pool,r=n.pool??new di;try{const i=await r.get(s.relays,{...s.filter},{maxWait:n.maxRelayWaitMs??hi});if(!i)throw new Error("No matching napplet manifest event was found on the pointer relay hints");if(!gi(i))throw new Error("Resolved manifest event signature is invalid");const o=Ei(i),l=ze(o);if(!l.ok)throw new Error(`Resolved event is not a valid NIP-5D napplet manifest: ${l.errors[0]?.message}`);const a=await _i(o,n.fetcher??fetch),c=(n.createObjectUrl??URL.createObjectURL)(new Blob([a],{type:"text/html;charset=utf-8"})),h=()=>(n.revokeObjectUrl??URL.revokeObjectURL)(c);return{source:"nostr",input:e,label:o.id??e,bootUrl:c,html:a,fetched:!0,manifestEvent:o,revoke:h}}finally{t&&r.destroy()}}async function xi(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 bi(s)?ki(s,n.fetcher??fetch):Ii(s,n)}const Mi=`"use strict";
11
11
  var NappletShimPrelude = (() => {
12
12
  var __defProp = Object.defineProperty;
13
13
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -38,6 +38,197 @@ var NappletShimPrelude = (() => {
38
38
 
39
39
  // ../core/dist/index.js
40
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"];
41
+ var NAP_IMPLEMENTATIONS = {
42
+ shell: {
43
+ proposal: { url: "https://github.com/napplet/naps/pull/101", status: "merged", checkedAt: "2026-10-31" },
44
+ maturity: "supported",
45
+ rationale: "Optional readiness and environment binding has focused shim and reference-runtime coverage.",
46
+ evidence: ["packages/nap/src/shell/shim.test.ts"]
47
+ },
48
+ relay: {
49
+ proposal: { url: "https://github.com/napplet/naps/pull/2", status: "in-review", checkedAt: "2026-10-31" },
50
+ maturity: "supported",
51
+ rationale: "Relay reads, publishing, and subscription lifecycle have maintained shim and integration tests; upstream naming remains under review.",
52
+ evidence: ["packages/nap/src/relay/shim.test.ts"],
53
+ implementationReference: { revision: "cb8f8eabb2d09439e9d174cb9eb6ef2caad0eca1", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "RelayEventResult sidecar migration; subsequent changes are not covered." }
54
+ },
55
+ identity: {
56
+ proposal: { url: "https://github.com/napplet/naps/pull/102", status: "merged", checkedAt: "2026-10-31" },
57
+ maturity: "supported",
58
+ rationale: "Read-only identity queries and updates have focused binding and reference-runtime coverage.",
59
+ evidence: ["packages/nap/src/identity/shim.test.ts"]
60
+ },
61
+ storage: {
62
+ proposal: { url: "https://github.com/napplet/naps/pull/3", status: "in-review", checkedAt: "2026-10-31" },
63
+ maturity: "supported",
64
+ rationale: "Key-value binding has focused request/result tests and tutorial usage; host storage isolation remains the host responsibility.",
65
+ evidence: ["packages/nap/src/storage/shim.test.ts"]
66
+ },
67
+ inc: {
68
+ proposal: { url: "https://github.com/napplet/naps/pull/104", status: "merged", checkedAt: "2026-10-31" },
69
+ maturity: "supported",
70
+ rationale: "Topic and channel bindings have compatibility tests and authenticated-endpoint reference-runtime coverage.",
71
+ evidence: ["packages/nap/src/inc/shim.ts", "packages/conformance-cli/src/browser.test.ts"]
72
+ },
73
+ theme: {
74
+ proposal: { url: "https://github.com/napplet/naps/pull/103", status: "merged", checkedAt: "2026-10-31" },
75
+ maturity: "supported",
76
+ rationale: "Theme queries and pushed updates have focused binding and opaque-iframe integration coverage.",
77
+ evidence: ["packages/nap/src/theme/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
78
+ },
79
+ keys: {
80
+ proposal: { url: "https://github.com/napplet/naps/pull/9", status: "in-review", checkedAt: "2026-10-31" },
81
+ maturity: "experimental",
82
+ rationale: "Keyboard binding ships, but dedicated domain regression coverage is limited; retain explicit evaluation opt-in.",
83
+ evidence: ["packages/nap/src/keys/shim.ts"]
84
+ },
85
+ media: {
86
+ proposal: { url: "https://github.com/napplet/naps/pull/10", status: "in-review", checkedAt: "2026-10-31" },
87
+ maturity: "supported",
88
+ rationale: "Session creation and playback binding have focused regression coverage; proposed torrent playback amendments are not implied.",
89
+ evidence: ["packages/nap/src/media/shim.test.ts"]
90
+ },
91
+ notify: {
92
+ proposal: { url: "https://github.com/napplet/naps/pull/11", status: "in-review", checkedAt: "2026-10-31" },
93
+ maturity: "experimental",
94
+ rationale: "Notification binding ships with limited dedicated domain regression evidence; broader host integration confidence is unverified.",
95
+ evidence: ["packages/nap/src/notify/shim.ts"]
96
+ },
97
+ config: {
98
+ proposal: { url: "https://github.com/napplet/naps/pull/14", status: "draft", checkedAt: "2026-10-31" },
99
+ maturity: "exploratory",
100
+ rationale: "Configuration binding is tested, but the upstream draft is marked MAY DEFER; use for design exploration.",
101
+ evidence: ["packages/nap/src/config/shim.test.ts"]
102
+ },
103
+ resource: {
104
+ proposal: { url: "https://github.com/napplet/naps/pull/80", status: "in-review", checkedAt: "2026-10-31" },
105
+ maturity: "supported",
106
+ rationale: "Resource fetching has focused shim and type tests; the reverted merge and reopened proposal do not change that implementation assessment.",
107
+ evidence: ["packages/nap/src/resource/shim.test.ts"],
108
+ implementationReference: { revision: "8e75eadf317d7fe809415e4755cd48f63cfb63f3", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "Shared ResourceSidecarEntry types during the sidecar migration; subsequent resource changes are not covered." }
109
+ },
110
+ cvm: {
111
+ proposal: { url: "https://github.com/napplet/naps/pull/31", status: "in-review", checkedAt: "2026-10-31" },
112
+ maturity: "experimental",
113
+ rationale: "Session and registry bindings are tested; upstream explicitly marks the contract NEEDS WORK.",
114
+ evidence: ["packages/nap/src/cvm/shim.test.ts"]
115
+ },
116
+ outbox: {
117
+ proposal: { url: "https://github.com/napplet/naps/pull/32", status: "in-review", checkedAt: "2026-10-31" },
118
+ maturity: "supported",
119
+ rationale: "Routing and subscription bindings have focused tests and an integration regression for structured-clone boundaries.",
120
+ evidence: ["packages/nap/src/outbox/shim.test.ts", "packages/nap/src/boundary-integration.test.ts"],
121
+ implementationReference: { revision: "57db924bac022cc14c67d9fca1a4d92cf1bd4725", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "RelayEventResult and stream lifecycle migration; subsequent changes are not covered." }
122
+ },
123
+ upload: {
124
+ proposal: { url: "https://github.com/napplet/naps/pull/33", status: "in-review", checkedAt: "2026-10-31" },
125
+ maturity: "supported",
126
+ rationale: "Upload binding has focused tests for request/result behavior; host rail support remains runtime-specific.",
127
+ evidence: ["packages/nap/src/upload/shim.test.ts"]
128
+ },
129
+ intent: {
130
+ proposal: { url: "https://github.com/napplet/naps/pull/91", status: "merged", checkedAt: "2026-10-31" },
131
+ maturity: "supported",
132
+ rationale: "Convention normalization and dispatch have focused binding and reference-runtime integration tests.",
133
+ evidence: ["packages/nap/src/intent/shim.test.ts"]
134
+ },
135
+ ble: {
136
+ proposal: { url: "https://github.com/napplet/naps/pull/62", status: "in-review", checkedAt: "2026-10-31" },
137
+ maturity: "experimental",
138
+ rationale: "GATT binding has unit coverage; real-device behavior across host backends is not established by these tests.",
139
+ evidence: ["packages/nap/src/ble/shim.test.ts"]
140
+ },
141
+ webrtc: {
142
+ proposal: { url: "https://github.com/napplet/naps/pull/59", status: "in-review", checkedAt: "2026-10-31" },
143
+ maturity: "experimental",
144
+ rationale: "Signaling and session binding have unit coverage; interoperable live peer sessions remain unverified here.",
145
+ evidence: ["packages/nap/src/webrtc/shim.test.ts"]
146
+ },
147
+ link: {
148
+ proposal: { url: "https://github.com/napplet/naps/pull/53", status: "in-review", checkedAt: "2026-10-31" },
149
+ maturity: "supported",
150
+ rationale: "The small link-opening binding has focused regression coverage; navigation authorization stays with the host.",
151
+ evidence: ["packages/nap/src/link/shim.test.ts"]
152
+ },
153
+ count: {
154
+ proposal: { url: "https://github.com/napplet/naps/pull/69", status: "in-review", checkedAt: "2026-10-31" },
155
+ maturity: "experimental",
156
+ rationale: "Count binding is tested, but accuracy and aggregation across real relay backends remain outside that evidence.",
157
+ evidence: ["packages/nap/src/count/shim.test.ts"]
158
+ },
159
+ lists: {
160
+ proposal: { url: "https://github.com/napplet/naps/pull/68", status: "in-review", checkedAt: "2026-10-31" },
161
+ maturity: "experimental",
162
+ rationale: "List mutation binding is tested; concurrent real-host mutation behavior is not established by binding tests.",
163
+ evidence: ["packages/nap/src/lists/shim.test.ts"]
164
+ },
165
+ serial: {
166
+ proposal: { url: "https://github.com/napplet/naps/pull/61", status: "in-review", checkedAt: "2026-10-31" },
167
+ maturity: "experimental",
168
+ rationale: "Serial binding has unit coverage; device and native-host integration evidence is limited.",
169
+ evidence: ["packages/nap/src/serial/shim.test.ts"]
170
+ },
171
+ fs: {
172
+ proposal: { url: "https://github.com/napplet/naps/pull/88", status: "in-review", checkedAt: "2026-10-31" },
173
+ maturity: "experimental",
174
+ rationale: "Filesystem binding has MVP coverage; portability and authorization across storage backends remain under evaluation.",
175
+ evidence: ["packages/nap/src/fs/shim.test.ts"]
176
+ },
177
+ common: {
178
+ proposal: { url: "https://github.com/napplet/naps/pull/67", status: "in-review", checkedAt: "2026-10-31" },
179
+ maturity: "experimental",
180
+ rationale: "Social action binding is tested; broader host integration and evolving action semantics warrant explicit opt-in.",
181
+ evidence: ["packages/nap/src/common/shim.test.ts"]
182
+ },
183
+ dm: {
184
+ proposal: { url: "https://github.com/napplet/naps/pull/74", status: "draft", checkedAt: "2026-10-31" },
185
+ maturity: "experimental",
186
+ rationale: "Direct-message binding has shim and type coverage; transport interoperability is not established by those tests.",
187
+ evidence: ["packages/nap/src/dm/shim.test.ts"]
188
+ },
189
+ gamepad: {
190
+ proposal: { url: "https://github.com/napplet/naps/pull/130", status: "in-review", checkedAt: "2026-10-31" },
191
+ maturity: "supported",
192
+ rationale: "Cross-repository delivery includes binding, security, runtime, and conformance verification; the reopened proposal is still subject to change.",
193
+ evidence: ["packages/nap/src/gamepad/shim.test.ts", ".planning/phases/163-nap-gamepad-across-repositories/163-VERIFICATION.md"],
194
+ implementationReference: { revision: "0b28f77e3dfa0f07dd7c0f9d61a7090ee99f3a5e", evidence: ".planning/phases/163-nap-gamepad-across-repositories/163-SECURITY.md", scope: "Phase 163 binding, runtime isolation, and conformance verification." }
195
+ },
196
+ llm: {
197
+ proposal: { url: "https://github.com/napplet/naps/pull/134", status: "draft", checkedAt: "2026-10-31" },
198
+ maturity: "exploratory",
199
+ rationale: "Early published draft has binding and mock-runtime tests; provider behavior and API design remain exploratory.",
200
+ evidence: ["packages/nap/src/llm/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
201
+ }
202
+ };
203
+ for (const entry of Object.values(NAP_IMPLEMENTATIONS)) {
204
+ Object.freeze(entry.proposal);
205
+ Object.freeze(entry.evidence);
206
+ if (entry.implementationReference) Object.freeze(entry.implementationReference);
207
+ Object.freeze(entry);
208
+ }
209
+ Object.freeze(NAP_IMPLEMENTATIONS);
210
+ function getNapImplementation(domain) {
211
+ return Object.hasOwn(NAP_IMPLEMENTATIONS, domain) ? NAP_IMPLEMENTATIONS[domain] : void 0;
212
+ }
213
+ function selectNapDomains(options) {
214
+ const allowed = new Set(options.allowedMaturities ?? ["supported"]);
215
+ const optIn = new Set(options.optIn ?? []);
216
+ const domains = [];
217
+ const excluded = [];
218
+ for (const domain of new Set(options.candidates)) {
219
+ const metadata = getNapImplementation(domain);
220
+ if (!metadata) {
221
+ excluded.push({ domain, reason: "unknown-domain" });
222
+ } else if (!metadata.maturity || !["supported", "experimental", "exploratory"].includes(metadata.maturity)) {
223
+ excluded.push({ domain, reason: "unclassified" });
224
+ } else if (allowed.has(metadata.maturity) || optIn.has(domain)) {
225
+ domains.push(domain);
226
+ } else {
227
+ excluded.push({ domain, reason: "maturity-not-allowed", maturity: metadata.maturity });
228
+ }
229
+ }
230
+ return { domains, excluded };
231
+ }
41
232
  function createDispatch() {
42
233
  const handlers3 = /* @__PURE__ */ new Map();
43
234
  function registerNap2(domain, handler) {
@@ -5397,6 +5588,9 @@ var NappletShimPrelude = (() => {
5397
5588
  if (!options || !Array.isArray(options.domains)) {
5398
5589
  throw new TypeError("Napplet runtime prelude requires an explicit domains array");
5399
5590
  }
5591
+ if (options.maturity) {
5592
+ return [...selectNapDomains({ ...options.maturity, candidates: options.domains }).domains];
5593
+ }
5400
5594
  return options.domains.filter((domain) => KNOWN_DOMAINS.has(domain));
5401
5595
  }
5402
5596
  function installNappletRuntimePrelude(options) {
@@ -5421,9 +5615,9 @@ var NappletShimPrelude = (() => {
5421
5615
  @scure/base/index.js:
5422
5616
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
5423
5617
  */
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=`
5618
+ //# sourceMappingURL=prelude.global.js.map`,Ui=/\bwindow\s*\.\s*nostr\b|\bglobalThis\s*\.\s*nostr\b/,Ai="/__conformance__/events",fn=new URLSearchParams(location.search),Nt=fn.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 Pi(){return se.innerHTML=`
5425
5619
  <header class="masthead">
5426
- <h1>napplet conformance ${Ct?'<span class="live-badge" id="live-badge">● live</span>':""}</h1>
5620
+ <h1>napplet conformance ${Nt?'<span class="live-badge" id="live-badge">● live</span>':""}</h1>
5427
5621
  <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>
5428
5622
  </header>
5429
5623
  <form id="run-form" class="runbar">
@@ -5433,22 +5627,22 @@ var NappletShimPrelude = (() => {
5433
5627
  </form>
5434
5628
  <p id="status" class="status" role="status"></p>
5435
5629
  <section id="output" class="output"></section>
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`
5630
+ `,{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 N=Pi();let Re="",gn=0;function Ae(e,n="info"){N.status.textContent=e,N.status.dataset.kind=n}function rn(e){return String(e).padStart(2,"0")}function ji(e){const n=new Date(e);return`${rn(n.getHours())}:${rn(n.getMinutes())}:${rn(n.getSeconds())}`}function Oi(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 c=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>${c}${h}</li>`}).join("");return`<div class="area"><h3>${te(o)}</h3><ul>${l}</ul></div>`}).join(""),r=e.summary,i=gn>1?`<span class="run-stamp">run #${gn} · ${ji(e.finishedAt)}</span>`:"";return`
5437
5631
  <div class="verdict ${n}">
5438
5632
  <span class="result">${e.ok?"CONFORMANT":"NON-CONFORMANT"}</span>
5439
5633
  <span class="counts">${r.passed} passed · ${r.failed} failed · ${r.skipped} skipped${r.warnings?` · ${r.warnings} warning(s)`:""}</span>
5440
5634
  ${i}
5441
5635
  </div>
5442
5636
  <div class="checks">${t}</div>
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`
5637
+ `}function qi(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 Ci(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=ze(s);return`
5444
5638
  <table class="manifest">
5445
- ${zs(s,t).map(([r,i])=>n(r,i)).join("")}
5639
+ ${Ys(s,t).map(([r,i])=>n(r,i)).join("")}
5446
5640
  </table>
5447
5641
  ${t.errors.length?`<div class="errs">${t.errors.map(r=>te(`${r.code}: ${r.message}`)).join("<br>")}</div>`:""}
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)}
5642
+ `}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 Ni(e,n,s){N.output.innerHTML=`
5643
+ ${Oi(e)}
5450
5644
  <div class="panels">
5451
- <section class="panel"><h2>Emitted envelopes (${n.length})</h2>${Ai(n)}</section>
5452
- <section class="panel"><h2>Manifest</h2>${ji(s)}</section>
5645
+ <section class="panel"><h2>Emitted envelopes (${n.length})</h2>${qi(n)}</section>
5646
+ <section class="panel"><h2>Manifest</h2>${Ci(s)}</section>
5453
5647
  </div>
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));
5648
+ `}async function Ye(e){Re=e,N.runButton.disabled=!0,N.rerunButton.disabled=!0;let n=null;try{Ae(`Resolving ${e} …`),n=await xi(e);const s=Ui.test(n.html)?["window.nostr"]:[];Ae("Booting napplet in a sandboxed iframe …");const t=await Fs({url:n.bootUrl,html:n.html,readyTimeoutMs:5e3,settleMs:800,runDegraded:!0,runtimePreludeSource:Mi}),r=Cs({manifestHtml:n.html,manifestEvent:n.manifestEvent,boot:t,forbiddenGlobals:s}),i=Ks(r);gn+=1,Ae(i.ok?"Done — conformant.":"Done — non-conformant.",i.ok?"info":"error"),Ni(i,t.emitted,n),N.rerunButton.hidden=!1}catch(s){Ae(`Error: ${s instanceof Error?s.message:String(s)}`,"error")}finally{n?.revoke?.(),N.runButton.disabled=!1,N.rerunButton.disabled=!1}}function Hi(){if(!Nt||typeof EventSource>"u")return;let e=!1;const n=new EventSource(Ai);n.addEventListener("rerun",()=>{!Re||e||(e=!0,setTimeout(()=>{e=!1,Ye(Re)},50))}),n.addEventListener("open",()=>{N.liveBadge&&(N.liveBadge.dataset.state="connected")}),n.addEventListener("error",()=>{N.liveBadge&&(N.liveBadge.dataset.state="disconnected")})}N.runButton.parentElement.addEventListener("submit",e=>{e.preventDefault();const n=N.targetInput.value.trim();if(n){const s=new URL(location.href);s.searchParams.set("target",n),s.searchParams.delete("url"),history.replaceState(null,"",s),Ye(n)}});N.rerunButton.addEventListener("click",()=>{Re&&Ye(Re)});Hi();const on=fn.get("target")??fn.get("url");on&&(N.targetInput.value=on,Ye(on));