window.nostr.js 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.cjs ADDED
@@ -0,0 +1,157 @@
1
+ module.exports = {
2
+ root: true,
3
+ extends: [
4
+ 'eslint:recommended',
5
+ 'plugin:@typescript-eslint/recommended',
6
+ 'plugin:svelte/recommended',
7
+ 'prettier'
8
+ ],
9
+ parser: '@typescript-eslint/parser',
10
+ plugins: ['@typescript-eslint'],
11
+ parserOptions: {
12
+ sourceType: 'module',
13
+ ecmaVersion: 2020,
14
+ extraFileExtensions: ['.svelte']
15
+ },
16
+ env: {
17
+ browser: true,
18
+ es2017: true,
19
+ node: true
20
+ },
21
+ overrides: [
22
+ {
23
+ files: ['*.svelte'],
24
+ parser: 'svelte-eslint-parser',
25
+ parserOptions: {
26
+ parser: '@typescript-eslint/parser'
27
+ }
28
+ }
29
+ ],
30
+ rules: {
31
+ '@typescript-eslint/no-explicit-any': 0,
32
+ '@typescript-eslint/no-unused-vars': [
33
+ 'error',
34
+ {
35
+ argsIgnorePattern: '^_',
36
+ destructuredArrayIgnorePattern: '^_'
37
+ }
38
+ ],
39
+ 'no-async-promise-executor': 0,
40
+ 'accessor-pairs': 2,
41
+ 'arrow-spacing': [2, {before: true, after: true}],
42
+ 'block-spacing': [2, 'always'],
43
+ 'brace-style': [2, '1tbs', {allowSingleLine: true}],
44
+ 'comma-dangle': 0,
45
+ 'comma-spacing': [2, {before: false, after: true}],
46
+ 'comma-style': [2, 'last'],
47
+ 'constructor-super': 2,
48
+ curly: [0, 'multi-line'],
49
+ 'dot-location': [2, 'property'],
50
+ 'eol-last': 2,
51
+ eqeqeq: [2, 'allow-null'],
52
+ 'generator-star-spacing': [2, {before: true, after: true}],
53
+ 'handle-callback-err': [2, '^(err|error)$'],
54
+ indent: 0,
55
+ 'jsx-quotes': [2, 'prefer-double'],
56
+ 'key-spacing': [2, {beforeColon: false, afterColon: true}],
57
+ 'keyword-spacing': [2, {before: true, after: true}],
58
+ 'new-cap': 0,
59
+ 'new-parens': 0,
60
+ 'no-array-constructor': 2,
61
+ 'no-caller': 2,
62
+ 'no-class-assign': 2,
63
+ 'no-cond-assign': 2,
64
+ 'no-const-assign': 2,
65
+ 'no-control-regex': 0,
66
+ 'no-debugger': 0,
67
+ 'no-delete-var': 2,
68
+ 'no-dupe-args': 2,
69
+ 'no-dupe-class-members': 2,
70
+ 'no-dupe-keys': 2,
71
+ 'no-duplicate-case': 2,
72
+ 'no-empty-character-class': 2,
73
+ 'no-empty-pattern': 2,
74
+ 'no-eval': 0,
75
+ 'no-ex-assign': 2,
76
+ 'no-extend-native': 2,
77
+ 'no-extra-bind': 2,
78
+ 'no-extra-boolean-cast': 2,
79
+ 'no-extra-parens': [2, 'functions'],
80
+ 'no-fallthrough': 2,
81
+ 'no-floating-decimal': 2,
82
+ 'no-func-assign': 2,
83
+ 'no-implied-eval': 2,
84
+ 'no-inner-declarations': [0, 'functions'],
85
+ 'no-invalid-regexp': 2,
86
+ 'no-irregular-whitespace': 2,
87
+ 'no-iterator': 2,
88
+ 'no-label-var': 2,
89
+ 'no-labels': [2, {allowLoop: false, allowSwitch: false}],
90
+ 'no-lone-blocks': 2,
91
+ 'no-mixed-spaces-and-tabs': 2,
92
+ 'no-multi-spaces': 2,
93
+ 'no-multi-str': 2,
94
+ 'no-multiple-empty-lines': [2, {max: 2}],
95
+ 'no-native-reassign': 2,
96
+ 'no-negated-in-lhs': 2,
97
+ 'no-new': 0,
98
+ 'no-new-func': 2,
99
+ 'no-new-object': 2,
100
+ 'no-new-require': 2,
101
+ 'no-new-symbol': 2,
102
+ 'no-new-wrappers': 2,
103
+ 'no-obj-calls': 2,
104
+ 'no-octal': 2,
105
+ 'no-octal-escape': 2,
106
+ 'no-path-concat': 0,
107
+ 'no-proto': 2,
108
+ 'no-redeclare': 2,
109
+ 'no-regex-spaces': 2,
110
+ 'no-return-assign': 0,
111
+ 'no-self-assign': 2,
112
+ 'no-self-compare': 2,
113
+ 'no-sequences': 2,
114
+ 'no-shadow-restricted-names': 2,
115
+ 'no-spaced-func': 2,
116
+ 'no-sparse-arrays': 2,
117
+ 'no-this-before-super': 2,
118
+ 'no-throw-literal': 2,
119
+ 'no-trailing-spaces': 2,
120
+ 'no-undef': 2,
121
+ 'no-undef-init': 2,
122
+ 'no-unexpected-multiline': 2,
123
+ 'no-unneeded-ternary': [2, {defaultAssignment: false}],
124
+ 'no-unreachable': 2,
125
+ 'no-unused-vars': [
126
+ 2,
127
+ {vars: 'local', args: 'none', varsIgnorePattern: '^_'}
128
+ ],
129
+ 'no-useless-call': 2,
130
+ 'no-useless-constructor': 2,
131
+ 'no-with': 2,
132
+ 'one-var': [0, {initialized: 'never'}],
133
+ 'operator-linebreak': [
134
+ 2,
135
+ 'after',
136
+ {overrides: {'?': 'before', ':': 'before'}}
137
+ ],
138
+ 'padded-blocks': [2, 'never'],
139
+ quotes: [2, 'single', {avoidEscape: true, allowTemplateLiterals: true}],
140
+ semi: [2, 'never'],
141
+ 'semi-spacing': [2, {before: false, after: true}],
142
+ 'space-before-blocks': [2, 'always'],
143
+ 'space-before-function-paren': 0,
144
+ 'space-in-parens': [2, 'never'],
145
+ 'space-infix-ops': 2,
146
+ 'space-unary-ops': [2, {words: true, nonwords: false}],
147
+ 'spaced-comment': 0,
148
+ 'template-curly-spacing': [2, 'never'],
149
+ 'use-isnan': 2,
150
+ 'valid-typeof': 2,
151
+ 'wrap-iife': [2, 'any'],
152
+ 'yield-star-spacing': [2, 'both'],
153
+ yoda: 0,
154
+ 'no-unsafe-optional-chaning': 0,
155
+ 'generator-star-spacing': 0
156
+ }
157
+ }
@@ -0,0 +1,25 @@
1
+ name: release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - '*'
7
+
8
+ permissions:
9
+ contents: write
10
+
11
+ jobs:
12
+ release-and-upload:
13
+ name: release
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-node@v3
18
+ with:
19
+ node-version: 21
20
+ - run: npm install
21
+ - uses: extractions/setup-just@v1
22
+ - run: just build
23
+ - uses: ncipollo/release-action@v1
24
+ with:
25
+ artifacts: dist/window.nostr.js
@@ -0,0 +1,16 @@
1
+ semi: false
2
+ arrowParens: avoid
3
+ insertPragma: false
4
+ printWidth: 80
5
+ proseWrap: preserve
6
+ singleQuote: true
7
+ trailingComma: none
8
+ useTabs: false
9
+ bracketSpacing: false
10
+ plugins:
11
+ - prettier-plugin-tailwindcss
12
+ - prettier-plugin-svelte
13
+ overrides:
14
+ - files: '*.svelte'
15
+ options:
16
+ parser: svelte
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # window.nostr.js
2
+
3
+ a small `<script>` you can drop in any page that already uses [NIP-07](https://nips.nostr.com/7) and make it also work with [NIP-46](https://nips.nostr.com/46) automatically when the user doesn't have an extension installed.
@@ -0,0 +1,38 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>window.nostr.js demo</title>
7
+ </head>
8
+ <body>
9
+ <main>
10
+ <h1>Lorem ipsum dolor sit amet</h1>
11
+ <p>
12
+ Aptent, quis penatibus dictumst! Varius neque maecenas sodales libero
13
+ facilisis, faucibus ut elit morbi phasellus proin. Vestibulum odio
14
+ pellentesque vehicula, non neque! Aliquam maecenas quis facilisis non.
15
+ Porta aenean integer aenean ultrices facilisis sagittis enim fermentum
16
+ commodo nisi condimentum vestibulum. Vivamus leo id ligula ullamcorper
17
+ cubilia scelerisque sodales rhoncus orci maecenas cubilia. Netus
18
+ facilisis neque iaculis euismod per iaculis habitant sem aliquam. Tellus
19
+ sapien fames metus hac sagittis?
20
+ </p>
21
+ <p>
22
+ Pellentesque habitant morbi tristique senectus et netus et malesuada
23
+ fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
24
+ ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam
25
+ egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend
26
+ leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum
27
+ erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean
28
+ fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
29
+ sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar
30
+ facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor
31
+ neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat
32
+ volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis
33
+ luctus, metus
34
+ </p>
35
+ </main>
36
+ <script src="../dist/window.nostr.js"></script>
37
+ </body>
38
+ </html>
@@ -0,0 +1,65 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>dev</title>
7
+ <script type="module" crossorigin src="/assets/index-D6-w3v1d.js"></script>
8
+ </head>
9
+ <body
10
+ style="
11
+ margin: 0;
12
+ padding: 1em 3em;
13
+ background-color: #333;
14
+ color: white;
15
+ font-size: 18px;
16
+ "
17
+ >
18
+ <main>
19
+ <h1>App Title</h1>
20
+ <p>
21
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et ex dui.
22
+ Donec eu dui sed massa auctor rhoncus. Nunc mollis, metus nec
23
+ sollicitudin ultricies, nibh diam accumsan eros, sit amet efficitur
24
+ lectus dui sit amet dolor. Donec commodo velit id nibh pharetra, at
25
+ fermentum velit mollis. Duis eu libero varius, ullamcorper tortor id,
26
+ pharetra neque. Nulla a pretium est. Sed imperdiet ultrices volutpat.
27
+ Sed quam arcu, aliquam eget diam et, pretium sagittis risus. Donec
28
+ finibus sapien id orci sollicitudin gravida. Vivamus et dui faucibus,
29
+ blandit nisl vitae, consectetur risus. Pellentesque vehicula dignissim
30
+ maximus. Donec pellentesque, sapien id sollicitudin bibendum, est magna
31
+ pretium ex, nec dignissim quam ante at mauris. Quisque sed scelerisque
32
+ nulla. Vestibulum lobortis orci vitae gravida posuere. Integer sed sem
33
+ diam. Maecenas bibendum ligula non metus faucibus, vitae pellentesque
34
+ nisi condimentum. Suspendisse vehicula ullamcorper nisi, ut rutrum dolor
35
+ mollis sit amet. Cras sit amet mi sit amet eros convallis pulvinar.
36
+ Donec condimentum condimentum tincidunt.
37
+ </p>
38
+
39
+ <p>
40
+ Suspendisse eu ipsum vel lorem congue mattis in at neque. Phasellus nec
41
+ felis sit amet nibh bibendum tristique a quis urna. Pellentesque laoreet
42
+ porta libero eget pellentesque. Praesent tempor, nisi et efficitur
43
+ cursus, leo nunc ullamcorper ante, quis eleifend velit justo sed enim.
44
+ Maecenas laoreet dictum lorem rhoncus tempus. Integer ipsum augue,
45
+ sagittis a facilisis et, mollis ut ipsum. Proin elementum consectetur
46
+ tincidunt.
47
+ </p>
48
+
49
+ <p>
50
+ Mauris nec mi et quam semper volutpat. Morbi suscipit felis lectus, in
51
+ ornare purus pretium in. Maecenas et ex metus. Ut aliquam, felis vel
52
+ mollis dapibus, tellus velit blandit dui, eu hendrerit tellus magna at
53
+ eros. Donec scelerisque hendrerit auctor. Aenean aliquet sapien
54
+ elementum dui sagittis eleifend. Donec hendrerit odio et dui lacinia
55
+ aliquet. Morbi auctor ultrices dui fringilla elementum. Curabitur
56
+ scelerisque lorem vitae placerat vulputate. Donec vestibulum urna sem,
57
+ at sodales ligula laoreet id. Etiam vehicula, lorem id tincidunt
58
+ sodales, sem odio vehicula ex, vel condimentum quam augue id augue.
59
+ Integer a varius nunc. Mauris rhoncus leo sed facilisis bibendum. Nullam
60
+ consectetur pellentesque vestibulum. Cras hendrerit feugiat orci, in
61
+ molestie risus rutrum ut. Proin dictum nunc at rutrum vehicula.
62
+ </p>
63
+ </main>
64
+ </body>
65
+ </html>
@@ -0,0 +1,3 @@
1
+ var ui=Object.defineProperty;var fi=(le,j,ue)=>j in le?ui(le,j,{enumerable:!0,configurable:!0,writable:!0,value:ue}):le[j]=ue;var b=(le,j,ue)=>(fi(le,typeof j!="symbol"?j+"":j,ue),ue);(function(){"use strict";var le=document.createElement("style");le.textContent=`.tw-fixed{position:fixed}.tw-right-6{right:1.5rem}.tw-top-6{top:1.5rem}.tw-mx-2{margin-left:.5rem;margin-right:.5rem}.tw-my-2{margin-top:.5rem;margin-bottom:.5rem}.tw-mb-1{margin-bottom:.25rem}.tw-mt-4{margin-top:1rem}.tw-mt-6{margin-top:1.5rem}.tw-box-border{box-sizing:border-box}.tw-block{display:block}.tw-flex{display:flex}.tw-w-80{width:20rem}.tw-w-full{width:100%}.tw-cursor-pointer{cursor:pointer}.tw-break-all{word-break:break-all}.tw-rounded{border-radius:.25rem}.tw-rounded-md{border-radius:.375rem}.tw-border-0{border-width:0px}.tw-border-none{border-style:none}.tw-bg-cyan-700{--tw-bg-opacity: 1;background-color:rgb(14 116 144 / var(--tw-bg-opacity))}.tw-bg-cyan-900{--tw-bg-opacity: 1;background-color:rgb(22 78 99 / var(--tw-bg-opacity))}.tw-bg-transparent{background-color:transparent}.tw-px-2{padding-left:.5rem;padding-right:.5rem}.tw-px-4{padding-left:1rem;padding-right:1rem}.tw-px-6{padding-left:1.5rem;padding-right:1.5rem}.tw-py-1{padding-top:.25rem;padding-bottom:.25rem}.tw-py-2{padding-top:.5rem;padding-bottom:.5rem}.tw-py-6{padding-top:1.5rem;padding-bottom:1.5rem}.tw-text-center{text-align:center}.tw-font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.tw-text-2xl{font-size:1.5rem;line-height:2rem}.tw-text-lg{font-size:1.125rem;line-height:1.75rem}.tw-text-sm{font-size:.875rem;line-height:1.25rem}.tw-text-xs{font-size:.75rem;line-height:1rem}.tw-leading-3{line-height:.75rem}.tw-text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.tw-underline{text-decoration-line:underline}.tw-no-underline{text-decoration-line:none}.tw-shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.tw-outline-none{outline:2px solid transparent;outline-offset:2px}.tw-transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.hover\\:tw-bg-cyan-800:hover{--tw-bg-opacity: 1;background-color:rgb(21 94 117 / var(--tw-bg-opacity))}.hover\\:tw-bg-cyan-950:hover{--tw-bg-opacity: 1;background-color:rgb(8 51 68 / var(--tw-bg-opacity))}.hover\\:tw-underline:hover{text-decoration-line:underline}
2
+ `,document.head.appendChild(le);function j(){}function ue(t){return t()}function Zt(){return Object.create(null)}function Be(t){t.forEach(ue)}function Jt(t){return typeof t=="function"}function ar(t,e){return t!=t?e==e:t!==e||t&&typeof t=="object"||typeof t=="function"}function lr(t){return Object.keys(t).length===0}const ur=typeof window<"u"?window:typeof globalThis<"u"?globalThis:global;function M(t,e){t.appendChild(e)}function H(t,e,n){t.insertBefore(e,n||null)}function U(t){t.parentNode&&t.parentNode.removeChild(t)}function fr(t,e){for(let n=0;n<t.length;n+=1)t[n]&&t[n].d(e)}function P(t){return document.createElement(t)}function $e(t){return document.createTextNode(t)}function se(){return $e(" ")}function Ee(t,e,n,r){return t.addEventListener(e,n,r),()=>t.removeEventListener(e,n,r)}function T(t,e,n){n==null?t.removeAttribute(e):t.getAttribute(e)!==n&&t.setAttribute(e,n)}function dr(t){return Array.from(t.childNodes)}function Yt(t,e){e=""+e,t.data!==e&&(t.data=e)}function Qt(t,e){t.value=e??""}function Xt(t,e,n){for(let r=0;r<t.options.length;r+=1){const s=t.options[r];if(s.__value===e){s.selected=!0;return}}(!n||e!==void 0)&&(t.selectedIndex=-1)}function hr(t){const e=t.querySelector(":checked");return e&&e.__value}function en(t,e,n){t.classList.toggle(e,!!n)}let Me;function Ke(t){Me=t}function wr(){if(!Me)throw new Error("Function called outside component initialization");return Me}function pr(t){wr().$$.on_mount.push(t)}const Oe=[],Je=[];let Ie=[];const tn=[],yr=Promise.resolve();let dt=!1;function gr(){dt||(dt=!0,yr.then(nn))}function Ye(t){Ie.push(t)}const ht=new Set;let Te=0;function nn(){if(Te!==0)return;const t=Me;do{try{for(;Te<Oe.length;){const e=Oe[Te];Te++,Ke(e),br(e.$$)}}catch(e){throw Oe.length=0,Te=0,e}for(Ke(null),Oe.length=0,Te=0;Je.length;)Je.pop()();for(let e=0;e<Ie.length;e+=1){const n=Ie[e];ht.has(n)||(ht.add(n),n())}Ie.length=0}while(Oe.length);for(;tn.length;)tn.pop()();dt=!1,ht.clear(),Ke(t)}function br(t){if(t.fragment!==null){t.update(),Be(t.before_update);const e=t.dirty;t.dirty=[-1],t.fragment&&t.fragment.p(t.ctx,e),t.after_update.forEach(Ye)}}function mr(t){const e=[],n=[];Ie.forEach(r=>t.indexOf(r)===-1?e.push(r):n.push(r)),n.forEach(r=>r()),Ie=e}const Er=new Set;function xr(t,e){t&&t.i&&(Er.delete(t),t.i(e))}function rn(t){return(t==null?void 0:t.length)!==void 0?t:Array.from(t)}function vr(t,e,n){const{fragment:r,after_update:s}=t.$$;r&&r.m(e,n),Ye(()=>{const o=t.$$.on_mount.map(ue).filter(Jt);t.$$.on_destroy?t.$$.on_destroy.push(...o):Be(o),t.$$.on_mount=[]}),s.forEach(Ye)}function Sr(t,e){const n=t.$$;n.fragment!==null&&(mr(n.after_update),Be(n.on_destroy),n.fragment&&n.fragment.d(e),n.on_destroy=n.fragment=null,n.ctx=[])}function _r(t,e){t.$$.dirty[0]===-1&&(Oe.push(t),gr(),t.$$.dirty.fill(0)),t.$$.dirty[e/31|0]|=1<<e%31}function Ar(t,e,n,r,s,o,i=null,c=[-1]){const a=Me;Ke(t);const u=t.$$={fragment:null,ctx:[],props:o,update:j,not_equal:s,bound:Zt(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(a?a.$$.context:[])),callbacks:Zt(),dirty:c,skip_bound:!1,root:e.target||a.$$.root};i&&i(u.root);let f=!1;if(u.ctx=n?n(t,e.props||{},(l,h,...w)=>{const g=w.length?w[0]:h;return u.ctx&&s(u.ctx[l],u.ctx[l]=g)&&(!u.skip_bound&&u.bound[l]&&u.bound[l](g),f&&_r(t,l)),h}):[],u.update(),f=!0,Be(u.before_update),u.fragment=r?r(u.ctx):!1,e.target){if(e.hydrate){const l=dr(e.target);u.fragment&&u.fragment.l(l),l.forEach(U)}else u.fragment&&u.fragment.c();e.intro&&xr(t.$$.fragment),vr(t,e.target,e.anchor),nn()}Ke(a)}class kr{constructor(){b(this,"$$");b(this,"$$set")}$destroy(){Sr(this,1),this.$destroy=j}$on(e,n){if(!Jt(n))return j;const r=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return r.push(n),()=>{const s=r.indexOf(n);s!==-1&&r.splice(s,1)}}$set(e){this.$$set&&!lr(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Br="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Br);function $r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var wt={exports:{}};function sn(t,e=100,n={}){if(typeof t!="function")throw new TypeError(`Expected the first parameter to be a function, got \`${typeof t}\`.`);if(e<0)throw new RangeError("`wait` must not be negative.");const{immediate:r}=typeof n=="boolean"?{immediate:n}:n;let s,o,i,c,a;function u(){const l=Date.now()-c;if(l<e&&l>=0)i=setTimeout(u,e-l);else if(i=void 0,!r){const h=s,w=o;s=void 0,o=void 0,a=t.apply(h,w)}}const f=function(...l){if(s&&this!==s)throw new Error("Debounced method called with different contexts.");s=this,o=l,c=Date.now();const h=r&&!i;if(i||(i=setTimeout(u,e)),h){const w=s,g=o;s=void 0,o=void 0,a=t.apply(w,g)}return a};return f.clear=()=>{i&&(clearTimeout(i),i=void 0)},f.flush=()=>{if(!i)return;const l=s,h=o;s=void 0,o=void 0,a=t.apply(l,h),clearTimeout(i),i=void 0},f}wt.exports.debounce=sn,wt.exports=sn;var Or=wt.exports;const Ir=$r(Or),pt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const on=t=>t instanceof Uint8Array,yt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),te=(t,e)=>t<<32-e|t>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");const Tr=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function V(t){if(!on(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Tr[t[n]];return e}function gt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}function Nr(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function cn(t){if(typeof t=="string"&&(t=Nr(t)),!on(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}let Cr=class{clone(){return this._cloneInto()}};function an(t){const e=r=>t().update(cn(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Pr(t=32){if(pt&&typeof pt.getRandomValues=="function")return pt.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ln(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function un(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function Rr(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ln(t.outputLen),ln(t.blockLen)}function Qe(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ur(t,e){un(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const bt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fn=t=>t instanceof Uint8Array,mt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ne=(t,e)=>t<<32-e|t>>>e;if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function Hr(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Et(t){if(typeof t=="string"&&(t=Hr(t)),!fn(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function Lr(...t){const e=new Uint8Array(t.reduce((r,s)=>r+s.length,0));let n=0;return t.forEach(r=>{if(!fn(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}class dn{clone(){return this._cloneInto()}}function qr(t){const e=r=>t().update(Et(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function hn(t=32){if(bt&&typeof bt.getRandomValues=="function")return bt.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function Mr(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,i,r),t.setUint32(e+u,c,r)}let Kr=class extends dn{constructor(e,n,r,s){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=mt(this.buffer)}update(e){Qe(this);const{view:n,buffer:r,blockLen:s}=this;e=Et(e);const o=e.length;for(let i=0;i<o;){const c=Math.min(s-this.pos,o-i);if(c===s){const a=mt(e);for(;s<=o-i;i+=s)this.process(a,i);continue}r.set(e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qe(this),Ur(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:o}=this;let{pos:i}=this;n[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(r,0),i=0);for(let l=i;l<s;l++)n[l]=0;Mr(r,s-8,BigInt(this.length*8),o),this.process(r,0);const c=mt(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],o)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:s,finished:o,destroyed:i,pos:c}=this;return e.length=s,e.pos=c,e.finished=o,e.destroyed=i,s%n&&e.buffer.set(r),e}};const jr=(t,e,n)=>t&e^~t&n,zr=(t,e,n)=>t&e^t&n^e&n,Vr=new Uint32Array([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]),fe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),de=new Uint32Array(64);let Dr=class extends Kr{constructor(){super(64,32,8,!1),this.A=fe[0]|0,this.B=fe[1]|0,this.C=fe[2]|0,this.D=fe[3]|0,this.E=fe[4]|0,this.F=fe[5]|0,this.G=fe[6]|0,this.H=fe[7]|0}get(){const{A:e,B:n,C:r,D:s,E:o,F:i,G:c,H:a}=this;return[e,n,r,s,o,i,c,a]}set(e,n,r,s,o,i,c,a){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=c|0,this.H=a|0}process(e,n){for(let l=0;l<16;l++,n+=4)de[l]=e.getUint32(n,!1);for(let l=16;l<64;l++){const h=de[l-15],w=de[l-2],g=ne(h,7)^ne(h,18)^h>>>3,d=ne(w,17)^ne(w,19)^w>>>10;de[l]=d+de[l-7]+g+de[l-16]|0}let{A:r,B:s,C:o,D:i,E:c,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const h=ne(c,6)^ne(c,11)^ne(c,25),w=f+h+jr(c,a,u)+Vr[l]+de[l]|0,d=(ne(r,2)^ne(r,13)^ne(r,22))+zr(r,s,o)|0;f=u,u=a,a=c,c=i+w|0,i=o,o=s,s=r,r=w+d|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,c,a,u,f)}roundClean(){de.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const xt=qr(()=>new Dr);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wn=BigInt(0),Xe=BigInt(1),Wr=BigInt(2),et=t=>t instanceof Uint8Array,Fr=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ne(t){if(!et(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Fr[t[n]];return e}function pn(t){const e=t.toString(16);return e.length&1?`0${e}`:e}function vt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}function Ce(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){const s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}function G(t){return vt(Ne(t))}function St(t){if(!et(t))throw new Error("Uint8Array expected");return vt(Ne(Uint8Array.from(t).reverse()))}function he(t,e){return Ce(t.toString(16).padStart(e*2,"0"))}function _t(t,e){return he(t,e).reverse()}function Gr(t){return Ce(pn(t))}function z(t,e,n){let r;if(typeof e=="string")try{r=Ce(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(et(e))r=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(`${t} expected ${n} bytes, got ${s}`);return r}function xe(...t){const e=new Uint8Array(t.reduce((r,s)=>r+s.length,0));let n=0;return t.forEach(r=>{if(!et(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}function Zr(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Jr(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Yr(t){let e;for(e=0;t>wn;t>>=Xe,e+=1);return e}function Qr(t,e){return t>>BigInt(e)&Xe}const Xr=(t,e,n)=>t|(n?Xe:wn)<<BigInt(e),At=t=>(Wr<<BigInt(t-1))-Xe,kt=t=>new Uint8Array(t),yn=t=>Uint8Array.from(t);function gn(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=kt(t),s=kt(t),o=0;const i=()=>{r.fill(1),s.fill(0),o=0},c=(...l)=>n(s,r,...l),a=(l=kt())=>{s=c(yn([0]),l),r=c(),l.length!==0&&(s=c(yn([1]),l),r=c())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<e;){r=c();const w=r.slice();h.push(w),l+=r.length}return xe(...h)};return(l,h)=>{i(),a(l);let w;for(;!(w=h(u()));)a();return i(),w}}const es={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||t instanceof Uint8Array,isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function je(t,e,n={}){const r=(s,o,i)=>{const c=es[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);const a=t[s];if(!(i&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(s)}=${a} (${typeof a}), expected ${o}`)};for(const[s,o]of Object.entries(e))r(s,o,!1);for(const[s,o]of Object.entries(n))r(s,o,!0);return t}const ts=Object.freeze(Object.defineProperty({__proto__:null,bitGet:Qr,bitLen:Yr,bitMask:At,bitSet:Xr,bytesToHex:Ne,bytesToNumberBE:G,bytesToNumberLE:St,concatBytes:xe,createHmacDrbg:gn,ensureBytes:z,equalBytes:Zr,hexToBytes:Ce,hexToNumber:vt,numberToBytesBE:he,numberToBytesLE:_t,numberToHexUnpadded:pn,numberToVarBytesBE:Gr,utf8ToBytes:Jr,validateObject:je},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const L=BigInt(0),R=BigInt(1),ve=BigInt(2),ns=BigInt(3),Bt=BigInt(4),bn=BigInt(5),mn=BigInt(8);BigInt(9),BigInt(16);function K(t,e){const n=t%e;return n>=L?n:e+n}function rs(t,e,n){if(n<=L||e<L)throw new Error("Expected power/modulo > 0");if(n===R)return L;let r=R;for(;e>L;)e&R&&(r=r*t%n),t=t*t%n,e>>=R;return r}function Q(t,e,n){let r=t;for(;e-- >L;)r*=r,r%=n;return r}function $t(t,e){if(t===L||e<=L)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=K(t,e),r=e,s=L,o=R;for(;n!==L;){const c=r/n,a=r%n,u=s-o*c;r=n,n=a,s=o,o=u}if(r!==R)throw new Error("invert: does not exist");return K(s,e)}function ss(t){const e=(t-R)/ve;let n,r,s;for(n=t-R,r=0;n%ve===L;n/=ve,r++);for(s=ve;s<t&&rs(s,e,t)!==t-R;s++);if(r===1){const i=(t+R)/Bt;return function(a,u){const f=a.pow(u,i);if(!a.eql(a.sqr(f),u))throw new Error("Cannot find square root");return f}}const o=(n+R)/ve;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=r,f=c.pow(c.mul(c.ONE,s),n),l=c.pow(a,o),h=c.pow(a,n);for(;!c.eql(h,c.ONE);){if(c.eql(h,c.ZERO))return c.ZERO;let w=1;for(let d=c.sqr(h);w<u&&!c.eql(d,c.ONE);w++)d=c.sqr(d);const g=c.pow(f,R<<BigInt(u-w-1));f=c.sqr(g),l=c.mul(l,g),h=c.mul(h,f),u=w}return l}}function os(t){if(t%Bt===ns){const e=(t+R)/Bt;return function(r,s){const o=r.pow(s,e);if(!r.eql(r.sqr(o),s))throw new Error("Cannot find square root");return o}}if(t%mn===bn){const e=(t-bn)/mn;return function(r,s){const o=r.mul(s,ve),i=r.pow(o,e),c=r.mul(s,i),a=r.mul(r.mul(c,ve),i),u=r.mul(c,r.sub(a,r.ONE));if(!r.eql(r.sqr(u),s))throw new Error("Cannot find square root");return u}}return ss(t)}const is=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cs(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=is.reduce((r,s)=>(r[s]="function",r),e);return je(t,n)}function as(t,e,n){if(n<L)throw new Error("Expected power > 0");if(n===L)return t.ONE;if(n===R)return e;let r=t.ONE,s=e;for(;n>L;)n&R&&(r=t.mul(r,s)),s=t.sqr(s),n>>=R;return r}function ls(t,e){const n=new Array(e.length),r=e.reduce((o,i,c)=>t.is0(i)?o:(n[c]=o,t.mul(o,i)),t.ONE),s=t.inv(r);return e.reduceRight((o,i,c)=>t.is0(i)?o:(n[c]=t.mul(o,n[c]),t.mul(o,i)),s),n}function En(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function us(t,e,n=!1,r={}){if(t<=L)throw new Error(`Expected Field ORDER > 0, got ${t}`);const{nBitLength:s,nByteLength:o}=En(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=os(t),c=Object.freeze({ORDER:t,BITS:s,BYTES:o,MASK:At(s),ZERO:L,ONE:R,create:a=>K(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return L<=a&&a<t},is0:a=>a===L,isOdd:a=>(a&R)===R,neg:a=>K(-a,t),eql:(a,u)=>a===u,sqr:a=>K(a*a,t),add:(a,u)=>K(a+u,t),sub:(a,u)=>K(a-u,t),mul:(a,u)=>K(a*u,t),pow:(a,u)=>as(c,a,u),div:(a,u)=>K(a*$t(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>$t(a,t),sqrt:r.sqrt||(a=>i(c,a)),invertBatch:a=>ls(c,a),cmov:(a,u,f)=>f?u:a,toBytes:a=>n?_t(a,o):he(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return n?St(a):G(a)}});return Object.freeze(c)}function xn(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function vn(t){const e=xn(t);return e+Math.ceil(e/2)}function fs(t,e,n=!1){const r=t.length,s=xn(e),o=vn(e);if(r<16||r<o||r>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${r}`);const i=n?G(t):St(t),c=K(i,e-R)+R;return n?_t(c,s):he(c,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ds=BigInt(0),Ot=BigInt(1);function hs(t,e){const n=(s,o)=>{const i=o.negate();return s?i:o},r=s=>{const o=Math.ceil(e/s)+1,i=2**(s-1);return{windows:o,windowSize:i}};return{constTimeNegate:n,unsafeLadder(s,o){let i=t.ZERO,c=s;for(;o>ds;)o&Ot&&(i=i.add(c)),c=c.double(),o>>=Ot;return i},precomputeWindow(s,o){const{windows:i,windowSize:c}=r(o),a=[];let u=s,f=u;for(let l=0;l<i;l++){f=u,a.push(f);for(let h=1;h<c;h++)f=f.add(u),a.push(f);u=f.double()}return a},wNAF(s,o,i){const{windows:c,windowSize:a}=r(s);let u=t.ZERO,f=t.BASE;const l=BigInt(2**s-1),h=2**s,w=BigInt(s);for(let g=0;g<c;g++){const d=g*a;let p=Number(i&l);i>>=w,p>a&&(p-=h,i+=Ot);const m=d,x=d+Math.abs(p)-1,S=g%2!==0,$=p<0;p===0?f=f.add(n(S,o[m])):u=u.add(n($,o[x]))}return{p:u,f}},wNAFCached(s,o,i,c){const a=s._WINDOW_SIZE||1;let u=o.get(s);return u||(u=this.precomputeWindow(s,a),a!==1&&o.set(s,c(u))),this.wNAF(a,u,i)}}}function Sn(t){return cs(t.Fp),je(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...En(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ws(t){const e=Sn(t);je(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:s}=e;if(n){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:ps,hexToBytes:ys}=ts,Se={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){const{Err:e}=Se;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:ps(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=Se,n=typeof t=="string"?ys(t):t;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||n[0]!=48)throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:s,l:o}=Se._parseInt(n.subarray(2)),{d:i,l:c}=Se._parseInt(o);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:i}},hexFromSig(t){const e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,n=u=>{const f=u.toString(16);return f.length&1?`0${f}`:f},r=e(n(t.s)),s=e(n(t.r)),o=r.length/2,i=s.length/2,c=n(o),a=n(i);return`30${n(i+o+4)}02${a}${s}02${c}${r}`}},oe=BigInt(0),X=BigInt(1);BigInt(2);const _n=BigInt(3);BigInt(4);function gs(t){const e=ws(t),{Fp:n}=e,r=e.toBytes||((g,d,p)=>{const m=d.toAffine();return xe(Uint8Array.from([4]),n.toBytes(m.x),n.toBytes(m.y))}),s=e.fromBytes||(g=>{const d=g.subarray(1),p=n.fromBytes(d.subarray(0,n.BYTES)),m=n.fromBytes(d.subarray(n.BYTES,2*n.BYTES));return{x:p,y:m}});function o(g){const{a:d,b:p}=e,m=n.sqr(g),x=n.mul(m,g);return n.add(n.add(x,n.mul(g,d)),p)}if(!n.eql(n.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function i(g){return typeof g=="bigint"&&oe<g&&g<e.n}function c(g){if(!i(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){const{allowedPrivateKeyLengths:d,nByteLength:p,wrapPrivateKey:m,n:x}=e;if(d&&typeof g!="bigint"){if(g instanceof Uint8Array&&(g=Ne(g)),typeof g!="string"||!d.includes(g.length))throw new Error("Invalid key");g=g.padStart(p*2,"0")}let S;try{S=typeof g=="bigint"?g:G(z("private key",g,p))}catch{throw new Error(`private key must be ${p} bytes, hex or bigint, not ${typeof g}`)}return m&&(S=K(S,x)),c(S),S}const u=new Map;function f(g){if(!(g instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(d,p,m){if(this.px=d,this.py=p,this.pz=m,d==null||!n.isValid(d))throw new Error("x required");if(p==null||!n.isValid(p))throw new Error("y required");if(m==null||!n.isValid(m))throw new Error("z required")}static fromAffine(d){const{x:p,y:m}=d||{};if(!d||!n.isValid(p)||!n.isValid(m))throw new Error("invalid affine point");if(d instanceof l)throw new Error("projective point not allowed");const x=S=>n.eql(S,n.ZERO);return x(p)&&x(m)?l.ZERO:new l(p,m,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){const p=n.invertBatch(d.map(m=>m.pz));return d.map((m,x)=>m.toAffine(p[x])).map(l.fromAffine)}static fromHex(d){const p=l.fromAffine(s(z("pointHex",d)));return p.assertValidity(),p}static fromPrivateKey(d){return l.BASE.multiply(a(d))}_setWindowSize(d){this._WINDOW_SIZE=d,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:d,y:p}=this.toAffine();if(!n.isValid(d)||!n.isValid(p))throw new Error("bad point: x or y not FE");const m=n.sqr(p),x=o(d);if(!n.eql(m,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:d}=this.toAffine();if(n.isOdd)return!n.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){f(d);const{px:p,py:m,pz:x}=this,{px:S,py:$,pz:B}=d,v=n.eql(n.mul(p,B),n.mul(S,x)),_=n.eql(n.mul(m,B),n.mul($,x));return v&&_}negate(){return new l(this.px,n.neg(this.py),this.pz)}double(){const{a:d,b:p}=e,m=n.mul(p,_n),{px:x,py:S,pz:$}=this;let B=n.ZERO,v=n.ZERO,_=n.ZERO,k=n.mul(x,x),Z=n.mul(S,S),C=n.mul($,$),O=n.mul(x,S);return O=n.add(O,O),_=n.mul(x,$),_=n.add(_,_),B=n.mul(d,_),v=n.mul(m,C),v=n.add(B,v),B=n.sub(Z,v),v=n.add(Z,v),v=n.mul(B,v),B=n.mul(O,B),_=n.mul(m,_),C=n.mul(d,C),O=n.sub(k,C),O=n.mul(d,O),O=n.add(O,_),_=n.add(k,k),k=n.add(_,k),k=n.add(k,C),k=n.mul(k,O),v=n.add(v,k),C=n.mul(S,$),C=n.add(C,C),k=n.mul(C,O),B=n.sub(B,k),_=n.mul(C,Z),_=n.add(_,_),_=n.add(_,_),new l(B,v,_)}add(d){f(d);const{px:p,py:m,pz:x}=this,{px:S,py:$,pz:B}=d;let v=n.ZERO,_=n.ZERO,k=n.ZERO;const Z=e.a,C=n.mul(e.b,_n);let O=n.mul(p,S),W=n.mul(m,$),F=n.mul(x,B),re=n.add(p,m),y=n.add(S,$);re=n.mul(re,y),y=n.add(O,W),re=n.sub(re,y),y=n.add(p,x);let E=n.add(S,B);return y=n.mul(y,E),E=n.add(O,F),y=n.sub(y,E),E=n.add(m,x),v=n.add($,B),E=n.mul(E,v),v=n.add(W,F),E=n.sub(E,v),k=n.mul(Z,y),v=n.mul(C,F),k=n.add(v,k),v=n.sub(W,k),k=n.add(W,k),_=n.mul(v,k),W=n.add(O,O),W=n.add(W,O),F=n.mul(Z,F),y=n.mul(C,y),W=n.add(W,F),F=n.sub(O,F),F=n.mul(Z,F),y=n.add(y,F),O=n.mul(W,y),_=n.add(_,O),O=n.mul(E,y),v=n.mul(re,v),v=n.sub(v,O),O=n.mul(re,W),k=n.mul(E,k),k=n.add(k,O),new l(v,_,k)}subtract(d){return this.add(d.negate())}is0(){return this.equals(l.ZERO)}wNAF(d){return w.wNAFCached(this,u,d,p=>{const m=n.invertBatch(p.map(x=>x.pz));return p.map((x,S)=>x.toAffine(m[S])).map(l.fromAffine)})}multiplyUnsafe(d){const p=l.ZERO;if(d===oe)return p;if(c(d),d===X)return this;const{endo:m}=e;if(!m)return w.unsafeLadder(this,d);let{k1neg:x,k1:S,k2neg:$,k2:B}=m.splitScalar(d),v=p,_=p,k=this;for(;S>oe||B>oe;)S&X&&(v=v.add(k)),B&X&&(_=_.add(k)),k=k.double(),S>>=X,B>>=X;return x&&(v=v.negate()),$&&(_=_.negate()),_=new l(n.mul(_.px,m.beta),_.py,_.pz),v.add(_)}multiply(d){c(d);let p=d,m,x;const{endo:S}=e;if(S){const{k1neg:$,k1:B,k2neg:v,k2:_}=S.splitScalar(p);let{p:k,f:Z}=this.wNAF(B),{p:C,f:O}=this.wNAF(_);k=w.constTimeNegate($,k),C=w.constTimeNegate(v,C),C=new l(n.mul(C.px,S.beta),C.py,C.pz),m=k.add(C),x=Z.add(O)}else{const{p:$,f:B}=this.wNAF(p);m=$,x=B}return l.normalizeZ([m,x])[0]}multiplyAndAddUnsafe(d,p,m){const x=l.BASE,S=(B,v)=>v===oe||v===X||!B.equals(x)?B.multiplyUnsafe(v):B.multiply(v),$=S(this,p).add(S(d,m));return $.is0()?void 0:$}toAffine(d){const{px:p,py:m,pz:x}=this,S=this.is0();d==null&&(d=S?n.ONE:n.inv(x));const $=n.mul(p,d),B=n.mul(m,d),v=n.mul(x,d);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(v,n.ONE))throw new Error("invZ was invalid");return{x:$,y:B}}isTorsionFree(){const{h:d,isTorsionFree:p}=e;if(d===X)return!0;if(p)return p(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:d,clearCofactor:p}=e;return d===X?this:p?p(l,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return this.assertValidity(),r(l,this,d)}toHex(d=!0){return Ne(this.toRawBytes(d))}}l.BASE=new l(e.Gx,e.Gy,n.ONE),l.ZERO=new l(n.ZERO,n.ONE,n.ZERO);const h=e.nBitLength,w=hs(l,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:l,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:i}}function bs(t){const e=Sn(t);return je(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function ms(t){const e=bs(t),{Fp:n,n:r}=e,s=n.BYTES+1,o=2*n.BYTES+1;function i(y){return oe<y&&y<n.ORDER}function c(y){return K(y,r)}function a(y){return $t(y,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:h}=gs({...e,toBytes(y,E,A){const N=E.toAffine(),I=n.toBytes(N.x),q=xe;return A?q(Uint8Array.from([E.hasEvenY()?2:3]),I):q(Uint8Array.from([4]),I,n.toBytes(N.y))},fromBytes(y){const E=y.length,A=y[0],N=y.subarray(1);if(E===s&&(A===2||A===3)){const I=G(N);if(!i(I))throw new Error("Point is not on curve");const q=l(I);let J=n.sqrt(q);const Y=(J&X)===X;return(A&1)===1!==Y&&(J=n.neg(J)),{x:I,y:J}}else if(E===o&&A===4){const I=n.fromBytes(N.subarray(0,n.BYTES)),q=n.fromBytes(N.subarray(n.BYTES,2*n.BYTES));return{x:I,y:q}}else throw new Error(`Point of length ${E} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}}),w=y=>Ne(he(y,e.nByteLength));function g(y){const E=r>>X;return y>E}function d(y){return g(y)?c(-y):y}const p=(y,E,A)=>G(y.slice(E,A));class m{constructor(E,A,N){this.r=E,this.s=A,this.recovery=N,this.assertValidity()}static fromCompact(E){const A=e.nByteLength;return E=z("compactSignature",E,A*2),new m(p(E,0,A),p(E,A,2*A))}static fromDER(E){const{r:A,s:N}=Se.toSig(z("DER",E));return new m(A,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(E){return new m(this.r,this.s,E)}recoverPublicKey(E){const{r:A,s:N,recovery:I}=this,q=_(z("msgHash",E));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");const J=I===2||I===3?A+e.n:A;if(J>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const Y=I&1?"03":"02",ge=u.fromHex(Y+w(J)),be=a(J),Ue=c(-q*be),Ze=c(N*be),me=u.BASE.multiplyAndAddUnsafe(ge,Ue,Ze);if(!me)throw new Error("point at infinify");return me.assertValidity(),me}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Ce(this.toDERHex())}toDERHex(){return Se.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ce(this.toCompactHex())}toCompactHex(){return w(this.r)+w(this.s)}}const x={isValidPrivateKey(y){try{return f(y),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const y=vn(e.n);return fs(e.randomBytes(y),e.n)},precompute(y=8,E=u.BASE){return E._setWindowSize(y),E.multiply(BigInt(3)),E}};function S(y,E=!0){return u.fromPrivateKey(y).toRawBytes(E)}function $(y){const E=y instanceof Uint8Array,A=typeof y=="string",N=(E||A)&&y.length;return E?N===s||N===o:A?N===2*s||N===2*o:y instanceof u}function B(y,E,A=!0){if($(y))throw new Error("first arg must be private key");if(!$(E))throw new Error("second arg must be public key");return u.fromHex(E).multiply(f(y)).toRawBytes(A)}const v=e.bits2int||function(y){const E=G(y),A=y.length*8-e.nBitLength;return A>0?E>>BigInt(A):E},_=e.bits2int_modN||function(y){return c(v(y))},k=At(e.nBitLength);function Z(y){if(typeof y!="bigint")throw new Error("bigint expected");if(!(oe<=y&&y<k))throw new Error(`bigint expected < 2^${e.nBitLength}`);return he(y,e.nByteLength)}function C(y,E,A=O){if(["recovered","canonical"].some(ke=>ke in A))throw new Error("sign() legacy options not supported");const{hash:N,randomBytes:I}=e;let{lowS:q,prehash:J,extraEntropy:Y}=A;q==null&&(q=!0),y=z("msgHash",y),J&&(y=z("prehashed msgHash",N(y)));const ge=_(y),be=f(E),Ue=[Z(be),Z(ge)];if(Y!=null){const ke=Y===!0?I(n.BYTES):Y;Ue.push(z("extraEntropy",ke))}const Ze=xe(...Ue),me=ge;function Gt(ke){const He=v(ke);if(!h(He))return;const or=a(He),Le=u.BASE.multiply(He).toAffine(),ee=c(Le.x);if(ee===oe)return;const qe=c(or*c(me+ee*be));if(qe===oe)return;let ir=(Le.x===ee?0:2)|Number(Le.y&X),cr=qe;return q&&g(qe)&&(cr=d(qe),ir^=1),new m(ee,cr,ir)}return{seed:Ze,k2sig:Gt}}const O={lowS:e.lowS,prehash:!1},W={lowS:e.lowS,prehash:!1};function F(y,E,A=O){const{seed:N,k2sig:I}=C(y,E,A),q=e;return gn(q.hash.outputLen,q.nByteLength,q.hmac)(N,I)}u.BASE._setWindowSize(8);function re(y,E,A,N=W){var Le;const I=y;if(E=z("msgHash",E),A=z("publicKey",A),"strict"in N)throw new Error("options.strict was renamed to lowS");const{lowS:q,prehash:J}=N;let Y,ge;try{if(typeof I=="string"||I instanceof Uint8Array)try{Y=m.fromDER(I)}catch(ee){if(!(ee instanceof Se.Err))throw ee;Y=m.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){const{r:ee,s:qe}=I;Y=new m(ee,qe)}else throw new Error("PARSE");ge=u.fromHex(A)}catch(ee){if(ee.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(q&&Y.hasHighS())return!1;J&&(E=e.hash(E));const{r:be,s:Ue}=Y,Ze=_(E),me=a(Ue),Gt=c(Ze*me),ke=c(be*me),He=(Le=u.BASE.multiplyAndAddUnsafe(ge,Gt,ke))==null?void 0:Le.toAffine();return He?c(He.x)===be:!1}return{CURVE:e,getPublicKey:S,getSharedSecret:B,sign:F,verify:re,ProjectivePoint:u,Signature:m,utils:x}}class An extends dn{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Rr(e);const r=Et(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),o.fill(0)}update(e){return Qe(this),this.iHash.update(e),this}digestInto(e){Qe(this),un(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const kn=(t,e,n)=>new An(t,e).update(n).digest();kn.create=(t,e)=>new An(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Es(t){return{hash:t,hmac:(e,...n)=>kn(t,e,Lr(...n)),randomBytes:hn}}function xs(t,e){const n=r=>ms({...t,...Es(r)});return Object.freeze({...n(e),create:n})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const tt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),nt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Bn=BigInt(1),rt=BigInt(2),$n=(t,e)=>(t+e/rt)/e;function On(t){const e=tt,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,f=u*u*t%e,l=Q(f,n,e)*f%e,h=Q(l,n,e)*f%e,w=Q(h,rt,e)*u%e,g=Q(w,s,e)*w%e,d=Q(g,o,e)*g%e,p=Q(d,c,e)*d%e,m=Q(p,a,e)*p%e,x=Q(m,c,e)*d%e,S=Q(x,n,e)*f%e,$=Q(S,i,e)*g%e,B=Q($,r,e)*u%e,v=Q(B,rt,e);if(!It.eql(It.sqr(v),t))throw new Error("Cannot find square root");return v}const It=us(tt,void 0,void 0,{sqrt:On}),ze=xs({a:BigInt(0),b:BigInt(7),Fp:It,n:nt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=nt,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Bn*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=n,i=BigInt("0x100000000000000000000000000000000"),c=$n(o*t,e),a=$n(-r*t,e);let u=K(t-c*n-a*s,e),f=K(-c*r-a*o,e);const l=u>i,h=f>i;if(l&&(u=e-u),h&&(f=e-f),u>i||f>i)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:h,k2:f}}}},xt),st=BigInt(0),In=t=>typeof t=="bigint"&&st<t&&t<tt,vs=t=>typeof t=="bigint"&&st<t&&t<nt,Tn={};function ot(t,...e){let n=Tn[t];if(n===void 0){const r=xt(Uint8Array.from(t,s=>s.charCodeAt(0)));n=xe(r,r),Tn[t]=n}return xt(xe(n,...e))}const Tt=t=>t.toRawBytes(!0).slice(1),Nt=t=>he(t,32),Ct=t=>K(t,tt),Ve=t=>K(t,nt),Pt=ze.ProjectivePoint,Ss=(t,e,n)=>Pt.BASE.multiplyAndAddUnsafe(t,e,n);function Rt(t){let e=ze.utils.normPrivateKeyToScalar(t),n=Pt.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:Ve(-e),bytes:Tt(n)}}function Nn(t){if(!In(t))throw new Error("bad x: need 0 < x < p");const e=Ct(t*t),n=Ct(e*t+BigInt(7));let r=On(n);r%rt!==st&&(r=Ct(-r));const s=new Pt(t,r,Bn);return s.assertValidity(),s}function Cn(...t){return Ve(G(ot("BIP0340/challenge",...t)))}function _s(t){return Rt(t).bytes}function As(t,e,n=hn(32)){const r=z("message",t),{bytes:s,scalar:o}=Rt(e),i=z("auxRand",n,32),c=Nt(o^G(ot("BIP0340/aux",i))),a=ot("BIP0340/nonce",c,s,r),u=Ve(G(a));if(u===st)throw new Error("sign failed: k is zero");const{bytes:f,scalar:l}=Rt(u),h=Cn(f,s,r),w=new Uint8Array(64);if(w.set(f,0),w.set(Nt(Ve(l+h*o)),32),!Pn(w,r,s))throw new Error("sign: Invalid signature produced");return w}function Pn(t,e,n){const r=z("signature",t,64),s=z("message",e),o=z("publicKey",n,32);try{const i=Nn(G(o)),c=G(r.subarray(0,32));if(!In(c))return!1;const a=G(r.subarray(32,64));if(!vs(a))return!1;const u=Cn(Nt(c),Tt(i),s),f=Ss(i,a,Ve(-u));return!(!f||!f.hasEvenY()||f.toAffine().x!==c)}catch{return!1}}const D={getPublicKey:_s,sign:As,verify:Pn,utils:{randomPrivateKey:ze.utils.randomPrivateKey,lift_x:Nn,pointToBytes:Tt,numberToBytesBE:he,bytesToNumberBE:G,taggedHash:ot,mod:K}};function Ut(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function ks(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}function Rn(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function Bs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ut(t.outputLen),Ut(t.blockLen)}function $s(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Os(t,e){Rn(t);const n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const Ht={number:Ut,bool:ks,bytes:Rn,hash:Bs,exists:$s,output:Os};function Is(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,i,r),t.setUint32(e+u,c,r)}class Ts extends Cr{constructor(e,n,r,s){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=yt(this.buffer)}update(e){Ht.exists(this);const{view:n,buffer:r,blockLen:s}=this;e=cn(e);const o=e.length;for(let i=0;i<o;){const c=Math.min(s-this.pos,o-i);if(c===s){const a=yt(e);for(;s<=o-i;i+=s)this.process(a,i);continue}r.set(e.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ht.exists(this),Ht.output(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:o}=this;let{pos:i}=this;n[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(r,0),i=0);for(let l=i;l<s;l++)n[l]=0;Is(r,s-8,BigInt(this.length*8),o),this.process(r,0);const c=yt(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],o)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:s,finished:o,destroyed:i,pos:c}=this;return e.length=s,e.pos=c,e.finished=o,e.destroyed=i,s%n&&e.buffer.set(r),e}}const Ns=(t,e,n)=>t&e^~t&n,Cs=(t,e,n)=>t&e^t&n^e&n,Ps=new Uint32Array([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]),we=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pe=new Uint32Array(64);class Un extends Ts{constructor(){super(64,32,8,!1),this.A=we[0]|0,this.B=we[1]|0,this.C=we[2]|0,this.D=we[3]|0,this.E=we[4]|0,this.F=we[5]|0,this.G=we[6]|0,this.H=we[7]|0}get(){const{A:e,B:n,C:r,D:s,E:o,F:i,G:c,H:a}=this;return[e,n,r,s,o,i,c,a]}set(e,n,r,s,o,i,c,a){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=c|0,this.H=a|0}process(e,n){for(let l=0;l<16;l++,n+=4)pe[l]=e.getUint32(n,!1);for(let l=16;l<64;l++){const h=pe[l-15],w=pe[l-2],g=te(h,7)^te(h,18)^h>>>3,d=te(w,17)^te(w,19)^w>>>10;pe[l]=d+pe[l-7]+g+pe[l-16]|0}let{A:r,B:s,C:o,D:i,E:c,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const h=te(c,6)^te(c,11)^te(c,25),w=f+h+Ns(c,a,u)+Ps[l]+pe[l]|0,d=(te(r,2)^te(r,13)^te(r,22))+Cs(r,s,o)|0;f=u,u=a,a=c,c=i+w|0,i=o,o=s,s=r,r=w+d|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,s,o,i,c,a,u,f)}roundClean(){pe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Rs extends Un{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Lt=an(()=>new Un);an(()=>new Rs);var Pe=Symbol("verified"),Us=t=>t instanceof Object;function Hs(t){if(!Us(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]=="object")return!1}return!0}new TextDecoder("utf-8");var Ls=new TextEncoder,qs=class{generateSecretKey(){return D.utils.randomPrivateKey()}getPublicKey(e){return V(D.getPublicKey(e))}finalizeEvent(e,n){const r=e;return r.pubkey=V(D.getPublicKey(n)),r.id=qt(r),r.sig=V(D.sign(qt(r),n)),r[Pe]=!0,r}verifyEvent(e){if(typeof e[Pe]=="boolean")return e[Pe];const n=qt(e);if(n!==e.id)return e[Pe]=!1,!1;try{const r=D.verify(e.sig,n,e.pubkey);return e[Pe]=r,r}catch{return e[Pe]=!1,!1}}};function Ms(t){if(!Hs(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function qt(t){let e=Lt(Ls.encode(Ms(t)));return V(e)}var it=new qs,Ks=it.generateSecretKey;it.getPublicKey,it.finalizeEvent,it.verifyEvent;var _e=Symbol("verified"),js=t=>t instanceof Object;function zs(t){if(!js(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]=="object")return!1}return!0}new TextDecoder("utf-8");var Vs=new TextEncoder;function De(t){t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}var Ds=class{constructor(e){b(this,"value");b(this,"next",null);b(this,"prev",null);this.value=e}},Ws=class{constructor(){b(this,"first");b(this,"last");this.first=null,this.last=null}enqueue(e){const n=new Ds(e);return this.last?this.last===this.first?(this.last=n,this.last.prev=this.first,this.first.next=n):(n.prev=this.last,this.last.next=n,this.last=n):(this.first=n,this.last=n),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const n=this.first;return this.first=null,this.last=null,n.value}const e=this.first;return this.first=e.next,e.value}},Fs=class{generateSecretKey(){return D.utils.randomPrivateKey()}getPublicKey(e){return V(D.getPublicKey(e))}finalizeEvent(e,n){const r=e;return r.pubkey=V(D.getPublicKey(n)),r.id=Mt(r),r.sig=V(D.sign(Mt(r),n)),r[_e]=!0,r}verifyEvent(e){if(typeof e[_e]=="boolean")return e[_e];const n=Mt(e);if(n!==e.id)return e[_e]=!1,!1;try{const r=D.verify(e.sig,n,e.pubkey);return e[_e]=r,r}catch{return e[_e]=!1,!1}}};function Gs(t){if(!zs(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function Mt(t){let e=Lt(Vs.encode(Gs(t)));return V(e)}var ct=new Fs;ct.generateSecretKey,ct.getPublicKey,ct.finalizeEvent;var Zs=ct.verifyEvent,Js=22242;function Ys(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1&&!t.ids.some(n=>e.id.startsWith(n))||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1&&!t.authors.some(n=>e.pubkey.startsWith(n)))return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),s=t[`#${r}`];if(s&&!e.tags.find(([o,i])=>o===n.slice(1)&&s.indexOf(i)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function Qs(t,e){for(let n=0;n<t.length;n++)if(Ys(t[n],e))return!0;return!1}function Xs(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,s=t.slice(r).indexOf('"')+r+1;return t.slice(s,s+64)}function eo(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,s=t.slice(r+1,80).indexOf('"');if(s===-1)return null;let o=r+1+s;return t.slice(r+1,o)}function to(t,e){return{kind:Js,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}async function no(){return new Promise(t=>{const e=new MessageChannel,n=()=>{e.port1.removeEventListener("message",n),t()};e.port1.addEventListener("message",n),e.port2.postMessage(0),e.port1.start()})}var ro=t=>(t[_e]=!0,!0),Hn;try{Hn=WebSocket}catch{}var Ln=class{constructor(e,n){b(this,"url");b(this,"_connected",!1);b(this,"onclose",null);b(this,"onnotice",e=>console.debug(`NOTICE from ${this.url}: ${e}`));b(this,"baseEoseTimeout",4400);b(this,"connectionTimeout",4400);b(this,"openSubs",new Map);b(this,"connectionTimeoutHandle");b(this,"connectionPromise");b(this,"openCountRequests",new Map);b(this,"openEventPublishes",new Map);b(this,"ws");b(this,"incomingMessageQueue",new Ws);b(this,"queueRunning",!1);b(this,"challenge");b(this,"serial",0);b(this,"verifyEvent");this.url=De(e),this.verifyEvent=n.verifyEvent}static async connect(e,n){const r=new Ln(e,n);return await r.connect(),r}closeAllSubscriptions(e){for(let[n,r]of this.openSubs)r.close(e);this.openSubs.clear();for(let[n,r]of this.openEventPublishes)r.reject(new Error(e));this.openEventPublishes.clear();for(let[n,r]of this.openCountRequests)r.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async connect(){return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.connectionPromise=new Promise((e,n)=>{this.connectionTimeoutHandle=setTimeout(()=>{var r;n("connection timed out"),this.connectionPromise=void 0,(r=this.onclose)==null||r.call(this),this.closeAllSubscriptions("relay connection timed out")},this.connectionTimeout);try{this.ws=new Hn(this.url)}catch(r){n(r);return}this.ws.onopen=()=>{clearTimeout(this.connectionTimeoutHandle),this._connected=!0,e()},this.ws.onerror=r=>{var s;n(r.message),this._connected&&((s=this.onclose)==null||s.call(this),this.closeAllSubscriptions("relay connection errored"),this._connected=!1)},this.ws.onclose=async()=>{var r;this.connectionPromise=void 0,(r=this.onclose)==null||r.call(this),this.closeAllSubscriptions("relay connection closed"),this._connected=!1},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}async runQueue(){for(this.queueRunning=!0;this.handleNext()!==!1;)await no();this.queueRunning=!1}handleNext(){var r,s;const e=this.incomingMessageQueue.dequeue();if(!e)return!1;const n=eo(e);if(n){const o=this.openSubs.get(n);if(!o)return;const i=Xs(e,"id"),c=(r=o.alreadyHaveEvent)==null?void 0:r.call(o,i);if((s=o.receivedEvent)==null||s.call(o,this,i),c)return}try{let o=JSON.parse(e);switch(o[0]){case"EVENT":{const i=this.openSubs.get(o[1]),c=o[2];this.verifyEvent(c)&&Qs(i.filters,c)&&i.onevent(c);return}case"COUNT":{const i=o[1],c=o[2],a=this.openCountRequests.get(i);a&&(a.resolve(c.count),this.openCountRequests.delete(i));return}case"EOSE":{const i=this.openSubs.get(o[1]);if(!i)return;i.receivedEose();return}case"OK":{const i=o[1],c=o[2],a=o[3],u=this.openEventPublishes.get(i);c?u.resolve(a):u.reject(new Error(a)),this.openEventPublishes.delete(i);return}case"CLOSED":{const i=o[1],c=this.openSubs.get(i);if(!c)return;c.closed=!0,c.close(o[2]);return}case"NOTICE":this.onnotice(o[1]);return;case"AUTH":{this.challenge=o[1];return}}}catch{return}}async send(e){if(!this.connectionPromise)throw new Error("sending on closed connection");this.connectionPromise.then(()=>{var n;(n=this.ws)==null||n.send(e)})}async auth(e){if(!this.challenge)throw new Error("can't perform auth, no challenge was received");const n=await e(to(this.url,this.challenge)),r=new Promise((s,o)=>{this.openEventPublishes.set(n.id,{resolve:s,reject:o})});return this.send('["AUTH",'+JSON.stringify(n)+"]"),r}async publish(e){const n=new Promise((r,s)=>{this.openEventPublishes.set(e.id,{resolve:r,reject:s})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),n}async count(e,n){this.serial++;const r=(n==null?void 0:n.id)||"count:"+this.serial,s=new Promise((o,i)=>{this.openCountRequests.set(r,{resolve:o,reject:i})});return this.send('["COUNT","'+r+'",'+JSON.stringify(e)+"]"),s}subscribe(e,n){const r=this.prepareSubscription(e,n);return r.fire(),r}prepareSubscription(e,n){this.serial++;const r=n.id||"sub:"+this.serial,s=new so(this,r,e,n);return this.openSubs.set(r,s),s}close(){var e;this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,(e=this.ws)==null||e.close()}_onmessage(e){this.incomingMessageQueue.enqueue(e.data),this.queueRunning||this.runQueue()}},so=class{constructor(e,n,r,s){b(this,"relay");b(this,"id");b(this,"closed",!1);b(this,"eosed",!1);b(this,"filters");b(this,"alreadyHaveEvent");b(this,"receivedEvent");b(this,"onevent");b(this,"oneose");b(this,"onclose");b(this,"eoseTimeout");b(this,"eoseTimeoutHandle");this.relay=e,this.filters=r,this.id=n,this.alreadyHaveEvent=s.alreadyHaveEvent,this.receivedEvent=s.receivedEvent,this.eoseTimeout=s.eoseTimeout||e.baseEoseTimeout,this.oneose=s.oneose,this.onclose=s.onclose,this.onevent=s.onevent||(o=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,o)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){var e;this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,(e=this.oneose)==null||e.call(this))}close(e="closed by caller"){var n;this.closed||(this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]"),this.closed=!0),this.relay.openSubs.delete(this.id),(n=this.onclose)==null||n.call(this,e)}},oo=class{constructor(e){b(this,"relays",new Map);b(this,"seenOn",new Map);b(this,"trackRelays",!1);b(this,"verifyEvent");b(this,"trustedRelayURLs",new Set);this.verifyEvent=e.verifyEvent}async ensureRelay(e,n){e=De(e);let r=this.relays.get(e);return r||(r=new Ln(e,{verifyEvent:this.trustedRelayURLs.has(e)?ro:this.verifyEvent}),n!=null&&n.connectionTimeout&&(r.connectionTimeout=n.connectionTimeout),this.relays.set(e,r)),await r.connect(),r}close(e){e.map(De).forEach(n=>{var r;(r=this.relays.get(n))==null||r.close()})}subscribeMany(e,n,r){this.trackRelays&&(r.receivedEvent=(h,w)=>{let g=this.seenOn.get(w);g||(g=new Set,this.seenOn.set(w,g)),g.add(h)});const s=new Set,o=[],i=[];let c=h=>{var w;i[h]=!0,i.filter(g=>g).length===e.length&&((w=r.oneose)==null||w.call(r),c=()=>{})};const a=[];let u=(h,w)=>{var g;c(h),a[h]=w,a.filter(d=>d).length===e.length&&((g=r.onclose)==null||g.call(r,a),u=()=>{})};const f=h=>{var g;if((g=r.alreadyHaveEvent)!=null&&g.call(r,h))return!0;const w=s.has(h);return s.add(h),w},l=Promise.all(e.map(De).map(async(h,w,g)=>{if(g.indexOf(h)!==w){u(w,"duplicate url");return}let d;try{d=await this.ensureRelay(h,{connectionTimeout:r.maxWait?Math.max(r.maxWait*.8,r.maxWait-1e3):void 0})}catch(m){u(w,(m==null?void 0:m.message)||String(m));return}let p=d.subscribe(n,{...r,oneose:()=>c(w),onclose:m=>u(w,m),alreadyHaveEvent:f,eoseTimeout:r.maxWait});o.push(p)}));return{async close(){await l,o.forEach(h=>{h.close()})}}}subscribeManyEose(e,n,r){const s=this.subscribeMany(e,n,{...r,oneose(){s.close()}});return s}async querySync(e,n,r){return new Promise(async s=>{const o=[];this.subscribeManyEose(e,[n],{...r,onevent(i){o.push(i)},onclose(i){s(o)}})})}async get(e,n,r){n.limit=1;const s=await this.querySync(e,n,r);return s.sort((o,i)=>i.created_at-o.created_at),s[0]||null}publish(e,n){return e.map(De).map(async(r,s,o)=>o.indexOf(r)!==s?Promise.reject("duplicate url"):(await this.ensureRelay(r)).publish(n))}},io=class extends oo{constructor(){super({verifyEvent:Zs})}};/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Re(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function ie(...t){const e=(s,o)=>i=>s(o(i)),n=Array.from(t).reverse().reduce((s,o)=>s?e(s,o.encode):o.encode,void 0),r=t.reduce((s,o)=>s?e(s,o.decode):o.decode,void 0);return{encode:n,decode:r}}function ce(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(n=>{if(Re(n),n<0||n>=t.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${t.length})`);return t[n]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(n=>{if(typeof n!="string")throw new Error(`alphabet.decode: not string element=${n}`);const r=t.indexOf(n);if(r===-1)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return r})}}}function ae(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let n of e)if(typeof n!="string")throw new Error(`join.encode: non-string input=${n}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function at(t,e="="){if(Re(t),typeof e!="string")throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of n)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&typeof n[0]!="string")throw new Error("padding.encode input should be array of strings");for(let s of n)if(typeof s!="string")throw new Error(`padding.decode: non-string input=${s}`);let r=n.length;if(r*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if(!((r-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function qn(t){if(typeof t!="function")throw new Error("normalize fn should be function");return{encode:e=>e,decode:e=>t(e)}}function Mn(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let r=0;const s=[],o=Array.from(t);for(o.forEach(i=>{if(Re(i),i<0||i>=e)throw new Error(`Wrong integer: ${i}`)});;){let i=0,c=!0;for(let a=r;a<o.length;a++){const u=o[a],f=e*i+u;if(!Number.isSafeInteger(f)||e*i/e!==i||f-u!==e*i)throw new Error("convertRadix: carry overflow");if(i=f%n,o[a]=Math.floor(f/n),!Number.isSafeInteger(o[a])||o[a]*n+i!==f)throw new Error("convertRadix: carry overflow");if(c)o[a]?c=!1:r=a;else continue}if(s.push(i),c)break}for(let i=0;i<t.length-1&&t[i]===0;i++)s.push(0);return s.reverse()}const Kn=(t,e)=>e?Kn(e,t%e):t,lt=(t,e)=>t+(e-Kn(t,e));function Kt(t,e,n,r){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(lt(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${lt(e,n)}`);let s=0,o=0;const i=2**n-1,c=[];for(const a of t){if(Re(a),a>=2**e)throw new Error(`convertRadix2: invalid data word=${a} from=${e}`);if(s=s<<e|a,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=n;o-=n)c.push((s>>o-n&i)>>>0);s&=2**o-1}if(s=s<<n-o&i,!r&&o>=e)throw new Error("Excess padding");if(!r&&s)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&c.push(s>>>0),c}function co(t){return Re(t),{encode:e=>{if(!(e instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return Mn(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(Mn(e,t,2**8))}}}function ye(t,e=!1){if(Re(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(lt(8,t)>32||lt(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Kt(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&typeof n[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Kt(n,t,8,e))}}}function jn(t){if(typeof t!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return t.apply(null,e)}catch{}}}const ao=ie(ye(4),ce("0123456789ABCDEF"),ae("")),lo=ie(ye(5),ce("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),at(5),ae(""));ie(ye(5),ce("0123456789ABCDEFGHIJKLMNOPQRSTUV"),at(5),ae("")),ie(ye(5),ce("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ae(""),qn(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const We=ie(ye(6),ce("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),at(6),ae("")),uo=ie(ye(6),ce("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),at(6),ae("")),jt=t=>ie(co(58),ce(t),ae("")),zt=jt("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");jt("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),jt("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const zn=[0,2,3,5,6,7,9,10,11],fo={encode(t){let e="";for(let n=0;n<t.length;n+=8){const r=t.subarray(n,n+8);e+=zt.encode(r).padStart(zn[r.length],"1")}return e},decode(t){let e=[];for(let n=0;n<t.length;n+=11){const r=t.slice(n,n+11),s=zn.indexOf(r.length),o=zt.decode(r);for(let i=0;i<o.length-s;i++)if(o[i]!==0)throw new Error("base58xmr: wrong padding");e=e.concat(Array.from(o.slice(o.length-s)))}return Uint8Array.from(e)}},Vt=ie(ce("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ae("")),Vn=[996825010,642813549,513874426,1027748829,705979059];function Fe(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Vn.length;r++)(e>>r&1)===1&&(n^=Vn[r]);return n}function Dn(t,e,n=1){const r=t.length;let s=1;for(let o=0;o<r;o++){const i=t.charCodeAt(o);if(i<33||i>126)throw new Error(`Invalid prefix (${t})`);s=Fe(s)^i>>5}s=Fe(s);for(let o=0;o<r;o++)s=Fe(s)^t.charCodeAt(o)&31;for(let o of e)s=Fe(s)^o;for(let o=0;o<6;o++)s=Fe(s);return s^=n,Vt.encode(Kt([s%2**30],30,5,!1))}function Wn(t){const e=t==="bech32"?1:734539939,n=ye(5),r=n.decode,s=n.encode,o=jn(r);function i(f,l,h=90){if(typeof f!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof f}`);if(!Array.isArray(l)||l.length&&typeof l[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof l}`);const w=f.length+7+l.length;if(h!==!1&&w>h)throw new TypeError(`Length ${w} exceeds limit ${h}`);return f=f.toLowerCase(),`${f}1${Vt.encode(l)}${Dn(f,l,e)}`}function c(f,l=90){if(typeof f!="string")throw new Error(`bech32.decode input should be string, not ${typeof f}`);if(f.length<8||l!==!1&&f.length>l)throw new TypeError(`Wrong string length: ${f.length} (${f}). Expected (8..${l})`);const h=f.toLowerCase();if(f!==h&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");f=h;const w=f.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const g=f.slice(0,w),d=f.slice(w+1);if(d.length<6)throw new Error("Data must be at least 6 characters long");const p=Vt.decode(d).slice(0,-6),m=Dn(g,p,e);if(!d.endsWith(m))throw new Error(`Invalid checksum in ${f}: expected "${m}"`);return{prefix:g,words:p}}const a=jn(c);function u(f){const{prefix:l,words:h}=c(f,!1);return{prefix:l,words:h,bytes:r(h)}}return{encode:i,decode:c,decodeToBytes:u,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:o,toWords:s}}const Fn=Wn("bech32");Wn("bech32m");const ho={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},wo=ie(ye(4),ce("0123456789abcdef"),ae(""),qn(t=>{if(typeof t!="string"||t.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));`${Object.keys({utf8:ho,hex:wo,base16:ao,base32:lo,base64:We,base64url:uo,base58:zt,base58xmr:fo}).join(", ")}`;var Ae=Symbol("verified"),po=t=>t instanceof Object;function yo(t){if(!po(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]=="object")return!1}return!0}var go=new TextDecoder("utf-8"),Gn=new TextEncoder;function Ge(t){t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}var bo=class{constructor(t){b(this,"value");b(this,"next",null);b(this,"prev",null);this.value=t}},mo=class{constructor(){b(this,"first");b(this,"last");this.first=null,this.last=null}enqueue(t){const e=new bo(t);return this.last?this.last===this.first?(this.last=e,this.last.prev=this.first,this.first.next=e):(e.prev=this.last,this.last.next=e,this.last=e):(this.first=e,this.last=e),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const e=this.first;return this.first=null,this.last=null,e.value}const t=this.first;return this.first=t.next,t.value}},Eo=class{generateSecretKey(){return D.utils.randomPrivateKey()}getPublicKey(t){return V(D.getPublicKey(t))}finalizeEvent(t,e){const n=t;return n.pubkey=V(D.getPublicKey(e)),n.id=Dt(n),n.sig=V(D.sign(Dt(n),e)),n[Ae]=!0,n}verifyEvent(t){if(typeof t[Ae]=="boolean")return t[Ae];const e=Dt(t);if(e!==t.id)return t[Ae]=!1,!1;try{const n=D.verify(t.sig,e,t.pubkey);return t[Ae]=n,n}catch{return t[Ae]=!1,!1}}};function xo(t){if(!yo(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function Dt(t){let e=Lt(Gn.encode(xo(t)));return V(e)}var ut=new Eo,vo=ut.generateSecretKey,Zn=ut.getPublicKey,So=ut.finalizeEvent,Jn=ut.verifyEvent;typeof crypto<"u"&&!crypto.subtle&&crypto.webcrypto&&(crypto.subtle=crypto.webcrypto.subtle);async function _o(t,e,n){const r=t instanceof Uint8Array?V(t):t,s=ze.getSharedSecret(r,"02"+e),o=Yn(s);let i=Uint8Array.from(Pr(16)),c=Gn.encode(n),a=await crypto.subtle.importKey("raw",o,{name:"AES-CBC"},!1,["encrypt"]),u=await crypto.subtle.encrypt({name:"AES-CBC",iv:i},a,c),f=We.encode(new Uint8Array(u)),l=We.encode(new Uint8Array(i.buffer));return`${f}?iv=${l}`}async function Ao(t,e,n){const r=t instanceof Uint8Array?V(t):t;let[s,o]=n.split("?iv="),i=ze.getSharedSecret(r,"02"+e),c=Yn(i),a=await crypto.subtle.importKey("raw",c,{name:"AES-CBC"},!1,["decrypt"]),u=We.decode(s),f=We.decode(o),l=await crypto.subtle.decrypt({name:"AES-CBC",iv:f},a,u);return go.decode(l)}function Yn(t){return t.slice(1,33)}var ko=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Bo;try{Bo=fetch}catch{}var $o=22242,Wt=24133,Oo=31990;function Io(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1&&!t.ids.some(n=>e.id.startsWith(n))||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1&&!t.authors.some(n=>e.pubkey.startsWith(n)))return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),s=t[`#${r}`];if(s&&!e.tags.find(([o,i])=>o===n.slice(1)&&s.indexOf(i)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function To(t,e){for(let n=0;n<t.length;n++)if(Io(t[n],e))return!0;return!1}function No(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,s=t.slice(r).indexOf('"')+r+1;return t.slice(s,s+64)}function Co(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,s=t.slice(r+1,80).indexOf('"');if(s===-1)return null;let o=r+1+s;return t.slice(r+1,o)}function Po(t,e){return{kind:$o,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}async function Ro(){return new Promise(t=>{const e=new MessageChannel,n=()=>{e.port1.removeEventListener("message",n),t()};e.port1.addEventListener("message",n),e.port2.postMessage(0),e.port1.start()})}var Uo=t=>(t[Ae]=!0,!0),Qn;try{Qn=WebSocket}catch{}var Xn=class{constructor(t,e){b(this,"url");b(this,"_connected",!1);b(this,"onclose",null);b(this,"onnotice",t=>console.debug(`NOTICE from ${this.url}: ${t}`));b(this,"baseEoseTimeout",4400);b(this,"connectionTimeout",4400);b(this,"openSubs",new Map);b(this,"connectionTimeoutHandle");b(this,"connectionPromise");b(this,"openCountRequests",new Map);b(this,"openEventPublishes",new Map);b(this,"ws");b(this,"incomingMessageQueue",new mo);b(this,"queueRunning",!1);b(this,"challenge");b(this,"serial",0);b(this,"verifyEvent");this.url=Ge(t),this.verifyEvent=e.verifyEvent}static async connect(t,e){const n=new Xn(t,e);return await n.connect(),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}async connect(){return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.connectionPromise=new Promise((t,e)=>{this.connectionTimeoutHandle=setTimeout(()=>{var n;e("connection timed out"),this.connectionPromise=void 0,(n=this.onclose)==null||n.call(this),this.closeAllSubscriptions("relay connection timed out")},this.connectionTimeout);try{this.ws=new Qn(this.url)}catch(n){e(n);return}this.ws.onopen=()=>{clearTimeout(this.connectionTimeoutHandle),this._connected=!0,t()},this.ws.onerror=n=>{var r;e(n.message),this._connected&&((r=this.onclose)==null||r.call(this),this.closeAllSubscriptions("relay connection errored"),this._connected=!1)},this.ws.onclose=async()=>{var n;this.connectionPromise=void 0,(n=this.onclose)==null||n.call(this),this.closeAllSubscriptions("relay connection closed"),this._connected=!1},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}async runQueue(){for(this.queueRunning=!0;this.handleNext()!==!1;)await Ro();this.queueRunning=!1}handleNext(){var n,r;const t=this.incomingMessageQueue.dequeue();if(!t)return!1;const e=Co(t);if(e){const s=this.openSubs.get(e);if(!s)return;const o=No(t,"id"),i=(n=s.alreadyHaveEvent)==null?void 0:n.call(s,o);if((r=s.receivedEvent)==null||r.call(s,this,o),i)return}try{let s=JSON.parse(t);switch(s[0]){case"EVENT":{const o=this.openSubs.get(s[1]),i=s[2];this.verifyEvent(i)&&To(o.filters,i)&&o.onevent(i);return}case"COUNT":{const o=s[1],i=s[2],c=this.openCountRequests.get(o);c&&(c.resolve(i.count),this.openCountRequests.delete(o));return}case"EOSE":{const o=this.openSubs.get(s[1]);if(!o)return;o.receivedEose();return}case"OK":{const o=s[1],i=s[2],c=s[3],a=this.openEventPublishes.get(o);i?a.resolve(c):a.reject(new Error(c)),this.openEventPublishes.delete(o);return}case"CLOSED":{const o=s[1],i=this.openSubs.get(o);if(!i)return;i.closed=!0,i.close(s[2]);return}case"NOTICE":this.onnotice(s[1]);return;case"AUTH":{this.challenge=s[1];return}}}catch{return}}async send(t){if(!this.connectionPromise)throw new Error("sending on closed connection");this.connectionPromise.then(()=>{var e;(e=this.ws)==null||e.send(t)})}async auth(t){if(!this.challenge)throw new Error("can't perform auth, no challenge was received");const e=await t(Po(this.url,this.challenge)),n=new Promise((r,s)=>{this.openEventPublishes.set(e.id,{resolve:r,reject:s})});return this.send('["AUTH",'+JSON.stringify(e)+"]"),n}async publish(t){const e=new Promise((n,r)=>{this.openEventPublishes.set(t.id,{resolve:n,reject:r})});return this.send('["EVENT",'+JSON.stringify(t)+"]"),e}async count(t,e){this.serial++;const n=(e==null?void 0:e.id)||"count:"+this.serial,r=new Promise((s,o)=>{this.openCountRequests.set(n,{resolve:s,reject:o})});return this.send('["COUNT","'+n+'",'+JSON.stringify(t)+"]"),r}subscribe(t,e){const n=this.prepareSubscription(t,e);return n.fire(),n}prepareSubscription(t,e){this.serial++;const n=e.id||"sub:"+this.serial,r=new Ho(this,n,t,e);return this.openSubs.set(n,r),r}close(){var t;this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,(t=this.ws)==null||t.close()}_onmessage(t){this.incomingMessageQueue.enqueue(t.data),this.queueRunning||this.runQueue()}},Ho=class{constructor(t,e,n,r){b(this,"relay");b(this,"id");b(this,"closed",!1);b(this,"eosed",!1);b(this,"filters");b(this,"alreadyHaveEvent");b(this,"receivedEvent");b(this,"onevent");b(this,"oneose");b(this,"onclose");b(this,"eoseTimeout");b(this,"eoseTimeoutHandle");this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.onevent=r.onevent||(s=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,s)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){var t;this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,(t=this.oneose)==null||t.call(this))}close(t="closed by caller"){var e;this.closed||(this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]"),this.closed=!0),this.relay.openSubs.delete(this.id),(e=this.onclose)==null||e.call(this,t)}},Lo=class{constructor(t){b(this,"relays",new Map);b(this,"seenOn",new Map);b(this,"trackRelays",!1);b(this,"verifyEvent");b(this,"trustedRelayURLs",new Set);this.verifyEvent=t.verifyEvent}async ensureRelay(t,e){t=Ge(t);let n=this.relays.get(t);return n||(n=new Xn(t,{verifyEvent:this.trustedRelayURLs.has(t)?Uo:this.verifyEvent}),e!=null&&e.connectionTimeout&&(n.connectionTimeout=e.connectionTimeout),this.relays.set(t,n)),await n.connect(),n}close(t){t.map(Ge).forEach(e=>{var n;(n=this.relays.get(e))==null||n.close()})}subscribeMany(t,e,n){this.trackRelays&&(n.receivedEvent=(l,h)=>{let w=this.seenOn.get(h);w||(w=new Set,this.seenOn.set(h,w)),w.add(l)});const r=new Set,s=[],o=[];let i=l=>{var h;o[l]=!0,o.filter(w=>w).length===t.length&&((h=n.oneose)==null||h.call(n),i=()=>{})};const c=[];let a=(l,h)=>{var w;i(l),c[l]=h,c.filter(g=>g).length===t.length&&((w=n.onclose)==null||w.call(n,c),a=()=>{})};const u=l=>{var w;if((w=n.alreadyHaveEvent)!=null&&w.call(n,l))return!0;const h=r.has(l);return r.add(l),h},f=Promise.all(t.map(Ge).map(async(l,h,w)=>{if(w.indexOf(l)!==h){a(h,"duplicate url");return}let g;try{g=await this.ensureRelay(l,{connectionTimeout:n.maxWait?Math.max(n.maxWait*.8,n.maxWait-1e3):void 0})}catch(p){a(h,(p==null?void 0:p.message)||String(p));return}let d=g.subscribe(e,{...n,oneose:()=>i(h),onclose:p=>a(h,p),alreadyHaveEvent:u,eoseTimeout:n.maxWait});s.push(d)}));return{async close(){await f,s.forEach(l=>{l.close()})}}}subscribeManyEose(t,e,n){const r=this.subscribeMany(t,e,{...n,oneose(){r.close()}});return r}async querySync(t,e,n){return new Promise(async r=>{const s=[];this.subscribeManyEose(t,[e],{...n,onevent(o){s.push(o)},onclose(o){r(s)}})})}async get(t,e,n){e.limit=1;const r=await this.querySync(t,e,n);return r.sort((s,o)=>o.created_at-s.created_at),r[0]||null}publish(t,e){return t.map(Ge).map(async(n,r,s)=>s.indexOf(n)!==r?Promise.reject("duplicate url"):(await this.ensureRelay(n)).publish(e))}},qo=class extends Lo{constructor(){super({verifyEvent:Jn})}},er;try{er=fetch}catch{}var Mo=/^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%]*)$/,Ko=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;async function jo(t){let e=t.match(Mo);if(e)try{const n=e[1],r=new URLSearchParams(e[2]);return{pubkey:n,relays:r.getAll("relay"),secret:r.get("secret")}}catch{}return tr(t)}async function tr(t){const e=t.match(ko);if(!e)return null;const[n,r="_",s]=e;try{const o=`https://${s}/.well-known/nostr.json?name=${r}`,i=await(await er(o,{redirect:"error"})).json();let c=i.names[r],a=i.nip46[c]||[];return{pubkey:c,relays:a,secret:null}}catch{return null}}var Ft=class{constructor(t,e,n={}){b(this,"pool");b(this,"subCloser");b(this,"isOpen");b(this,"serial");b(this,"idPrefix");b(this,"listeners");b(this,"waitingForAuth");b(this,"secretKey");b(this,"bp");if(e.relays.length===0)throw new Error("no relays are specified for this bunker");this.pool=n.pool||new qo,this.secretKey=t,this.bp=e,this.isOpen=!1,this.idPrefix=Math.random().toString(36).substring(7),this.serial=0,this.listeners={},this.waitingForAuth={};const r=this.listeners,s=this.waitingForAuth;this.subCloser=this.pool.subscribeMany(this.bp.relays,[{kinds:[Wt],"#p":[Zn(this.secretKey)]}],{async onevent(o){const{id:i,result:c,error:a}=JSON.parse(await Ao(t,o.pubkey,o.content));if(c==="auth_url"&&s[i]){delete r[i],n.onauth?n.onauth(a):console.warn(`nostr-tools/nip46: remote signer ${e.pubkey} tried to send an "auth_url"='${a}' but there was no onauth() callback configured.`);return}let u=r[i];u&&(a?u.reject(a):c&&u.resolve(c),delete r[i])}}),this.isOpen=!0}async close(){this.isOpen=!1,this.subCloser.close()}async sendRequest(t,e){return new Promise(async(n,r)=>{try{if(!this.isOpen)throw new Error("this signer is not open anymore, create a new one");this.serial++;const s=`${this.idPrefix}-${this.serial}`,o=await _o(this.secretKey,this.bp.pubkey,JSON.stringify({id:s,method:t,params:e})),i=So({kind:Wt,tags:[["p",this.bp.pubkey]],content:o,created_at:Math.floor(Date.now()/1e3)},this.secretKey);this.listeners[s]={resolve:n,reject:r},this.waitingForAuth[s]=!0,await Promise.any(this.pool.publish(this.bp.relays,i))}catch(s){r(s)}})}async ping(){let t=await this.sendRequest("ping",[]);if(t!=="pong")throw new Error(`result is not pong: ${t}`)}async connect(){await this.sendRequest("connect",[Zn(this.secretKey),this.bp.secret||""])}async getPublicKey(){return this.bp.pubkey}async getRelays(){return JSON.parse(await this.sendRequest("get_relays",[]))}async signEvent(t){let e=await this.sendRequest("sign_event",[JSON.stringify(t)]),n=JSON.parse(e);if(n.pubkey===this.bp.pubkey&&Jn(n))return n;throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(n)}`)}async nip04Encrypt(t,e){return await this.sendRequest("nip04_encrypt",[t,e])}async nip04Decrypt(t,e){return await this.sendRequest("nip04_decrypt",[t,e])}async nip44GetKey(t){let e=await this.sendRequest("nip44_get_key",[t]);return gt(e)}async nip44Encrypt(t,e){return await this.sendRequest("nip44_encrypt",[t,e])}async nip44Decrypt(t,e){return await this.sendRequest("nip44_encrypt",[t,e])}};async function zo(t,e,n,r,s){if(s&&!Ko.test(s))throw new Error("Invalid email");let o=vo(),i=new Ft(o,t.bunkerPointer,e),c=await i.sendRequest("create_account",[n,r,s||""]);return i.bp.pubkey=c,await i.connect(),i}async function Vo(t,e){const n=await t.querySync(e,{kinds:[Oo],"#k":[Wt.toString()]});return(await Promise.all(n.map(async s=>{try{const o=JSON.parse(s.content),i=await tr(o.nip05);if(i&&i.pubkey===s.pubkey&&i.relays.length)return{bunkerPointer:i,nip05:o.nip05,domain:o.nip05.split("@")[1],name:o.name||o.display_name,picture:o.picture,about:o.about,website:o.website,local:!1}}catch{return}}))).filter(s=>s!==void 0)}var Do=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,nr;try{nr=fetch}catch{}async function Wo(t){var o;const e=t.match(Do);if(!e)return null;const[n,r="_",s]=e;try{const i=`https://${s}/.well-known/nostr.json?name=${r}`,c=await(await nr(i,{redirect:"error"})).json();let a=c.names[r];return a?{pubkey:a,relays:(o=c.relays)==null?void 0:o[a]}:null}catch{return null}}new TextDecoder("utf-8"),new TextEncoder;var Fo=5e3;function Go(t){return Jo("npub",gt(t))}function Zo(t,e){let n=Fn.toWords(e);return Fn.encode(t,n,Fo)}function Jo(t,e){return Zo(t,e)}const{window:Yo}=ur;function rr(t,e,n){const r=t.slice();return r[28]=e[n],r}function Qo(t){let e;function n(o,i){if(o[5])return ni;if(!o[6])return ti;if(o[6])return ei}let r=n(t),s=r&&r(t);return{c(){e=P("div"),s&&s.c(),T(e,"class","tw-w-80 tw-px-6 tw-py-6 tw-transition-all tw-bg-cyan-700 tw-shadow-xl tw-rounded-md")},m(o,i){H(o,e,i),s&&s.m(e,null)},p(o,i){r===(r=n(o))&&s?s.p(o,i):(s&&s.d(1),s=r&&r(o),s&&(s.c(),s.m(e,null)))},d(o){o&&U(e),s&&s.d()}}}function Xo(t){let e;function n(o,i){return o[4]?oi:o[6]?ri:si}let r=n(t),s=r(t);return{c(){e=P("div"),s.c(),T(e,"class","tw-px-4 tw-py-2 tw-transition-all tw-bg-cyan-700 hover:tw-bg-cyan-800 tw-shadow-xl tw-rounded tw-cursor-pointer")},m(o,i){H(o,e,i),s.m(e,null)},p(o,i){r===(r=n(o))&&s?s.p(o,i):(s.d(1),s=r(o),s&&(s.c(),s.m(e,null)))},d(o){o&&U(e),s.d()}}}function ei(t){let e,n,r,s,o=t[6].npub+"",i,c,a,u,f,l;return{c(){e=P("div"),n=P("div"),n.textContent="You are currently connect to Nostr as",r=se(),s=P("a"),i=$e(o),a=se(),u=P("button"),u.textContent="Disconnect",T(n,"class","tw-text-xs"),T(s,"target","_blank"),T(s,"href",c="https://nosta.me/"+t[6].npub),T(s,"class","tw-block tw-text-white tw-mt-4 tw-break-all tw-no-underline hover:tw-underline"),T(e,"class","tw-text-center"),T(u,"class","tw-block tw-w-full tw-my-2 tw-mt-4 tw-px-2 tw-py-1 tw-text-lg tw-rounded tw-border-0 tw-bg-cyan-900 hover:tw-bg-cyan-950 tw-hover:bg-indigo-900 tw-cursor-pointer tw-text-white")},m(h,w){H(h,e,w),M(e,n),M(e,r),M(e,s),M(s,i),H(h,a,w),H(h,u,w),f||(l=Ee(u,"click",t[10]),f=!0)},p(h,w){w&64&&o!==(o=h[6].npub+"")&&Yt(i,o),w&64&&c!==(c="https://nosta.me/"+h[6].npub)&&T(s,"href",c)},d(h){h&&(U(e),U(a),U(u)),f=!1,l()}}}function ti(t){let e,n,r,s,o,i,c,a,u,f,l,h;return{c(){e=P("div"),e.textContent="How do you want to connect to Nostr?",n=se(),r=P("form"),s=P("input"),o=se(),i=P("button"),i.textContent="Connect »",c=se(),a=P("div"),u=$e(`Do you need a Nostr account?
3
+ `),f=P("button"),f.textContent="Get one now for free",T(e,"class","tw-text-lg tw-text-center"),T(s,"class","tw-box-border tw-w-full tw-px-2 tw-py-1 tw-rounded tw-text-lg tw-border-none tw-outline-none"),T(s,"placeholder","user@provider or bunker://..."),T(i,"class","tw-block tw-w-full tw-mt-4 tw-px-2 tw-py-1 tw-text-lg tw-rounded tw-border-0 tw-bg-cyan-900 hover:tw-bg-cyan-950 tw-hover:bg-indigo-900 tw-cursor-pointer tw-text-white"),T(r,"class","flex tw-mt-4 tw-mb-1"),T(f,"class","tw-border-0 tw-bg-transparent tw-text-white tw-cursor-pointer tw-underline tw-text-sm"),T(a,"class","tw-mt-6 tw-text-center tw-text-sm tw-leading-3")},m(w,g){H(w,e,g),H(w,n,g),H(w,r,g),M(r,s),t[16](s),M(r,o),M(r,i),H(w,c,g),H(w,a,g),M(a,u),M(a,f),l||(h=[Ee(r,"submit",t[9]),Ee(f,"click",t[11])],l=!0)},p:j,d(w){w&&(U(e),U(n),U(r),U(c),U(a)),t[16](null),l=!1,Be(h)}}}function ni(t){let e,n,r,s,o,i,c,a,u,f,l,h,w,g=rn(t[7]),d=[];for(let p=0;p<g.length;p+=1)d[p]=sr(rr(t,g,p));return{c(){e=P("div"),e.textContent="Create a new Nostr account",n=se(),r=P("form"),s=P("div"),o=P("input"),i=se(),c=P("div"),c.textContent="@",a=se(),u=P("select");for(let p=0;p<d.length;p+=1)d[p].c();f=se(),l=P("button"),l.textContent="create",T(e,"class","tw-text-lg tw-text-center"),T(o,"class","tw-box-border tw-w-full tw-px-2 tw-py-1 tw-rounded tw-text-lg tw-border-none tw-outline-none"),T(o,"placeholder","bob"),T(c,"class","tw-mx-2 tw-text-2xl"),T(u,"class","tw-w-full tw-box-border tw-px-2 tw-py-1 tw-rounded tw-text-lg tw-border-none tw-outline-none"),t[2]===void 0&&Ye(()=>t[15].call(u)),T(s,"class","tw-flex items-center"),T(l,"class","tw-block tw-w-full tw-mt-4 tw-px-2 tw-py-1 tw-text-lg tw-rounded tw-border-0 tw-bg-cyan-900 hover:tw-bg-cyan-950 tw-hover:bg-indigo-900 tw-cursor-pointer tw-text-white"),T(r,"class","tw-mt-4 tw-mb-1")},m(p,m){H(p,e,m),H(p,n,m),H(p,r,m),M(r,s),M(s,o),t[14](o),M(s,i),M(s,c),M(s,a),M(s,u);for(let x=0;x<d.length;x+=1)d[x]&&d[x].m(u,null);Xt(u,t[2],!0),M(r,f),M(r,l),h||(w=[Ee(o,"input",t[13]),Ee(u,"change",t[15]),Ee(r,"submit",t[12])],h=!0)},p(p,m){if(m&128){g=rn(p[7]);let x;for(x=0;x<g.length;x+=1){const S=rr(p,g,x);d[x]?d[x].p(S,m):(d[x]=sr(S),d[x].c(),d[x].m(u,null))}for(;x<d.length;x+=1)d[x].d(1);d.length=g.length}m&132&&Xt(u,p[2])},d(p){p&&(U(e),U(n),U(r)),t[14](null),fr(d,p),h=!1,Be(w)}}}function sr(t){let e,n,r;return{c(){e=P("option"),T(e,"label",n=t[28].domain),e.__value=r=t[28],Qt(e,e.__value),T(e,"class","tw-px-2 tw-py-1 tw-text-lg")},m(s,o){H(s,e,o)},p(s,o){o&128&&n!==(n=s[28].domain)&&T(e,"label",n),o&128&&r!==(r=s[28])&&(e.__value=r,Qt(e,e.__value))},d(s){s&&U(e)}}}function ri(t){let e,n=(t[6].name||t[6].npub.slice(0,7)+"…"+t[6].npub.slice(-4))+"",r;return{c(){e=$e("☉ "),r=$e(n)},m(s,o){H(s,e,o),H(s,r,o)},p(s,o){o&64&&n!==(n=(s[6].name||s[6].npub.slice(0,7)+"…"+s[6].npub.slice(-4))+"")&&Yt(r,n)},d(s){s&&(U(e),U(r))}}}function si(t){let e;return{c(){e=$e("Login with Nostr")},m(n,r){H(n,e,r)},p:j,d(n){n&&U(e)}}}function oi(t){let e;return{c(){e=P("div"),e.textContent="Connecting to bunker..."},m(n,r){H(n,e,r)},p:j,d(n){n&&U(e)}}}function ii(t){let e,n,r;function s(c,a){return c[3]?Qo:Xo}let o=s(t),i=o(t);return{c(){e=P("div"),i.c(),T(e,"class","tw-text-white tw-font-sans"),en(e,"tw-cursor-pointer",!t[6]&&!t[3])},m(c,a){H(c,e,a),i.m(e,null),n||(r=Ee(Yo,"click",t[8]),n=!0)},p(c,[a]){o===(o=s(c))&&i?i.p(c,a):(i.d(1),i=o(c),i&&(i.c(),i.m(e,null))),a&72&&en(e,"tw-cursor-pointer",!c[6]&&!c[3])},i:j,o:j,d(c){c&&U(e),i.d(),n=!1,r()}}}function ci(t,e,n){const r=window,s=new io;let o,i,c,a;const u=localStorage.getItem("nip46ClientSecretKey");u?a=gt(u):(a=Ks(),localStorage.setItem("nip46ClientSecretKey",V(a)));let f,l,h,w,g,d,p,m,x=[];S();function S(){n(3,f=!1),l=null,w=new Promise(y=>{h=y}),n(4,g=!1),n(5,d=!1),n(6,p=null),m=null}const $={pool:s,onauth(y){window.open(y,"window.nostr","width=600,height=800,popup=yes")}};pr(()=>{let y=localStorage.getItem("nip46BunkerPointer");return y&&(l=JSON.parse(y),n(4,g=!0),O(new Ft(a,l,$))),setTimeout(()=>{if(r.nostr&&!r.nostr.isWnj){r.destroyWnj();return}else r.nostr={isWnj:!0,async getPublicKey(){return g||n(3,f=!0),(await w).bp.pubkey},async signEvent(E){return g||n(3,f=!0),(await w).signEvent(E)}}},3e3),()=>{m&&m.close()}});function B(y){y.composedPath().find(E=>E.id==="windowNostrModal")?n(3,f=!0):n(3,f=!1)}async function v(y){if(y.preventDefault(),l=await jo(o.value),!l){o.setCustomValidity('invalid NIP-05 "name@domain.com" address or bunker:// URI');return}o.setCustomValidity(""),O(new Ft(a,l,$))}async function _(y){y.preventDefault(),localStorage.removeItem("nip46BunkerPointer"),r.isWnj&&delete r.nostr,S()}async function k(y){y.preventDefault(),n(5,d=!0),x.length===0&&n(7,x=await Vo(s,["wss://relay.nostr.band"]))}async function Z(y){if(y.preventDefault(),!c)return;let E=await zo(c,$,i.value,c.domain);n(3,f=!0),n(5,d=!1),O(E)}const C=Ir(async()=>{c&&i.value.length>0&&(await Wo(i.value+"@"+c.domain)?i.setCustomValidity(`'${i.value}' is already taken.`):i.setCustomValidity(""))},500);async function O(y){await y.connect(),n(6,p={pubkey:y.bp.pubkey,npub:Go(y.bp.pubkey),event:null}),n(4,g=!1),localStorage.setItem("nip46BunkerPointer",JSON.stringify(l)),m=s.subscribeMany(["wss://purplepag.es","wss://relay.snort.social","wss://relay.nos.social"],[{kinds:[0],authors:[y.bp.pubkey]}],{onevent(E){var A;if(!((((A=p.event)==null?void 0:A.created_at)||0)>=E.created_at))try{let{name:N,picture:I}=JSON.parse(E.content);n(6,p.event=E,p),n(6,p.name=N,p),n(6,p.picture=I,p)}catch{}}}),n(3,f=!1),h(y)}function W(y){Je[y?"unshift":"push"](()=>{i=y,n(1,i)})}function F(){c=hr(this),n(2,c),n(7,x)}function re(y){Je[y?"unshift":"push"](()=>{o=y,n(0,o)})}return[o,i,c,f,g,d,p,x,B,v,_,k,Z,C,W,F,re]}class ai extends kr{constructor(e){super(),Ar(this,e,ci,ii,ar,{})}}const ft=document.createElement("div");document.body.appendChild(ft),ft.id="windowNostrModal",ft.classList.add("tw-fixed","tw-top-6","tw-right-6");const li=new ai({target:ft});window.destroyWnj=()=>{li.$destroy()}})();
package/index.html ADDED
@@ -0,0 +1,65 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>dev</title>
7
+ </head>
8
+ <body
9
+ style="
10
+ margin: 0;
11
+ padding: 1em 3em;
12
+ background-color: #333;
13
+ color: white;
14
+ font-size: 18px;
15
+ "
16
+ >
17
+ <main>
18
+ <h1>App Title</h1>
19
+ <p>
20
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et ex dui.
21
+ Donec eu dui sed massa auctor rhoncus. Nunc mollis, metus nec
22
+ sollicitudin ultricies, nibh diam accumsan eros, sit amet efficitur
23
+ lectus dui sit amet dolor. Donec commodo velit id nibh pharetra, at
24
+ fermentum velit mollis. Duis eu libero varius, ullamcorper tortor id,
25
+ pharetra neque. Nulla a pretium est. Sed imperdiet ultrices volutpat.
26
+ Sed quam arcu, aliquam eget diam et, pretium sagittis risus. Donec
27
+ finibus sapien id orci sollicitudin gravida. Vivamus et dui faucibus,
28
+ blandit nisl vitae, consectetur risus. Pellentesque vehicula dignissim
29
+ maximus. Donec pellentesque, sapien id sollicitudin bibendum, est magna
30
+ pretium ex, nec dignissim quam ante at mauris. Quisque sed scelerisque
31
+ nulla. Vestibulum lobortis orci vitae gravida posuere. Integer sed sem
32
+ diam. Maecenas bibendum ligula non metus faucibus, vitae pellentesque
33
+ nisi condimentum. Suspendisse vehicula ullamcorper nisi, ut rutrum dolor
34
+ mollis sit amet. Cras sit amet mi sit amet eros convallis pulvinar.
35
+ Donec condimentum condimentum tincidunt.
36
+ </p>
37
+
38
+ <p>
39
+ Suspendisse eu ipsum vel lorem congue mattis in at neque. Phasellus nec
40
+ felis sit amet nibh bibendum tristique a quis urna. Pellentesque laoreet
41
+ porta libero eget pellentesque. Praesent tempor, nisi et efficitur
42
+ cursus, leo nunc ullamcorper ante, quis eleifend velit justo sed enim.
43
+ Maecenas laoreet dictum lorem rhoncus tempus. Integer ipsum augue,
44
+ sagittis a facilisis et, mollis ut ipsum. Proin elementum consectetur
45
+ tincidunt.
46
+ </p>
47
+
48
+ <p>
49
+ Mauris nec mi et quam semper volutpat. Morbi suscipit felis lectus, in
50
+ ornare purus pretium in. Maecenas et ex metus. Ut aliquam, felis vel
51
+ mollis dapibus, tellus velit blandit dui, eu hendrerit tellus magna at
52
+ eros. Donec scelerisque hendrerit auctor. Aenean aliquet sapien
53
+ elementum dui sagittis eleifend. Donec hendrerit odio et dui lacinia
54
+ aliquet. Morbi auctor ultrices dui fringilla elementum. Curabitur
55
+ scelerisque lorem vitae placerat vulputate. Donec vestibulum urna sem,
56
+ at sodales ligula laoreet id. Etiam vehicula, lorem id tincidunt
57
+ sodales, sem odio vehicula ex, vel condimentum quam augue id augue.
58
+ Integer a varius nunc. Mauris rhoncus leo sed facilisis bibendum. Nullam
59
+ consectetur pellentesque vestibulum. Cras hendrerit feugiat orci, in
60
+ molestie risus rutrum ut. Proin dictum nunc at rutrum vehicula.
61
+ </p>
62
+ </main>
63
+ <script type="module" src="/src/main.ts"></script>
64
+ </body>
65
+ </html>
package/justfile ADDED
@@ -0,0 +1,15 @@
1
+ export PATH := "./node_modules/.bin:" + env_var('PATH')
2
+
3
+ dev:
4
+ vite
5
+
6
+ build:
7
+ vite build
8
+ mv dist/assets/*.js dist/window.nostr.js
9
+
10
+ demo:
11
+ xdg-open demo/index.html
12
+
13
+ publish:
14
+ just build
15
+ npm publish
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "window.nostr.js",
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "devDependencies": {
6
+ "@sveltejs/vite-plugin-svelte": "^3.0.2",
7
+ "@tsconfig/svelte": "^5.0.2",
8
+ "@typescript-eslint/eslint-plugin": "^7.0.1",
9
+ "autoprefixer": "^10.4.17",
10
+ "eslint-config-prettier": "^9.1.0",
11
+ "eslint-plugin-svelte": "^2.35.1",
12
+ "postcss": "^8.4.35",
13
+ "prettier": "^3.2.5",
14
+ "prettier-plugin-svelte": "^3.2.0",
15
+ "prettier-plugin-tailwindcss": "^0.5.11",
16
+ "svelte": "^4.2.10",
17
+ "svelte-check": "^3.6.3",
18
+ "tailwindcss": "^3.4.1",
19
+ "tslib": "^2.6.2",
20
+ "typescript": "^5.2.2",
21
+ "vite": "^5.1.0"
22
+ },
23
+ "dependencies": {
24
+ "debounce": "^2.0.0",
25
+ "nostr-tools": "^2.2.1"
26
+ }
27
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ }
package/src/App.svelte ADDED
@@ -0,0 +1,310 @@
1
+ <script lang="ts">
2
+ import debounce from 'debounce'
3
+ import {hexToBytes, bytesToHex} from '@noble/hashes/utils'
4
+ import {
5
+ generateSecretKey,
6
+ type VerifiedEvent,
7
+ type NostrEvent
8
+ } from 'nostr-tools/pure'
9
+ import {SimplePool, type SubCloser} from 'nostr-tools/pool'
10
+ import {
11
+ BunkerSigner,
12
+ type BunkerSignerParams,
13
+ createAccount,
14
+ parseBunkerInput,
15
+ fetchCustodialBunkers,
16
+ type BunkerPointer,
17
+ type BunkerProfile
18
+ } from 'nostr-tools/nip46'
19
+ import {queryProfile} from 'nostr-tools/nip05'
20
+ import {npubEncode} from 'nostr-tools/nip19'
21
+ import {onMount} from 'svelte'
22
+
23
+ const win = window as any
24
+ const pool = new SimplePool()
25
+ let bunkerInput: HTMLInputElement
26
+ let nameInput: HTMLInputElement
27
+ let chosenProvider: BunkerProfile | undefined
28
+ let clientSecret: Uint8Array
29
+ const local = localStorage.getItem('nip46ClientSecretKey')
30
+ if (local) {
31
+ clientSecret = hexToBytes(local)
32
+ } else {
33
+ clientSecret = generateSecretKey()
34
+ localStorage.setItem('nip46ClientSecretKey', bytesToHex(clientSecret))
35
+ }
36
+
37
+ let opened: Boolean
38
+ let bunkerPointer: BunkerPointer | null
39
+ let resolveBunker: (_: BunkerSigner) => void
40
+ let bunker: Promise<BunkerSigner>
41
+ let connecting: boolean
42
+ let creating: boolean
43
+ let connected: null | {
44
+ pubkey: string
45
+ npub: string
46
+ name?: string
47
+ picture?: string
48
+ event: NostrEvent | null
49
+ }
50
+ let metadataSub: SubCloser | null
51
+ let providers: BunkerProfile[] = []
52
+ reset()
53
+
54
+ function reset() {
55
+ opened = false
56
+ bunkerPointer = null
57
+ bunker = new Promise(resolve => {
58
+ resolveBunker = resolve
59
+ })
60
+ connecting = false
61
+ creating = false
62
+ connected = null
63
+ metadataSub = null
64
+ }
65
+
66
+ const bunkerSignerParams: BunkerSignerParams = {
67
+ pool,
68
+ onauth(url: string) {
69
+ window.open(url, 'window.nostr', `width=600,height=800,popup=yes`)
70
+ }
71
+ }
72
+
73
+ onMount(() => {
74
+ let data = localStorage.getItem('nip46BunkerPointer')
75
+ if (data) {
76
+ bunkerPointer = JSON.parse(data)
77
+ connecting = true
78
+ connect(
79
+ new BunkerSigner(clientSecret, bunkerPointer!, bunkerSignerParams)
80
+ )
81
+ }
82
+
83
+ setTimeout(() => {
84
+ if (win.nostr && !win.nostr.isWnj) {
85
+ win.destroyWnj()
86
+ return
87
+ } else {
88
+ win.nostr = {
89
+ isWnj: true,
90
+ async getPublicKey(): Promise<string> {
91
+ if (!connecting) opened = true
92
+ return (await bunker).bp.pubkey
93
+ },
94
+ async signEvent(event: NostrEvent): Promise<VerifiedEvent> {
95
+ if (!connecting) opened = true
96
+ return (await bunker).signEvent(event)
97
+ }
98
+ }
99
+ }
100
+ }, 3000)
101
+
102
+ return () => {
103
+ if (metadataSub) metadataSub.close()
104
+ }
105
+ })
106
+
107
+ function handleClick(ev: MouseEvent) {
108
+ if (ev.composedPath().find((el: any) => el.id === 'windowNostrModal'))
109
+ opened = true
110
+ else opened = false
111
+ }
112
+
113
+ async function handleConnect(ev: SubmitEvent) {
114
+ ev.preventDefault()
115
+ bunkerPointer = await parseBunkerInput(bunkerInput.value)
116
+ if (!bunkerPointer) {
117
+ bunkerInput.setCustomValidity(
118
+ 'invalid NIP-05 "name@domain.com" address or bunker:// URI'
119
+ )
120
+ return
121
+ }
122
+
123
+ bunkerInput.setCustomValidity('')
124
+ connect(new BunkerSigner(clientSecret, bunkerPointer!, bunkerSignerParams))
125
+ }
126
+
127
+ async function handleDisconnect(ev: MouseEvent) {
128
+ ev.preventDefault()
129
+ localStorage.removeItem('nip46BunkerPointer')
130
+ if (win.isWnj) delete win.nostr
131
+ reset()
132
+ }
133
+
134
+ async function handleOpenCreate(ev: MouseEvent) {
135
+ ev.preventDefault()
136
+ creating = true
137
+ if (providers.length === 0)
138
+ providers = await fetchCustodialBunkers(pool, ['wss://relay.nostr.band'])
139
+ }
140
+
141
+ async function handleCreate(ev: SubmitEvent) {
142
+ ev.preventDefault()
143
+ if (!chosenProvider) return
144
+
145
+ let bunker = await createAccount(
146
+ chosenProvider,
147
+ bunkerSignerParams,
148
+ nameInput.value,
149
+ chosenProvider.domain
150
+ )
151
+ opened = true
152
+ creating = false
153
+
154
+ connect(bunker)
155
+ }
156
+
157
+ const checkNameInput = debounce(async () => {
158
+ if (chosenProvider && nameInput.value.length > 0) {
159
+ if (await queryProfile(nameInput.value + '@' + chosenProvider.domain)) {
160
+ nameInput.setCustomValidity(`'${nameInput.value}' is already taken.`)
161
+ } else {
162
+ nameInput.setCustomValidity('')
163
+ }
164
+ }
165
+ }, 500)
166
+
167
+ async function connect(bunker: BunkerSigner) {
168
+ await bunker.connect()
169
+
170
+ // set this so the floating thing will update
171
+ connected = {
172
+ pubkey: bunker.bp.pubkey,
173
+ npub: npubEncode(bunker.bp.pubkey),
174
+ event: null
175
+ }
176
+ connecting = false
177
+
178
+ localStorage.setItem('nip46BunkerPointer', JSON.stringify(bunkerPointer))
179
+
180
+ // load metadata
181
+ metadataSub = pool.subscribeMany(
182
+ [
183
+ 'wss://purplepag.es',
184
+ 'wss://relay.snort.social',
185
+ 'wss://relay.nos.social'
186
+ ],
187
+ [{kinds: [0], authors: [bunker.bp.pubkey]}],
188
+ {
189
+ onevent(evt) {
190
+ if ((connected!.event?.created_at || 0) >= evt.created_at) return
191
+ try {
192
+ let {name, picture} = JSON.parse(evt.content)
193
+ connected!.event = evt
194
+ connected!.name = name
195
+ connected!.picture = picture
196
+ } catch (err) {
197
+ /***/
198
+ }
199
+ }
200
+ }
201
+ )
202
+
203
+ opened = false
204
+ resolveBunker(bunker)
205
+ }
206
+ </script>
207
+
208
+ <svelte:window on:click={handleClick} />
209
+
210
+ <div
211
+ class="tw-text-white tw-font-sans"
212
+ class:tw-cursor-pointer={!connected && !opened}
213
+ >
214
+ <!-- Close status ################### -->
215
+ {#if !opened}
216
+ <div
217
+ class="tw-px-4 tw-py-2 tw-transition-all tw-bg-cyan-700 hover:tw-bg-cyan-800 tw-shadow-xl tw-rounded tw-cursor-pointer"
218
+ >
219
+ <!-- Connecting view ################### -->
220
+ {#if connecting}
221
+ <div>Connecting to bunker...</div>
222
+ {:else if !connected}
223
+ Login with Nostr
224
+ {:else}
225
+ ☉ {connected.name ||
226
+ connected.npub.slice(0, 7) + '…' + connected.npub.slice(-4)}
227
+ {/if}
228
+ </div>
229
+
230
+ <!-- Open status ################### -->
231
+ {:else}
232
+ <div
233
+ class="tw-w-80 tw-px-6 tw-py-6 tw-transition-all tw-bg-cyan-700 tw-shadow-xl tw-rounded-md"
234
+ >
235
+ <!-- Create account view ################### -->
236
+ {#if creating}
237
+ <div class="tw-text-lg tw-text-center">Create a new Nostr account</div>
238
+ <form class="tw-mt-4 tw-mb-1" on:submit={handleCreate}>
239
+ <div class="tw-flex items-center">
240
+ <input
241
+ class="tw-box-border tw-w-full tw-px-2 tw-py-1 tw-rounded tw-text-lg tw-border-none tw-outline-none"
242
+ placeholder="bob"
243
+ bind:this={nameInput}
244
+ on:input={checkNameInput}
245
+ />
246
+ <div class="tw-mx-2 tw-text-2xl">@</div>
247
+ <select
248
+ class="tw-w-full tw-box-border tw-px-2 tw-py-1 tw-rounded tw-text-lg tw-border-none tw-outline-none"
249
+ bind:value={chosenProvider}
250
+ >
251
+ {#each providers as prov}
252
+ <option
253
+ label={prov.domain}
254
+ value={prov}
255
+ class="tw-px-2 tw-py-1 tw-text-lg"
256
+ />
257
+ {/each}
258
+ </select>
259
+ </div>
260
+ <button
261
+ class="tw-block tw-w-full tw-mt-4 tw-px-2 tw-py-1 tw-text-lg tw-rounded tw-border-0 tw-bg-cyan-900 hover:tw-bg-cyan-950 tw-hover:bg-indigo-900 tw-cursor-pointer tw-text-white"
262
+ >
263
+ create
264
+ </button>
265
+ </form>
266
+
267
+ <!-- Login view ################### -->
268
+ {:else if !connected}
269
+ <div class="tw-text-lg tw-text-center">
270
+ How do you want to connect to Nostr?
271
+ </div>
272
+ <form class="flex tw-mt-4 tw-mb-1" on:submit={handleConnect}>
273
+ <input
274
+ class="tw-box-border tw-w-full tw-px-2 tw-py-1 tw-rounded tw-text-lg tw-border-none tw-outline-none"
275
+ placeholder="user@provider or bunker://..."
276
+ bind:this={bunkerInput}
277
+ />
278
+ <button
279
+ class="tw-block tw-w-full tw-mt-4 tw-px-2 tw-py-1 tw-text-lg tw-rounded tw-border-0 tw-bg-cyan-900 hover:tw-bg-cyan-950 tw-hover:bg-indigo-900 tw-cursor-pointer tw-text-white"
280
+ >
281
+ Connect »
282
+ </button>
283
+ </form>
284
+ <div class="tw-mt-6 tw-text-center tw-text-sm tw-leading-3">
285
+ Do you need a Nostr account?
286
+ <button
287
+ class="tw-border-0 tw-bg-transparent tw-text-white tw-cursor-pointer tw-underline tw-text-sm"
288
+ on:click={handleOpenCreate}>Get one now for free</button
289
+ >
290
+ </div>
291
+
292
+ <!-- Connected view ################### -->
293
+ {:else if connected}
294
+ <div class="tw-text-center">
295
+ <div class="tw-text-xs">You are currently connect to Nostr as</div>
296
+ <a
297
+ target="_blank"
298
+ href={'https://nosta.me/' + connected.npub}
299
+ class="tw-block tw-text-white tw-mt-4 tw-break-all tw-no-underline hover:tw-underline"
300
+ >{connected.npub}</a
301
+ >
302
+ </div>
303
+ <button
304
+ class="tw-block tw-w-full tw-my-2 tw-mt-4 tw-px-2 tw-py-1 tw-text-lg tw-rounded tw-border-0 tw-bg-cyan-900 hover:tw-bg-cyan-950 tw-hover:bg-indigo-900 tw-cursor-pointer tw-text-white"
305
+ on:click={handleDisconnect}>Disconnect</button
306
+ >
307
+ {/if}
308
+ </div>
309
+ {/if}
310
+ </div>
package/src/app.css ADDED
@@ -0,0 +1,2 @@
1
+ @tailwind components;
2
+ @tailwind utilities;
package/src/main.ts ADDED
@@ -0,0 +1,22 @@
1
+ import './app.css'
2
+ import App from './App.svelte'
3
+
4
+ const div = document.createElement('div')
5
+ document.body.appendChild(div)
6
+ div.id = 'windowNostrModal'
7
+ div.classList.add(
8
+ 'tw-fixed',
9
+ 'tw-top-6',
10
+ 'tw-right-6',
11
+ )
12
+
13
+ const app = new App({
14
+ target: div
15
+ })
16
+
17
+ export default app
18
+
19
+ // ~
20
+ ;(window as any).destroyWnj= () => {
21
+ app.$destroy()
22
+ }
@@ -0,0 +1,2 @@
1
+ /// <reference types="svelte" />
2
+ /// <reference types="vite/client" />
@@ -0,0 +1,7 @@
1
+ import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
2
+
3
+ export default {
4
+ // Consult https://svelte.dev/docs#compile-time-svelte-preprocess
5
+ // for more information about preprocessors
6
+ preprocess: vitePreprocess(),
7
+ }
@@ -0,0 +1,9 @@
1
+ /** @type {import('tailwindcss').Config} */
2
+ export default {
3
+ content: ['./src/**/*.{html,js,ts,svelte}'],
4
+ theme: {
5
+ extend: {}
6
+ },
7
+ plugins: [],
8
+ prefix: 'tw-'
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "extends": "@tsconfig/svelte/tsconfig.json",
3
+ "compilerOptions": {
4
+ "target": "ESNext",
5
+ "useDefineForClassFields": true,
6
+ "module": "ESNext",
7
+ "resolveJsonModule": true,
8
+ /**
9
+ * Typecheck JS in `.svelte` and `.js` files by default.
10
+ * Disable checkJs if you'd like to use dynamic types in JS.
11
+ * Note that setting allowJs false does not prevent the use
12
+ * of JS in `.svelte` files.
13
+ */
14
+ "allowJs": true,
15
+ "checkJs": true,
16
+ "isolatedModules": true
17
+ },
18
+ "include": ["src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
19
+ "references": [{ "path": "./tsconfig.node.json" }]
20
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "compilerOptions": {
3
+ "composite": true,
4
+ "skipLibCheck": true,
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "strict": true
8
+ },
9
+ "include": ["vite.config.ts"]
10
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,14 @@
1
+ import {defineConfig} from 'vite'
2
+ import {svelte} from '@sveltejs/vite-plugin-svelte'
3
+
4
+ // https://vitejs.dev/config/
5
+ export default defineConfig({
6
+ plugins: [svelte()],
7
+ build: {
8
+ rollupOptions: {
9
+ output: {
10
+ format: 'iife'
11
+ }
12
+ }
13
+ }
14
+ })