nostr-components 0.2.0 → 0.2.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/README.md +72 -35
- package/dist/assets/dark-nostrich-running.gif +0 -0
- package/dist/assets/default_dp-NQ3TGrtT.png +0 -0
- package/dist/assets/default_dp.png +0 -0
- package/dist/assets/default_dp_32.png +0 -0
- package/dist/assets/light-nostrich-running.gif +0 -0
- package/dist/components/nostr-comment.es.js +13 -13
- package/dist/components/nostr-comment.es.js.map +1 -1
- package/dist/nostr-components.umd.js +27 -27
- package/dist/nostr-components.umd.js.map +1 -1
- package/dist/src/index.d.ts +10 -10
- package/package.json +43 -3
package/README.md
CHANGED
|
@@ -4,51 +4,88 @@
|
|
|
4
4
|
|
|
5
5
|
## 🚀 About the Project
|
|
6
6
|
|
|
7
|
-
Nostr Components makes it easy to embed Nostr profiles, posts, and follow buttons in any website. Inspired by <a href="https://unpkg.com/nostr-web-components@0.0.15/demo.html">fiatjaf's Nostr Web Components</a>, this project adds a beautiful UI, a Storybook component generator (for webmasters), and allows embedding Nostr content anywhere on the Internet.
|
|
7
|
+
Nostr Components makes it easy to embed Zap button, Nostr profiles, posts, and follow buttons in any website. Inspired by <a href="https://unpkg.com/nostr-web-components@0.0.15/demo.html">fiatjaf's Nostr Web Components</a>, this project adds a beautiful UI, a Storybook component generator (for webmasters), and allows embedding Nostr content anywhere on the Internet.
|
|
8
8
|
|
|
9
9
|
🔹 **[Nostr Zap](#5-nostr-zap-)** - Lightning Network zap button for Nostr
|
|
10
10
|
🔹 **[Nostr Profile Badge](#1-nostr-profile-badge-)** - Compact badge-style profile display
|
|
11
11
|
🔹 **[Nostr Profile](#2-nostr-profile-)** - Full Nostr profile with more details
|
|
12
12
|
🔹 **[Nostr Post](#3-nostr-post-)** - Embed a specific Nostr post
|
|
13
13
|
🔹 **[Nostr Follow](#4-nostr-follow-)** - Follow button for Nostr
|
|
14
|
-
🔹 **[Nostr DM](#6-nostr-dm-)** - Send a direct message on Nostr
|
|
15
|
-
🔹 **[Nostr Live Chat](#7-nostr-live-chat-)** - Real-time chat with message history
|
|
16
|
-
🔹 **[Nostr Comment](#8-nostr-comment-)** - Decentralized comment system for any website
|
|
14
|
+
🔹 **[Nostr DM](#6-nostr-dm-)** - Send a direct message on Nostr (Under construction)
|
|
15
|
+
🔹 **[Nostr Live Chat](#7-nostr-live-chat-)** - Real-time chat with message history (Under construction)
|
|
16
|
+
🔹 **[Nostr Comment](#8-nostr-comment-)** - Decentralized comment system for any website (Under construction)
|
|
17
17
|
🔹 **[Wordpress Integration](#9-wordpress-integration)** - Wordpress Integration
|
|
18
18
|
|
|
19
19
|
## 🛠️ Usage
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
21
|
+
### Option 1: Using with Bundlers (Webpack, Vite, React, etc.)
|
|
22
|
+
|
|
23
|
+
For modern bundler-based projects (React, Vue, Next.js, etc.):
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
// Import the main package - this automatically registers all components
|
|
27
|
+
import 'nostr-components';
|
|
28
|
+
|
|
29
|
+
// Or import specific components only
|
|
30
|
+
import 'nostr-components/components/nostr-like';
|
|
31
|
+
import 'nostr-components/components/nostr-zap';
|
|
32
|
+
|
|
33
|
+
// Import themes
|
|
34
|
+
import 'nostr-components/themes/dark';
|
|
35
|
+
// or
|
|
36
|
+
import 'nostr-components/themes/light';
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Then use the components in your JSX/HTML:
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
function MyComponent() {
|
|
43
|
+
return (
|
|
44
|
+
<>
|
|
45
|
+
<nostr-like url="https://example.com" text="Like" />
|
|
46
|
+
<nostr-zap npub="npub1..." theme="dark" />
|
|
47
|
+
</>
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**Note:** When importing from the main package (`import 'nostr-components'`), all components are automatically registered. Individual component imports also work and register only that component.
|
|
53
|
+
|
|
54
|
+
### Option 2: Direct Script Tag Usage
|
|
55
|
+
|
|
56
|
+
For direct HTML usage without a bundler:
|
|
57
|
+
|
|
58
|
+
```html
|
|
59
|
+
<head>
|
|
60
|
+
<!-- Required: Nostr Components Script (choose UMD or ES) -->
|
|
61
|
+
<script src="./dist/nostr-components.umd.js"></script>
|
|
62
|
+
<!-- Or nostr-components.es.js -->
|
|
63
|
+
<script>
|
|
64
|
+
// Initialize components (only needed for UMD build)
|
|
65
|
+
NostrComponents.default.init();
|
|
66
|
+
</script>
|
|
67
|
+
|
|
68
|
+
<!-- Optional: Glide.js CSS for Post Carousel -->
|
|
69
|
+
<!-- Needed only if displaying posts that might contain multiple images/videos -->
|
|
70
|
+
<link
|
|
71
|
+
rel="stylesheet"
|
|
72
|
+
href="https://cdn.jsdelivr.net/npm/@glidejs/glide/dist/css/glide.core.min.css"
|
|
73
|
+
/>
|
|
74
|
+
<link
|
|
75
|
+
rel="stylesheet"
|
|
76
|
+
href="https://cdn.jsdelivr.net/npm/@glidejs/glide/dist/css/glide.theme.min.css"
|
|
77
|
+
/>
|
|
78
|
+
</head>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- **UMD (Universal Module Definition):** Use `<script src="./dist/nostr-components.umd.js"></script>` and the initialization script.
|
|
82
|
+
- **ES Module:** Use `<script type="module">import NostrComponents from './dist/nostr-components.es.js'; NostrComponents.init();</script>`.
|
|
83
|
+
|
|
84
|
+
_Note: Replace `./dist/nostr-components._.js`with the actual path to the file on your server or use a CDN link if available (e.g.,`https://nostr-components.web.app/dist/nostr-components.umd.js`).\*
|
|
85
|
+
|
|
86
|
+
### Using the Components
|
|
87
|
+
|
|
88
|
+
Place the component tags anywhere in your HTML/JSX:
|
|
52
89
|
|
|
53
90
|
---
|
|
54
91
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pure-jrVhRVpB.js","assets/nostr-service-pr_crY62.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t;var f=(o,r,t)=>Zt(o,typeof r!="symbol"?r+"":r,t);import{_ as xe}from"../assets/preload-helper-D7HrI6pR.js";import{N as Qt,D as Jt,e as en}from"../assets/nostr-service-pr_crY62.js";import{n as gt}from"../assets/utils--bxLbhGF.js";function
|
|
3
|
-
<div class="modern-comment" data-comment-id="${
|
|
2
|
+
var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[r]=t;var f=(o,r,t)=>Zt(o,typeof r!="symbol"?r+"":r,t);import{_ as xe}from"../assets/preload-helper-D7HrI6pR.js";import{N as Qt,D as Jt,e as en}from"../assets/nostr-service-pr_crY62.js";import{n as gt}from"../assets/utils--bxLbhGF.js";function B(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function tn(o){const t=Date.now()/1e3-o;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:new Date(o*1e3).toLocaleDateString()}function kt(o){var r,t;return(r=o.userProfile)!=null&&r.displayName?o.userProfile.displayName:(t=o.userProfile)!=null&&t.name?o.userProfile.name:`${o.pubkey.slice(0,8)}...${o.pubkey.slice(-4)}`}function nn(o){var r,t;if((r=o.userProfile)!=null&&r.image&&o.userProfile.image.trim()!==""){let n=o.userProfile.image.trim();return console.log("Processing image URL:",n,"for user:",o.userProfile.name||o.pubkey),(n.startsWith("Qm")||n.startsWith("bafy"))&&(n=`https://ipfs.io/ipfs/${n}`,console.log("Converted IPFS to gateway URL:",n)),n.startsWith("//")&&(n="https:"+n,console.log("Added protocol to URL:",n)),console.log("Final image URL:",n),n}return console.log("No image found for user:",((t=o.userProfile)==null?void 0:t.name)||o.pubkey,"using default"),"../../assets/default_dp.png"}function St(o,r=!1,t=null,n=null,a="anon",s=!1){const c=kt(o),h=nn(o),g=tn(o.created_at),y=o.depth||0,d=6,E=t===o.id;return`
|
|
3
|
+
<div class="modern-comment" data-comment-id="${B(o.id)}" data-depth="${y}">
|
|
4
4
|
<div class="comment-content-wrapper">
|
|
5
5
|
<div class="comment-avatar-section">
|
|
6
6
|
<img src="${h}" alt="Avatar" class="comment-avatar" />
|
|
7
7
|
</div>
|
|
8
8
|
<div class="comment-body">
|
|
9
9
|
<div class="comment-header">
|
|
10
|
-
<span class="comment-author">${
|
|
11
|
-
<span class="comment-time">${
|
|
10
|
+
<span class="comment-author">${B(c)}</span>
|
|
11
|
+
<span class="comment-time">${B(g)}</span>
|
|
12
12
|
</div>
|
|
13
13
|
<div class="comment-text">
|
|
14
|
-
${
|
|
14
|
+
${B(o.content.trim())}
|
|
15
15
|
</div>
|
|
16
16
|
<div class="comment-actions">
|
|
17
|
-
${r?"":`<button class="reply-btn" data-comment-id="${
|
|
17
|
+
${r?"":`<button class="reply-btn" data-comment-id="${B(o.id)}" aria-label="Reply to comment">
|
|
18
18
|
<span class="reply-icon">💬</span>
|
|
19
19
|
<span class="reply-text">Reply</span>
|
|
20
20
|
</button>`}
|
|
@@ -28,10 +28,10 @@ var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,config
|
|
|
28
28
|
</div>
|
|
29
29
|
`:""}
|
|
30
30
|
</div>
|
|
31
|
-
`}function on(o,r,t="anon",n=!1){let a="
|
|
31
|
+
`}function on(o,r,t="anon",n=!1){let a="../../assets/default_dp.png";if(console.log("renderInlineReplyForm - currentUserProfile:",r),r!=null&&r.image&&r.image.trim()!==""){let c=r.image.trim();console.log("Inline reply form - Processing image URL:",c),(c.startsWith("Qm")||c.startsWith("bafy"))&&(c=`https://ipfs.io/ipfs/${c}`,console.log("Inline reply form - Converted IPFS to gateway URL:",c)),c.startsWith("//")&&(c="https:"+c,console.log("Inline reply form - Added protocol to URL:",c)),console.log("Inline reply form - Final image URL:",c),a=c}else console.log("Inline reply form - No image found, using default");const s=kt(o);return`
|
|
32
32
|
<div class="inline-reply-form">
|
|
33
33
|
<div class="reply-context">
|
|
34
|
-
<span class="reply-context-text">💬 Replying to <strong>${
|
|
34
|
+
<span class="reply-context-text">💬 Replying to <strong>${B(s)}</strong></span>
|
|
35
35
|
<button data-role="cancel-reply" class="cancel-reply-btn" aria-label="Cancel reply">✕</button>
|
|
36
36
|
</div>
|
|
37
37
|
<div class="reply-input-container">
|
|
@@ -73,7 +73,7 @@ var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,config
|
|
|
73
73
|
<div class="comment-input-main">
|
|
74
74
|
<textarea
|
|
75
75
|
data-role="comment-input"
|
|
76
|
-
placeholder="${
|
|
76
|
+
placeholder="${B(r)}"
|
|
77
77
|
rows="3"
|
|
78
78
|
${t?"disabled":""}
|
|
79
79
|
class="modern-comment-textarea"
|
|
@@ -129,7 +129,7 @@ var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,config
|
|
|
129
129
|
<div class="comment-widget error">
|
|
130
130
|
<div class="error-message">
|
|
131
131
|
<p>❌ Failed to load comments</p>
|
|
132
|
-
${t?`<small>${
|
|
132
|
+
${t?`<small>${B(t)}</small>`:""}
|
|
133
133
|
</div>
|
|
134
134
|
</div>
|
|
135
135
|
`:`
|
|
@@ -900,8 +900,8 @@ var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,config
|
|
|
900
900
|
}
|
|
901
901
|
}
|
|
902
902
|
</style>
|
|
903
|
-
`}/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:Lt,setPrototypeOf:bt,isFrozen:cn,getPrototypeOf:mn,getOwnPropertyDescriptor:dn}=Object;let{freeze:I,seal:M,create:Pt}=Object,{apply:We,construct:Be}=typeof Reflect<"u"&&Reflect;I||(I=function(r){return r});M||(M=function(r){return r});We||(We=function(r,t,n){return r.apply(t,n)});Be||(Be=function(r,t){return new r(...t)});const ve=C(Array.prototype.forEach),pn=C(Array.prototype.lastIndexOf),yt=C(Array.prototype.pop),se=C(Array.prototype.push),un=C(Array.prototype.splice),Ee=C(String.prototype.toLowerCase),ze=C(String.prototype.toString),xt=C(String.prototype.match),le=C(String.prototype.replace),fn=C(String.prototype.indexOf),hn=C(String.prototype.trim),z=C(Object.prototype.hasOwnProperty),N=C(RegExp.prototype.test),ce=gn(TypeError);function C(o){return function(r){r instanceof RegExp&&(r.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),a=1;a<t;a++)n[a-1]=arguments[a];return We(o,r,n)}}function gn(o){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return Be(o,t)}}function u(o,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ee;bt&&bt(o,null);let n=r.length;for(;n--;){let a=r[n];if(typeof a=="string"){const s=t(a);s!==a&&(cn(r)||(r[n]=s),a=s)}o[a]=!0}return o}function bn(o){for(let r=0;r<o.length;r++)z(o,r)||(o[r]=null);return o}function B(o){const r=Pt(null);for(const[t,n]of Lt(o))z(o,t)&&(Array.isArray(n)?r[t]=bn(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=B(n):r[t]=n);return r}function me(o,r){for(;o!==null;){const n=dn(o,r);if(n){if(n.get)return C(n.get);if(typeof n.value=="function")return C(n.value)}o=mn(o)}function t(){return null}return t}const vt=I(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Fe=I(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),$e=I(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),yn=I(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),He=I(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),xn=I(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Tt=I(["#text"]),Et=I(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ke=I(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),At=I(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Te=I(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),vn=M(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Tn=M(/<%[\w\W]*|[\w\W]*%>/gm),En=M(/\$\{[\w\W]*/gm),An=M(/^data-[\-\w.\u00B7-\uFFFF]+$/),wn=M(/^aria-[\-\w]+$/),Nt=M(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),_n=M(/^(?:\w+script|data):/i),kn=M(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),It=M(/^html$/i),Sn=M(/^[a-z][.\w]*(-[.\w]+)+$/i);var wt=Object.freeze({__proto__:null,ARIA_ATTR:wn,ATTR_WHITESPACE:kn,CUSTOM_ELEMENT:Sn,DATA_ATTR:An,DOCTYPE_NAME:It,ERB_EXPR:Tn,IS_ALLOWED_URI:Nt,IS_SCRIPT_OR_DATA:_n,MUSTACHE_EXPR:vn,TMPLIT_EXPR:En});const de={element:1,text:3,progressingInstruction:7,comment:8,document:9},Rn=function(){return typeof window>"u"?null:window},Ln=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let n=null;const a="data-tt-policy-suffix";t&&t.hasAttribute(a)&&(n=t.getAttribute(a));const s="dompurify"+(n?"#"+n:"");try{return r.createPolicy(s,{createHTML(c){return c},createScriptURL(c){return c}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},_t=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ct(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Rn();const r=m=>Ct(m);if(r.version="3.2.6",r.removed=[],!o||!o.document||o.document.nodeType!==de.document||!o.Element)return r.isSupported=!1,r;let{document:t}=o;const n=t,a=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:c,Node:h,Element:g,NodeFilter:y,NamedNodeMap:d=o.NamedNodeMap||o.MozNamedAttrMap,HTMLFormElement:E,DOMParser:D,trustedTypes:Y}=o,p=g.prototype,x=me(p,"cloneNode"),k=me(p,"remove"),te=me(p,"nextSibling"),U=me(p,"childNodes"),$=me(p,"parentNode");if(typeof c=="function"){const m=t.createElement("template");m.content&&m.content.ownerDocument&&(t=m.content.ownerDocument)}let L,ne="";const{implementation:Ae,createNodeIterator:Dt,createDocumentFragment:Ot,getElementsByTagName:Mt}=t,{importNode:Ut}=n;let P=_t();r.isSupported=typeof Lt=="function"&&typeof $=="function"&&Ae&&Ae.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:we,ERB_EXPR:_e,TMPLIT_EXPR:ke,DATA_ATTR:zt,ARIA_ATTR:Ft,IS_SCRIPT_OR_DATA:$t,ATTR_WHITESPACE:Ge,CUSTOM_ELEMENT:Ht}=wt;let{IS_ALLOWED_URI:Ye}=wt,A=null;const qe=u({},[...vt,...Fe,...$e,...He,...Tt]);let _=null;const Ve=u({},[...Et,...Ke,...At,...Te]);let v=Object.seal(Pt(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),oe=null,Se=null,je=!0,Re=!0,Xe=!1,Ze=!0,V=!1,pe=!0,q=!1,Le=!1,Pe=!1,j=!1,ue=!1,fe=!1,Qe=!0,Je=!1;const Kt="user-content-";let Ne=!0,re=!1,X={},Z=null;const et=u({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let tt=null;const nt=u({},["audio","video","img","source","image","track"]);let Ie=null;const ot=u({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),he="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",H="http://www.w3.org/1999/xhtml";let Q=H,Ce=!1,De=null;const Wt=u({},[he,ge,H],ze);let be=u({},["mi","mo","mn","ms","mtext"]),ye=u({},["annotation-xml"]);const Bt=u({},["title","style","font","a","script"]);let ie=null;const Gt=["application/xhtml+xml","text/html"],Yt="text/html";let w=null,J=null;const qt=t.createElement("form"),rt=function(e){return e instanceof RegExp||e instanceof Function},Oe=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(J&&J===e)){if((!e||typeof e!="object")&&(e={}),e=B(e),ie=Gt.indexOf(e.PARSER_MEDIA_TYPE)===-1?Yt:e.PARSER_MEDIA_TYPE,w=ie==="application/xhtml+xml"?ze:Ee,A=z(e,"ALLOWED_TAGS")?u({},e.ALLOWED_TAGS,w):qe,_=z(e,"ALLOWED_ATTR")?u({},e.ALLOWED_ATTR,w):Ve,De=z(e,"ALLOWED_NAMESPACES")?u({},e.ALLOWED_NAMESPACES,ze):Wt,Ie=z(e,"ADD_URI_SAFE_ATTR")?u(B(ot),e.ADD_URI_SAFE_ATTR,w):ot,tt=z(e,"ADD_DATA_URI_TAGS")?u(B(nt),e.ADD_DATA_URI_TAGS,w):nt,Z=z(e,"FORBID_CONTENTS")?u({},e.FORBID_CONTENTS,w):et,oe=z(e,"FORBID_TAGS")?u({},e.FORBID_TAGS,w):B({}),Se=z(e,"FORBID_ATTR")?u({},e.FORBID_ATTR,w):B({}),X=z(e,"USE_PROFILES")?e.USE_PROFILES:!1,je=e.ALLOW_ARIA_ATTR!==!1,Re=e.ALLOW_DATA_ATTR!==!1,Xe=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ze=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,pe=e.SAFE_FOR_XML!==!1,q=e.WHOLE_DOCUMENT||!1,j=e.RETURN_DOM||!1,ue=e.RETURN_DOM_FRAGMENT||!1,fe=e.RETURN_TRUSTED_TYPE||!1,Pe=e.FORCE_BODY||!1,Qe=e.SANITIZE_DOM!==!1,Je=e.SANITIZE_NAMED_PROPS||!1,Ne=e.KEEP_CONTENT!==!1,re=e.IN_PLACE||!1,Ye=e.ALLOWED_URI_REGEXP||Nt,Q=e.NAMESPACE||H,be=e.MATHML_TEXT_INTEGRATION_POINTS||be,ye=e.HTML_INTEGRATION_POINTS||ye,v=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&rt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(v.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&rt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(v.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(v.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),V&&(Re=!1),ue&&(j=!0),X&&(A=u({},Tt),_=[],X.html===!0&&(u(A,vt),u(_,Et)),X.svg===!0&&(u(A,Fe),u(_,Ke),u(_,Te)),X.svgFilters===!0&&(u(A,$e),u(_,Ke),u(_,Te)),X.mathMl===!0&&(u(A,He),u(_,At),u(_,Te))),e.ADD_TAGS&&(A===qe&&(A=B(A)),u(A,e.ADD_TAGS,w)),e.ADD_ATTR&&(_===Ve&&(_=B(_)),u(_,e.ADD_ATTR,w)),e.ADD_URI_SAFE_ATTR&&u(Ie,e.ADD_URI_SAFE_ATTR,w),e.FORBID_CONTENTS&&(Z===et&&(Z=B(Z)),u(Z,e.FORBID_CONTENTS,w)),Ne&&(A["#text"]=!0),q&&u(A,["html","head","body"]),A.table&&(u(A,["tbody"]),delete oe.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!="function")throw ce('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ce('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');L=e.TRUSTED_TYPES_POLICY,ne=L.createHTML("")}else L===void 0&&(L=Ln(Y,a)),L!==null&&typeof ne=="string"&&(ne=L.createHTML(""));I&&I(e),J=e}},it=u({},[...Fe,...$e,...yn]),at=u({},[...He,...xn]),Vt=function(e){let i=$(e);(!i||!i.tagName)&&(i={namespaceURI:Q,tagName:"template"});const l=Ee(e.tagName),b=Ee(i.tagName);return De[e.namespaceURI]?e.namespaceURI===ge?i.namespaceURI===H?l==="svg":i.namespaceURI===he?l==="svg"&&(b==="annotation-xml"||be[b]):!!it[l]:e.namespaceURI===he?i.namespaceURI===H?l==="math":i.namespaceURI===ge?l==="math"&&ye[b]:!!at[l]:e.namespaceURI===H?i.namespaceURI===ge&&!ye[b]||i.namespaceURI===he&&!be[b]?!1:!at[l]&&(Bt[l]||!it[l]):!!(ie==="application/xhtml+xml"&&De[e.namespaceURI]):!1},F=function(e){se(r.removed,{element:e});try{$(e).removeChild(e)}catch{k(e)}},ee=function(e,i){try{se(r.removed,{attribute:i.getAttributeNode(e),from:i})}catch{se(r.removed,{attribute:null,from:i})}if(i.removeAttribute(e),e==="is")if(j||ue)try{F(i)}catch{}else try{i.setAttribute(e,"")}catch{}},st=function(e){let i=null,l=null;if(Pe)e="<remove></remove>"+e;else{const T=xt(e,/^[\r\n\t ]+/);l=T&&T[0]}ie==="application/xhtml+xml"&&Q===H&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const b=L?L.createHTML(e):e;if(Q===H)try{i=new D().parseFromString(b,ie)}catch{}if(!i||!i.documentElement){i=Ae.createDocument(Q,"template",null);try{i.documentElement.innerHTML=Ce?ne:b}catch{}}const S=i.body||i.documentElement;return e&&l&&S.insertBefore(t.createTextNode(l),S.childNodes[0]||null),Q===H?Mt.call(i,q?"html":"body")[0]:q?i.documentElement:S},lt=function(e){return Dt.call(e.ownerDocument||e,e,y.SHOW_ELEMENT|y.SHOW_COMMENT|y.SHOW_TEXT|y.SHOW_PROCESSING_INSTRUCTION|y.SHOW_CDATA_SECTION,null)},Me=function(e){return e instanceof E&&(typeof e.nodeName!="string"||typeof e.textContent!="string"||typeof e.removeChild!="function"||!(e.attributes instanceof d)||typeof e.removeAttribute!="function"||typeof e.setAttribute!="function"||typeof e.namespaceURI!="string"||typeof e.insertBefore!="function"||typeof e.hasChildNodes!="function")},ct=function(e){return typeof h=="function"&&e instanceof h};function K(m,e,i){ve(m,l=>{l.call(r,e,i,J)})}const mt=function(e){let i=null;if(K(P.beforeSanitizeElements,e,null),Me(e))return F(e),!0;const l=w(e.nodeName);if(K(P.uponSanitizeElement,e,{tagName:l,allowedTags:A}),pe&&e.hasChildNodes()&&!ct(e.firstElementChild)&&N(/<[/\w!]/g,e.innerHTML)&&N(/<[/\w!]/g,e.textContent)||e.nodeType===de.progressingInstruction||pe&&e.nodeType===de.comment&&N(/<[/\w]/g,e.data))return F(e),!0;if(!A[l]||oe[l]){if(!oe[l]&&pt(l)&&(v.tagNameCheck instanceof RegExp&&N(v.tagNameCheck,l)||v.tagNameCheck instanceof Function&&v.tagNameCheck(l)))return!1;if(Ne&&!Z[l]){const b=$(e)||e.parentNode,S=U(e)||e.childNodes;if(S&&b){const T=S.length;for(let O=T-1;O>=0;--O){const W=x(S[O],!0);W.__removalCount=(e.__removalCount||0)+1,b.insertBefore(W,te(e))}}}return F(e),!0}return e instanceof g&&!Vt(e)||(l==="noscript"||l==="noembed"||l==="noframes")&&N(/<\/no(script|embed|frames)/i,e.innerHTML)?(F(e),!0):(V&&e.nodeType===de.text&&(i=e.textContent,ve([we,_e,ke],b=>{i=le(i,b," ")}),e.textContent!==i&&(se(r.removed,{element:e.cloneNode()}),e.textContent=i)),K(P.afterSanitizeElements,e,null),!1)},dt=function(e,i,l){if(Qe&&(i==="id"||i==="name")&&(l in t||l in qt))return!1;if(!(Re&&!Se[i]&&N(zt,i))){if(!(je&&N(Ft,i))){if(!_[i]||Se[i]){if(!(pt(e)&&(v.tagNameCheck instanceof RegExp&&N(v.tagNameCheck,e)||v.tagNameCheck instanceof Function&&v.tagNameCheck(e))&&(v.attributeNameCheck instanceof RegExp&&N(v.attributeNameCheck,i)||v.attributeNameCheck instanceof Function&&v.attributeNameCheck(i))||i==="is"&&v.allowCustomizedBuiltInElements&&(v.tagNameCheck instanceof RegExp&&N(v.tagNameCheck,l)||v.tagNameCheck instanceof Function&&v.tagNameCheck(l))))return!1}else if(!Ie[i]){if(!N(Ye,le(l,Ge,""))){if(!((i==="src"||i==="xlink:href"||i==="href")&&e!=="script"&&fn(l,"data:")===0&&tt[e])){if(!(Xe&&!N($t,le(l,Ge,"")))){if(l)return!1}}}}}}return!0},pt=function(e){return e!=="annotation-xml"&&xt(e,Ht)},ut=function(e){K(P.beforeSanitizeAttributes,e,null);const{attributes:i}=e;if(!i||Me(e))return;const l={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:_,forceKeepAttr:void 0};let b=i.length;for(;b--;){const S=i[b],{name:T,namespaceURI:O,value:W}=S,ae=w(T),Ue=W;let R=T==="value"?Ue:hn(Ue);if(l.attrName=ae,l.attrValue=R,l.keepAttr=!0,l.forceKeepAttr=void 0,K(P.uponSanitizeAttribute,e,l),R=l.attrValue,Je&&(ae==="id"||ae==="name")&&(ee(T,e),R=Kt+R),pe&&N(/((--!?|])>)|<\/(style|title)/i,R)){ee(T,e);continue}if(l.forceKeepAttr)continue;if(!l.keepAttr){ee(T,e);continue}if(!Ze&&N(/\/>/i,R)){ee(T,e);continue}V&&ve([we,_e,ke],ht=>{R=le(R,ht," ")});const ft=w(e.nodeName);if(!dt(ft,ae,R)){ee(T,e);continue}if(L&&typeof Y=="object"&&typeof Y.getAttributeType=="function"&&!O)switch(Y.getAttributeType(ft,ae)){case"TrustedHTML":{R=L.createHTML(R);break}case"TrustedScriptURL":{R=L.createScriptURL(R);break}}if(R!==Ue)try{O?e.setAttributeNS(O,T,R):e.setAttribute(T,R),Me(e)?F(e):yt(r.removed)}catch{ee(T,e)}}K(P.afterSanitizeAttributes,e,null)},jt=function m(e){let i=null;const l=lt(e);for(K(P.beforeSanitizeShadowDOM,e,null);i=l.nextNode();)K(P.uponSanitizeShadowNode,i,null),mt(i),ut(i),i.content instanceof s&&m(i.content);K(P.afterSanitizeShadowDOM,e,null)};return r.sanitize=function(m){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,l=null,b=null,S=null;if(Ce=!m,Ce&&(m="<!-->"),typeof m!="string"&&!ct(m))if(typeof m.toString=="function"){if(m=m.toString(),typeof m!="string")throw ce("dirty is not a string, aborting")}else throw ce("toString is not a function");if(!r.isSupported)return m;if(Le||Oe(e),r.removed=[],typeof m=="string"&&(re=!1),re){if(m.nodeName){const W=w(m.nodeName);if(!A[W]||oe[W])throw ce("root node is forbidden and cannot be sanitized in-place")}}else if(m instanceof h)i=st("<!---->"),l=i.ownerDocument.importNode(m,!0),l.nodeType===de.element&&l.nodeName==="BODY"||l.nodeName==="HTML"?i=l:i.appendChild(l);else{if(!j&&!V&&!q&&m.indexOf("<")===-1)return L&&fe?L.createHTML(m):m;if(i=st(m),!i)return j?null:fe?ne:""}i&&Pe&&F(i.firstChild);const T=lt(re?m:i);for(;b=T.nextNode();)mt(b),ut(b),b.content instanceof s&&jt(b.content);if(re)return m;if(j){if(ue)for(S=Ot.call(i.ownerDocument);i.firstChild;)S.appendChild(i.firstChild);else S=i;return(_.shadowroot||_.shadowrootmode)&&(S=Ut.call(n,S,!0)),S}let O=q?i.outerHTML:i.innerHTML;return q&&A["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&N(It,i.ownerDocument.doctype.name)&&(O="<!DOCTYPE "+i.ownerDocument.doctype.name+`>
|
|
904
|
-
`+O),V&&ve([we,_e,ke],W=>{O=le(O,W," ")}),L&&fe?L.createHTML(O):O},r.setConfig=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Oe(m),Le=!0},r.clearConfig=function(){J=null,Le=!1},r.isValidAttribute=function(m,e,i){J||Oe({});const l=w(m),b=w(e);return dt(l,b,i)},r.addHook=function(m,e){typeof e=="function"&&se(P[m],e)},r.removeHook=function(m,e){if(e!==void 0){const i=pn(P[m],e);return i===-1?void 0:un(P[m],i,1)[0]}return yt(P[m])},r.removeHooks=function(m){P[m]=[]},r.removeAllHooks=function(){P=_t()},r}var Pn=Ct();class Nn extends HTMLElement{constructor(){super();f(this,"rendered",!1);f(this,"nostrService",Qt.getInstance());f(this,"shadow");f(this,"theme","light");f(this,"isLoading",!0);f(this,"isError",!1);f(this,"errorMessage","");f(this,"comments",[]);f(this,"baseUrl","");f(this,"userPublicKey",null);f(this,"userPrivateKey",null);f(this,"currentUserProfile",null);f(this,"isSubmitting",!1);f(this,"replyingToComment",null);f(this,"commentAs","user");f(this,"hasNip07",!1);f(this,"anonPrivateKeyHex",null);f(this,"eventListeners",[]);f(this,"nip07MonitoringInterval",null);f(this,"loadVersion",0);f(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(",").map(n=>n.trim()):Jt});f(this,"getTheme",()=>{this.theme="light";const t=this.getAttribute("theme");t&&(["light","dark"].includes(t)?this.theme=t:console.warn(`Invalid theme '${t}'. Accepted values are 'light', 'dark'`))});f(this,"getBaseUrl",()=>{const t=this.getAttribute("url");return t?gt(t):gt(window.location.href)});f(this,"detectNip07Extension",()=>{const t=window.nostr;return t?typeof t.getPublicKey=="function"&&typeof t.signEvent=="function"?!0:(console.warn("NIP-07 extension detected but missing required methods"),!1):!1});f(this,"handleNip07StateChange",async()=>{const t=this.hasNip07,n=this.detectNip07Extension();if(t!==n&&(console.log("NIP-07 extension state changed:",n),this.hasNip07=n,n&&this.commentAs==="user"))try{await this.initializeUser(),this.render()}catch(a){console.warn("Failed to reconnect to NIP-07 extension:",a)}});f(this,"setupNip07StateMonitoring",()=>{const t=setInterval(async()=>{document.contains(this)&&await this.handleNip07StateChange()},2e3);this.nip07MonitoringInterval=t});f(this,"loadComments",async()=>{this.loadVersion++;const t=this.loadVersion;try{this.isLoading=!0,this.isError=!1,this.render();const n=this.getRelays();await this.nostrService.connectToNostr(n);const a={kinds:[1111],"#I":[this.baseUrl],limit:200},s=await this.nostrService.getNDK().fetchEvents(a),c=Array.from(s),h=new Map;c.forEach(p=>h.set(p.id,{content:p.content,id:p.id,tags:p.tags}));const g=[],y=new Set;for(const p of c){let x;const k=(p.tags||[]).filter(U=>U[0]==="e");for(let U=k.length-1;U>=0;U--){const $=k[U];if($[3]==="reply"){x=$[1];break}}if(!x&&k.length>0){const U=k.filter($=>$[3]!=="root");U.length>0?x=U[U.length-1][1]:x=k[k.length-1][1]}const te={id:p.id,pubkey:p.pubkey,content:p.content,created_at:p.created_at,replies:[],replyTo:x,depth:0};y.add(p.pubkey),g.push(te)}const d=Array.from(y).map(async p=>{try{console.log("Fetching profile for pubkey:",p);const x=await this.nostrService.getProfile({pubkey:p});return console.log("Profile fetched for",p,":",x),{pubkey:p,profile:x}}catch(x){return console.warn("Failed to fetch profile for:",p,x),{pubkey:p,profile:null}}}),E=await Promise.allSettled(d),D=new Map;if(E.forEach(p=>{if(p.status==="fulfilled"){const{pubkey:x,profile:k}=p.value;D.set(x,k)}}),g.forEach(p=>{p.userProfile=D.get(p.pubkey)||void 0,console.log("Attached profile to comment:",p.pubkey,"Profile:",p.userProfile)}),t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting");return}this.comments=this.buildCommentTree(g);const Y=new Map;this.comments.forEach(p=>{const x=[p];for(;x.length;){const k=x.pop();Y.set(k.id,k),k.replies.forEach(te=>x.push(te))}}),g.forEach(p=>{const x=p.replyTo?Y.get(p.replyTo):void 0,k=x?x.content:"(no parent)";console.log(`[nostr-comment] recv: "${p.content}" -> parent: ${k}`)})}catch(n){if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting error handling");return}this.isError=!0,this.errorMessage=n instanceof Error?n.message:"Failed to load comments",console.error("Error loading comments:",n)}finally{if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting final state update");return}this.isLoading=!1,this.render()}});f(this,"buildCommentTree",t=>{const n=new Map,a=[];t.forEach(c=>{n.set(c.id,c)}),t.forEach(c=>{if(c.replyTo&&n.has(c.replyTo)){const h=n.get(c.replyTo);h.replies.push(c),h.replies.sort((g,y)=>g.created_at-y.created_at)}else a.push(c)});const s=(c,h)=>{for(const g of c)g.depth=h,g.replies&&g.replies.length&&s(g.replies,h+1)};return s(a,0),a.sort((c,h)=>h.created_at-c.created_at)});f(this,"initializeUser",async()=>{if(this.hasNip07=this.detectNip07Extension(),console.log("NIP-07 extension detected:",this.hasNip07),this.hasNip07&&this.commentAs==="user")try{this.userPublicKey=await window.nostr.getPublicKey(),console.log("Successfully connected to NIP-07 extension, public key:",this.userPublicKey),this.userPrivateKey=null,this.anonPrivateKeyHex=null}catch(t){console.warn("NIP-07 extension available but failed to get public key:",t),this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null}if(!this.userPublicKey){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,this.userPrivateKey=t;const{getPublicKey:n}=await xe(async()=>{const{getPublicKey:a}=await import("../assets/pure-jrVhRVpB.js");return{getPublicKey:a}},__vite__mapDeps([0,1]));this.userPublicKey=n(new Uint8Array(t.match(/.{1,2}/g).map(a=>parseInt(a,16)))),console.log("Using anonymous key for user:",this.userPublicKey)}if(this.commentAs==="anon"&&!this.anonPrivateKeyHex){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,console.log("Ensured anonymous key is available")}if(this.userPublicKey){try{console.log("Fetching profile for user:",this.userPublicKey);const t=await this.nostrService.getProfile({pubkey:this.userPublicKey});console.log("Profile fetched for current user:",t),t?(this.currentUserProfile=t,console.log("Set currentUserProfile to:",this.currentUserProfile)):(this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"./assets/default_dp.png"},console.log("Set fallback currentUserProfile to:",this.currentUserProfile))}catch(t){console.error("Error fetching current user profile:",t),this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"./assets/default_dp.png"},console.log("Set error fallback currentUserProfile to:",this.currentUserProfile)}this.render()}});f(this,"submitComment",async t=>{if(t.trim()){this.userPublicKey||await this.initializeUser(),this.isSubmitting=!0,this.render();try{const n=[];if(n.push(["I",this.baseUrl]),this.replyingToComment){const{rootId:d}=this.findRootAndParent(this.replyingToComment);n.push(["e",d||this.replyingToComment,"","root"]),n.push(["e",this.replyingToComment,"","reply"]),n.push(["k","1111"])}const a={kind:1111,pubkey:this.userPublicKey,content:t.trim(),created_at:Math.floor(Date.now()/1e3),tags:n};let s;if(console.log(`[nostr-comment] Signing attempt - commentAs: ${this.commentAs}, hasNip07: ${!!window.nostr}, anonKey: ${!!this.anonPrivateKeyHex}, userKey: ${!!this.userPrivateKey}`),this.commentAs==="user"&&this.hasNip07&&window.nostr){console.log("[nostr-comment] Using NIP-07 extension to sign");try{s=await window.nostr.signEvent(a),console.log("[nostr-comment] Successfully signed with NIP-07 extension")}catch(d){throw console.error("[nostr-comment] Failed to sign with NIP-07 extension:",d),new Error("Failed to sign with NIP-07 extension. Please check if your extension is unlocked.")}}else if(this.commentAs==="anon"&&this.anonPrivateKeyHex){console.log("[nostr-comment] Using anonymous private key to sign");const{finalizeEvent:d}=await xe(async()=>{const{finalizeEvent:D}=await import("../assets/pure-jrVhRVpB.js");return{finalizeEvent:D}},__vite__mapDeps([0,1])),E=new Uint8Array(this.anonPrivateKeyHex.match(/.{1,2}/g).map(D=>parseInt(D,16)));s=d(a,E)}else if(this.userPrivateKey){console.log("[nostr-comment] Using local private key to sign (fallback)");const{finalizeEvent:d}=await xe(async()=>{const{finalizeEvent:D}=await import("../assets/pure-jrVhRVpB.js");return{finalizeEvent:D}},__vite__mapDeps([0,1])),E=new Uint8Array(this.userPrivateKey.match(/.{1,2}/g).map(D=>parseInt(D,16)));s=d(a,E)}else throw console.error("[nostr-comment] No signing method available - commentAs:",this.commentAs,"hasNip07:",this.hasNip07,"anonKey:",!!this.anonPrivateKeyHex,"userKey:",!!this.userPrivateKey),new Error("No signing method available. Please check your NIP-07 extension or switch to anonymous mode.");await new en(this.nostrService.getNDK(),s).publish();const h={id:s.id,pubkey:s.pubkey,content:s.content,created_at:s.created_at,replies:[],replyTo:this.replyingToComment||void 0,depth:0};if(this.currentUserProfile)h.userProfile=this.currentUserProfile;else{try{const d=await this.nostrService.getProfile({pubkey:s.pubkey});d&&(h.userProfile=d,this.currentUserProfile=d)}catch{console.warn("Could not fetch profile for new comment")}h.userProfile||(h.userProfile={name:this.commentAs==="anon"?"Anonymous":`User ${s.pubkey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${s.pubkey.slice(0,8)}`,image:"./assets/default_dp.png"})}this.replyingToComment?this.addReplyToComment(h,this.replyingToComment):this.comments.unshift(h);const g=n.find(d=>d[0]==="e"&&d[3]==="root"),y=n.find(d=>d[0]==="e"&&d[3]==="reply");if(console.log(`[nostr-comment] send: "${a.content}" root=${g?g[1]:"(none)"} parent=${y?y[1]:"(none)"} `),this.replyingToComment){const d=this.shadow.querySelector(".inline-reply-form"),E=d==null?void 0:d.querySelector('[data-role="comment-input"]');E&&(E.value="")}else{const d=this.shadow.querySelector(".modern-comment-form"),E=d==null?void 0:d.querySelector('[data-role="comment-input"]');E&&(E.value="")}this.replyingToComment=null}catch(n){console.error("Failed to submit comment:",n);let a="Failed to submit comment: "+(n instanceof Error?n.message:"Unknown error");n instanceof Error&&n.message.includes("NIP-07")&&(n.message.includes("extension is unlocked")?a="Please unlock your Nostr extension (nos2x/Alby) and try again.":n.message.includes("getPublicKey")?a="Please authorize this website in your Nostr extension.":a="Nostr extension error. Please check if your extension is working properly."),this.showError(a)}finally{this.isSubmitting=!1,this.render()}}});f(this,"addReplyToComment",(t,n)=>{const a=s=>{for(const c of s){if(c.id===n)return t.depth=(c.depth||0)+1,c.replies.push(t),c.replies.sort((h,g)=>h.created_at-g.created_at),!0;if(c.replies.length>0&&a(c.replies))return!0}return!1};a(this.comments)});f(this,"startReply",t=>{this.replyingToComment=null,this.render(),setTimeout(()=>{this.replyingToComment=t,this.render(),setTimeout(()=>{const n=this.shadow.querySelector(".inline-reply-form"),a=n==null?void 0:n.querySelector('[data-role="comment-input"]');a&&a.focus()},100)},10)});f(this,"cancelReply",()=>{this.replyingToComment=null,this.render()});this.shadow=this.attachShadow({mode:"open"})}findRootAndParent(t){let n,a;const s=(c,h,g)=>{var y;for(const d of c){const E=h??d.id;if(d.id===t)return n=E,a=g,!0;if((y=d.replies)!=null&&y.length&&s(d.replies,E,d.id))return!0}return!1};return s(this.comments),{rootId:n,parentId:a}}async connectedCallback(){if(!this.rendered)try{this.getTheme(),this.baseUrl=this.getBaseUrl(),await this.initializeUser(),await this.loadComments(),this.setupNip07StateMonitoring(),this.rendered=!0}catch(t){console.error("Error in connectedCallback:",t),this.isError=!0,this.errorMessage="Failed to initialize comment component",this.render()}}static get observedAttributes(){return["relays","theme","url","readonly","placeholder"]}async attributeChangedCallback(t,n,a){t==="relays"&&(this.nostrService.connectToNostr(this.getRelays()),await this.loadComments()),t==="theme"&&(this.getTheme(),this.render()),t==="url"&&(this.baseUrl=this.getBaseUrl(),await this.loadComments()),["readonly","placeholder"].includes(t)&&this.render()}disconnectedCallback(){this.removeEventListeners(),this.nip07MonitoringInterval&&(clearInterval(this.nip07MonitoringInterval),this.nip07MonitoringInterval=null)}attachEventListeners(){this.removeEventListeners(),this.shadow.querySelectorAll('[data-role="submit-comment"]').forEach(t=>{const n=a=>{a.preventDefault();const s=a.target.closest(".modern-comment-form, .inline-reply-form"),c=s==null?void 0:s.querySelector('[data-role="comment-input"]');c&&this.submitComment(c.value)};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}),this.shadow.querySelectorAll('[data-role="comment-input"]').forEach(t=>{const n=a=>{const s=a;s.key==="Enter"&&(s.ctrlKey||s.metaKey)&&(s.preventDefault(),this.submitComment(t.value))};t.addEventListener("keydown",n),this.eventListeners.push({element:t,type:"keydown",handler:n})}),this.shadow.querySelectorAll('[data-role="cancel-reply"]').forEach(t=>{const n=a=>{a.preventDefault(),this.cancelReply()};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}),this.shadow.querySelectorAll(".reply-btn").forEach(t=>{const n=a=>{a.preventDefault();const s=a.currentTarget.getAttribute("data-comment-id");s&&this.startReply(s)};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}),this.shadow.querySelectorAll('[data-role="toggle-as-user"]').forEach(t=>{if(!this.hasNip07)t.disabled=!0,t.title="NIP-07 extension not detected";else{const n=async a=>{a.preventDefault(),this.commentAs!=="user"&&(this.commentAs="user",this.userPrivateKey=null,this.anonPrivateKeyHex=null,await this.initializeUser())};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}}),this.shadow.querySelectorAll('[data-role="toggle-as-anon"]').forEach(t=>{t.disabled=!1;const n=async a=>{a.preventDefault(),this.commentAs!=="anon"&&(this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null,await this.initializeUser())};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})})}attachAvatarErrorHandlers(){this.shadow.querySelectorAll("img[src]").forEach(t=>{const n=a=>{const s=a.target;if(s.src===this.getDefaultAvatarUrl()){console.warn("Avatar fallback also failed, preventing infinite loop");return}s.src=this.getDefaultAvatarUrl()};t.addEventListener("error",n),this.eventListeners.push({element:t,type:"error",handler:n})})}removeEventListeners(){this.eventListeners.forEach(({element:t,type:n,handler:a})=>{t.removeEventListener(n,a)}),this.eventListeners=[]}showError(t){const n=document.createElement("div");n.className="nostr-comment-error",n.style.cssText=`
|
|
903
|
+
`}/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:Lt,setPrototypeOf:bt,isFrozen:cn,getPrototypeOf:mn,getOwnPropertyDescriptor:dn}=Object;let{freeze:I,seal:M,create:Pt}=Object,{apply:We,construct:Ge}=typeof Reflect<"u"&&Reflect;I||(I=function(r){return r});M||(M=function(r){return r});We||(We=function(r,t,n){return r.apply(t,n)});Ge||(Ge=function(r,t){return new r(...t)});const ve=C(Array.prototype.forEach),pn=C(Array.prototype.lastIndexOf),yt=C(Array.prototype.pop),se=C(Array.prototype.push),un=C(Array.prototype.splice),Ee=C(String.prototype.toLowerCase),ze=C(String.prototype.toString),xt=C(String.prototype.match),le=C(String.prototype.replace),fn=C(String.prototype.indexOf),hn=C(String.prototype.trim),z=C(Object.prototype.hasOwnProperty),N=C(RegExp.prototype.test),ce=gn(TypeError);function C(o){return function(r){r instanceof RegExp&&(r.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),a=1;a<t;a++)n[a-1]=arguments[a];return We(o,r,n)}}function gn(o){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return Ge(o,t)}}function u(o,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ee;bt&&bt(o,null);let n=r.length;for(;n--;){let a=r[n];if(typeof a=="string"){const s=t(a);s!==a&&(cn(r)||(r[n]=s),a=s)}o[a]=!0}return o}function bn(o){for(let r=0;r<o.length;r++)z(o,r)||(o[r]=null);return o}function G(o){const r=Pt(null);for(const[t,n]of Lt(o))z(o,t)&&(Array.isArray(n)?r[t]=bn(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=G(n):r[t]=n);return r}function me(o,r){for(;o!==null;){const n=dn(o,r);if(n){if(n.get)return C(n.get);if(typeof n.value=="function")return C(n.value)}o=mn(o)}function t(){return null}return t}const vt=I(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Fe=I(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),$e=I(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),yn=I(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),He=I(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),xn=I(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Tt=I(["#text"]),Et=I(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ke=I(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),At=I(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Te=I(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),vn=M(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Tn=M(/<%[\w\W]*|[\w\W]*%>/gm),En=M(/\$\{[\w\W]*/gm),An=M(/^data-[\-\w.\u00B7-\uFFFF]+$/),wn=M(/^aria-[\-\w]+$/),Nt=M(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),_n=M(/^(?:\w+script|data):/i),kn=M(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),It=M(/^html$/i),Sn=M(/^[a-z][.\w]*(-[.\w]+)+$/i);var wt=Object.freeze({__proto__:null,ARIA_ATTR:wn,ATTR_WHITESPACE:kn,CUSTOM_ELEMENT:Sn,DATA_ATTR:An,DOCTYPE_NAME:It,ERB_EXPR:Tn,IS_ALLOWED_URI:Nt,IS_SCRIPT_OR_DATA:_n,MUSTACHE_EXPR:vn,TMPLIT_EXPR:En});const de={element:1,text:3,progressingInstruction:7,comment:8,document:9},Rn=function(){return typeof window>"u"?null:window},Ln=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let n=null;const a="data-tt-policy-suffix";t&&t.hasAttribute(a)&&(n=t.getAttribute(a));const s="dompurify"+(n?"#"+n:"");try{return r.createPolicy(s,{createHTML(c){return c},createScriptURL(c){return c}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},_t=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Ct(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Rn();const r=m=>Ct(m);if(r.version="3.2.6",r.removed=[],!o||!o.document||o.document.nodeType!==de.document||!o.Element)return r.isSupported=!1,r;let{document:t}=o;const n=t,a=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:c,Node:h,Element:g,NodeFilter:y,NamedNodeMap:d=o.NamedNodeMap||o.MozNamedAttrMap,HTMLFormElement:E,DOMParser:D,trustedTypes:Y}=o,p=g.prototype,x=me(p,"cloneNode"),k=me(p,"remove"),te=me(p,"nextSibling"),U=me(p,"childNodes"),$=me(p,"parentNode");if(typeof c=="function"){const m=t.createElement("template");m.content&&m.content.ownerDocument&&(t=m.content.ownerDocument)}let L,ne="";const{implementation:Ae,createNodeIterator:Dt,createDocumentFragment:Ot,getElementsByTagName:Mt}=t,{importNode:Ut}=n;let P=_t();r.isSupported=typeof Lt=="function"&&typeof $=="function"&&Ae&&Ae.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:we,ERB_EXPR:_e,TMPLIT_EXPR:ke,DATA_ATTR:zt,ARIA_ATTR:Ft,IS_SCRIPT_OR_DATA:$t,ATTR_WHITESPACE:Be,CUSTOM_ELEMENT:Ht}=wt;let{IS_ALLOWED_URI:Ye}=wt,A=null;const qe=u({},[...vt,...Fe,...$e,...He,...Tt]);let _=null;const Ve=u({},[...Et,...Ke,...At,...Te]);let v=Object.seal(Pt(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),oe=null,Se=null,je=!0,Re=!0,Xe=!1,Ze=!0,V=!1,pe=!0,q=!1,Le=!1,Pe=!1,j=!1,ue=!1,fe=!1,Qe=!0,Je=!1;const Kt="user-content-";let Ne=!0,re=!1,X={},Z=null;const et=u({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let tt=null;const nt=u({},["audio","video","img","source","image","track"]);let Ie=null;const ot=u({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),he="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",H="http://www.w3.org/1999/xhtml";let Q=H,Ce=!1,De=null;const Wt=u({},[he,ge,H],ze);let be=u({},["mi","mo","mn","ms","mtext"]),ye=u({},["annotation-xml"]);const Gt=u({},["title","style","font","a","script"]);let ie=null;const Bt=["application/xhtml+xml","text/html"],Yt="text/html";let w=null,J=null;const qt=t.createElement("form"),rt=function(e){return e instanceof RegExp||e instanceof Function},Oe=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(J&&J===e)){if((!e||typeof e!="object")&&(e={}),e=G(e),ie=Bt.indexOf(e.PARSER_MEDIA_TYPE)===-1?Yt:e.PARSER_MEDIA_TYPE,w=ie==="application/xhtml+xml"?ze:Ee,A=z(e,"ALLOWED_TAGS")?u({},e.ALLOWED_TAGS,w):qe,_=z(e,"ALLOWED_ATTR")?u({},e.ALLOWED_ATTR,w):Ve,De=z(e,"ALLOWED_NAMESPACES")?u({},e.ALLOWED_NAMESPACES,ze):Wt,Ie=z(e,"ADD_URI_SAFE_ATTR")?u(G(ot),e.ADD_URI_SAFE_ATTR,w):ot,tt=z(e,"ADD_DATA_URI_TAGS")?u(G(nt),e.ADD_DATA_URI_TAGS,w):nt,Z=z(e,"FORBID_CONTENTS")?u({},e.FORBID_CONTENTS,w):et,oe=z(e,"FORBID_TAGS")?u({},e.FORBID_TAGS,w):G({}),Se=z(e,"FORBID_ATTR")?u({},e.FORBID_ATTR,w):G({}),X=z(e,"USE_PROFILES")?e.USE_PROFILES:!1,je=e.ALLOW_ARIA_ATTR!==!1,Re=e.ALLOW_DATA_ATTR!==!1,Xe=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ze=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,pe=e.SAFE_FOR_XML!==!1,q=e.WHOLE_DOCUMENT||!1,j=e.RETURN_DOM||!1,ue=e.RETURN_DOM_FRAGMENT||!1,fe=e.RETURN_TRUSTED_TYPE||!1,Pe=e.FORCE_BODY||!1,Qe=e.SANITIZE_DOM!==!1,Je=e.SANITIZE_NAMED_PROPS||!1,Ne=e.KEEP_CONTENT!==!1,re=e.IN_PLACE||!1,Ye=e.ALLOWED_URI_REGEXP||Nt,Q=e.NAMESPACE||H,be=e.MATHML_TEXT_INTEGRATION_POINTS||be,ye=e.HTML_INTEGRATION_POINTS||ye,v=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&rt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(v.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&rt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(v.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(v.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),V&&(Re=!1),ue&&(j=!0),X&&(A=u({},Tt),_=[],X.html===!0&&(u(A,vt),u(_,Et)),X.svg===!0&&(u(A,Fe),u(_,Ke),u(_,Te)),X.svgFilters===!0&&(u(A,$e),u(_,Ke),u(_,Te)),X.mathMl===!0&&(u(A,He),u(_,At),u(_,Te))),e.ADD_TAGS&&(A===qe&&(A=G(A)),u(A,e.ADD_TAGS,w)),e.ADD_ATTR&&(_===Ve&&(_=G(_)),u(_,e.ADD_ATTR,w)),e.ADD_URI_SAFE_ATTR&&u(Ie,e.ADD_URI_SAFE_ATTR,w),e.FORBID_CONTENTS&&(Z===et&&(Z=G(Z)),u(Z,e.FORBID_CONTENTS,w)),Ne&&(A["#text"]=!0),q&&u(A,["html","head","body"]),A.table&&(u(A,["tbody"]),delete oe.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!="function")throw ce('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ce('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');L=e.TRUSTED_TYPES_POLICY,ne=L.createHTML("")}else L===void 0&&(L=Ln(Y,a)),L!==null&&typeof ne=="string"&&(ne=L.createHTML(""));I&&I(e),J=e}},it=u({},[...Fe,...$e,...yn]),at=u({},[...He,...xn]),Vt=function(e){let i=$(e);(!i||!i.tagName)&&(i={namespaceURI:Q,tagName:"template"});const l=Ee(e.tagName),b=Ee(i.tagName);return De[e.namespaceURI]?e.namespaceURI===ge?i.namespaceURI===H?l==="svg":i.namespaceURI===he?l==="svg"&&(b==="annotation-xml"||be[b]):!!it[l]:e.namespaceURI===he?i.namespaceURI===H?l==="math":i.namespaceURI===ge?l==="math"&&ye[b]:!!at[l]:e.namespaceURI===H?i.namespaceURI===ge&&!ye[b]||i.namespaceURI===he&&!be[b]?!1:!at[l]&&(Gt[l]||!it[l]):!!(ie==="application/xhtml+xml"&&De[e.namespaceURI]):!1},F=function(e){se(r.removed,{element:e});try{$(e).removeChild(e)}catch{k(e)}},ee=function(e,i){try{se(r.removed,{attribute:i.getAttributeNode(e),from:i})}catch{se(r.removed,{attribute:null,from:i})}if(i.removeAttribute(e),e==="is")if(j||ue)try{F(i)}catch{}else try{i.setAttribute(e,"")}catch{}},st=function(e){let i=null,l=null;if(Pe)e="<remove></remove>"+e;else{const T=xt(e,/^[\r\n\t ]+/);l=T&&T[0]}ie==="application/xhtml+xml"&&Q===H&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const b=L?L.createHTML(e):e;if(Q===H)try{i=new D().parseFromString(b,ie)}catch{}if(!i||!i.documentElement){i=Ae.createDocument(Q,"template",null);try{i.documentElement.innerHTML=Ce?ne:b}catch{}}const S=i.body||i.documentElement;return e&&l&&S.insertBefore(t.createTextNode(l),S.childNodes[0]||null),Q===H?Mt.call(i,q?"html":"body")[0]:q?i.documentElement:S},lt=function(e){return Dt.call(e.ownerDocument||e,e,y.SHOW_ELEMENT|y.SHOW_COMMENT|y.SHOW_TEXT|y.SHOW_PROCESSING_INSTRUCTION|y.SHOW_CDATA_SECTION,null)},Me=function(e){return e instanceof E&&(typeof e.nodeName!="string"||typeof e.textContent!="string"||typeof e.removeChild!="function"||!(e.attributes instanceof d)||typeof e.removeAttribute!="function"||typeof e.setAttribute!="function"||typeof e.namespaceURI!="string"||typeof e.insertBefore!="function"||typeof e.hasChildNodes!="function")},ct=function(e){return typeof h=="function"&&e instanceof h};function K(m,e,i){ve(m,l=>{l.call(r,e,i,J)})}const mt=function(e){let i=null;if(K(P.beforeSanitizeElements,e,null),Me(e))return F(e),!0;const l=w(e.nodeName);if(K(P.uponSanitizeElement,e,{tagName:l,allowedTags:A}),pe&&e.hasChildNodes()&&!ct(e.firstElementChild)&&N(/<[/\w!]/g,e.innerHTML)&&N(/<[/\w!]/g,e.textContent)||e.nodeType===de.progressingInstruction||pe&&e.nodeType===de.comment&&N(/<[/\w]/g,e.data))return F(e),!0;if(!A[l]||oe[l]){if(!oe[l]&&pt(l)&&(v.tagNameCheck instanceof RegExp&&N(v.tagNameCheck,l)||v.tagNameCheck instanceof Function&&v.tagNameCheck(l)))return!1;if(Ne&&!Z[l]){const b=$(e)||e.parentNode,S=U(e)||e.childNodes;if(S&&b){const T=S.length;for(let O=T-1;O>=0;--O){const W=x(S[O],!0);W.__removalCount=(e.__removalCount||0)+1,b.insertBefore(W,te(e))}}}return F(e),!0}return e instanceof g&&!Vt(e)||(l==="noscript"||l==="noembed"||l==="noframes")&&N(/<\/no(script|embed|frames)/i,e.innerHTML)?(F(e),!0):(V&&e.nodeType===de.text&&(i=e.textContent,ve([we,_e,ke],b=>{i=le(i,b," ")}),e.textContent!==i&&(se(r.removed,{element:e.cloneNode()}),e.textContent=i)),K(P.afterSanitizeElements,e,null),!1)},dt=function(e,i,l){if(Qe&&(i==="id"||i==="name")&&(l in t||l in qt))return!1;if(!(Re&&!Se[i]&&N(zt,i))){if(!(je&&N(Ft,i))){if(!_[i]||Se[i]){if(!(pt(e)&&(v.tagNameCheck instanceof RegExp&&N(v.tagNameCheck,e)||v.tagNameCheck instanceof Function&&v.tagNameCheck(e))&&(v.attributeNameCheck instanceof RegExp&&N(v.attributeNameCheck,i)||v.attributeNameCheck instanceof Function&&v.attributeNameCheck(i))||i==="is"&&v.allowCustomizedBuiltInElements&&(v.tagNameCheck instanceof RegExp&&N(v.tagNameCheck,l)||v.tagNameCheck instanceof Function&&v.tagNameCheck(l))))return!1}else if(!Ie[i]){if(!N(Ye,le(l,Be,""))){if(!((i==="src"||i==="xlink:href"||i==="href")&&e!=="script"&&fn(l,"data:")===0&&tt[e])){if(!(Xe&&!N($t,le(l,Be,"")))){if(l)return!1}}}}}}return!0},pt=function(e){return e!=="annotation-xml"&&xt(e,Ht)},ut=function(e){K(P.beforeSanitizeAttributes,e,null);const{attributes:i}=e;if(!i||Me(e))return;const l={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:_,forceKeepAttr:void 0};let b=i.length;for(;b--;){const S=i[b],{name:T,namespaceURI:O,value:W}=S,ae=w(T),Ue=W;let R=T==="value"?Ue:hn(Ue);if(l.attrName=ae,l.attrValue=R,l.keepAttr=!0,l.forceKeepAttr=void 0,K(P.uponSanitizeAttribute,e,l),R=l.attrValue,Je&&(ae==="id"||ae==="name")&&(ee(T,e),R=Kt+R),pe&&N(/((--!?|])>)|<\/(style|title)/i,R)){ee(T,e);continue}if(l.forceKeepAttr)continue;if(!l.keepAttr){ee(T,e);continue}if(!Ze&&N(/\/>/i,R)){ee(T,e);continue}V&&ve([we,_e,ke],ht=>{R=le(R,ht," ")});const ft=w(e.nodeName);if(!dt(ft,ae,R)){ee(T,e);continue}if(L&&typeof Y=="object"&&typeof Y.getAttributeType=="function"&&!O)switch(Y.getAttributeType(ft,ae)){case"TrustedHTML":{R=L.createHTML(R);break}case"TrustedScriptURL":{R=L.createScriptURL(R);break}}if(R!==Ue)try{O?e.setAttributeNS(O,T,R):e.setAttribute(T,R),Me(e)?F(e):yt(r.removed)}catch{ee(T,e)}}K(P.afterSanitizeAttributes,e,null)},jt=function m(e){let i=null;const l=lt(e);for(K(P.beforeSanitizeShadowDOM,e,null);i=l.nextNode();)K(P.uponSanitizeShadowNode,i,null),mt(i),ut(i),i.content instanceof s&&m(i.content);K(P.afterSanitizeShadowDOM,e,null)};return r.sanitize=function(m){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,l=null,b=null,S=null;if(Ce=!m,Ce&&(m="<!-->"),typeof m!="string"&&!ct(m))if(typeof m.toString=="function"){if(m=m.toString(),typeof m!="string")throw ce("dirty is not a string, aborting")}else throw ce("toString is not a function");if(!r.isSupported)return m;if(Le||Oe(e),r.removed=[],typeof m=="string"&&(re=!1),re){if(m.nodeName){const W=w(m.nodeName);if(!A[W]||oe[W])throw ce("root node is forbidden and cannot be sanitized in-place")}}else if(m instanceof h)i=st("<!---->"),l=i.ownerDocument.importNode(m,!0),l.nodeType===de.element&&l.nodeName==="BODY"||l.nodeName==="HTML"?i=l:i.appendChild(l);else{if(!j&&!V&&!q&&m.indexOf("<")===-1)return L&&fe?L.createHTML(m):m;if(i=st(m),!i)return j?null:fe?ne:""}i&&Pe&&F(i.firstChild);const T=lt(re?m:i);for(;b=T.nextNode();)mt(b),ut(b),b.content instanceof s&&jt(b.content);if(re)return m;if(j){if(ue)for(S=Ot.call(i.ownerDocument);i.firstChild;)S.appendChild(i.firstChild);else S=i;return(_.shadowroot||_.shadowrootmode)&&(S=Ut.call(n,S,!0)),S}let O=q?i.outerHTML:i.innerHTML;return q&&A["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&N(It,i.ownerDocument.doctype.name)&&(O="<!DOCTYPE "+i.ownerDocument.doctype.name+`>
|
|
904
|
+
`+O),V&&ve([we,_e,ke],W=>{O=le(O,W," ")}),L&&fe?L.createHTML(O):O},r.setConfig=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Oe(m),Le=!0},r.clearConfig=function(){J=null,Le=!1},r.isValidAttribute=function(m,e,i){J||Oe({});const l=w(m),b=w(e);return dt(l,b,i)},r.addHook=function(m,e){typeof e=="function"&&se(P[m],e)},r.removeHook=function(m,e){if(e!==void 0){const i=pn(P[m],e);return i===-1?void 0:un(P[m],i,1)[0]}return yt(P[m])},r.removeHooks=function(m){P[m]=[]},r.removeAllHooks=function(){P=_t()},r}var Pn=Ct();class Nn extends HTMLElement{constructor(){super();f(this,"rendered",!1);f(this,"nostrService",Qt.getInstance());f(this,"shadow");f(this,"theme","light");f(this,"isLoading",!0);f(this,"isError",!1);f(this,"errorMessage","");f(this,"comments",[]);f(this,"baseUrl","");f(this,"userPublicKey",null);f(this,"userPrivateKey",null);f(this,"currentUserProfile",null);f(this,"isSubmitting",!1);f(this,"replyingToComment",null);f(this,"commentAs","user");f(this,"hasNip07",!1);f(this,"anonPrivateKeyHex",null);f(this,"eventListeners",[]);f(this,"nip07MonitoringInterval",null);f(this,"loadVersion",0);f(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(",").map(n=>n.trim()):Jt});f(this,"getTheme",()=>{this.theme="light";const t=this.getAttribute("theme");t&&(["light","dark"].includes(t)?this.theme=t:console.warn(`Invalid theme '${t}'. Accepted values are 'light', 'dark'`))});f(this,"getBaseUrl",()=>{const t=this.getAttribute("url");return t?gt(t):gt(window.location.href)});f(this,"detectNip07Extension",()=>{const t=window.nostr;return t?typeof t.getPublicKey=="function"&&typeof t.signEvent=="function"?!0:(console.warn("NIP-07 extension detected but missing required methods"),!1):!1});f(this,"handleNip07StateChange",async()=>{const t=this.hasNip07,n=this.detectNip07Extension();if(t!==n&&(console.log("NIP-07 extension state changed:",n),this.hasNip07=n,n&&this.commentAs==="user"))try{await this.initializeUser(),this.render()}catch(a){console.warn("Failed to reconnect to NIP-07 extension:",a)}});f(this,"setupNip07StateMonitoring",()=>{const t=setInterval(async()=>{document.contains(this)&&await this.handleNip07StateChange()},2e3);this.nip07MonitoringInterval=t});f(this,"loadComments",async()=>{this.loadVersion++;const t=this.loadVersion;try{this.isLoading=!0,this.isError=!1,this.render();const n=this.getRelays();await this.nostrService.connectToNostr(n);const a={kinds:[1111],"#I":[this.baseUrl],limit:200},s=await this.nostrService.getNDK().fetchEvents(a),c=Array.from(s),h=new Map;c.forEach(p=>h.set(p.id,{content:p.content,id:p.id,tags:p.tags}));const g=[],y=new Set;for(const p of c){let x;const k=(p.tags||[]).filter(U=>U[0]==="e");for(let U=k.length-1;U>=0;U--){const $=k[U];if($[3]==="reply"){x=$[1];break}}if(!x&&k.length>0){const U=k.filter($=>$[3]!=="root");U.length>0?x=U[U.length-1][1]:x=k[k.length-1][1]}const te={id:p.id,pubkey:p.pubkey,content:p.content,created_at:p.created_at,replies:[],replyTo:x,depth:0};y.add(p.pubkey),g.push(te)}const d=Array.from(y).map(async p=>{try{console.log("Fetching profile for pubkey:",p);const x=await this.nostrService.getProfile({pubkey:p});return console.log("Profile fetched for",p,":",x),{pubkey:p,profile:x}}catch(x){return console.warn("Failed to fetch profile for:",p,x),{pubkey:p,profile:null}}}),E=await Promise.allSettled(d),D=new Map;if(E.forEach(p=>{if(p.status==="fulfilled"){const{pubkey:x,profile:k}=p.value;D.set(x,k)}}),g.forEach(p=>{p.userProfile=D.get(p.pubkey)||void 0,console.log("Attached profile to comment:",p.pubkey,"Profile:",p.userProfile)}),t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting");return}this.comments=this.buildCommentTree(g);const Y=new Map;this.comments.forEach(p=>{const x=[p];for(;x.length;){const k=x.pop();Y.set(k.id,k),k.replies.forEach(te=>x.push(te))}}),g.forEach(p=>{const x=p.replyTo?Y.get(p.replyTo):void 0,k=x?x.content:"(no parent)";console.log(`[nostr-comment] recv: "${p.content}" -> parent: ${k}`)})}catch(n){if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting error handling");return}this.isError=!0,this.errorMessage=n instanceof Error?n.message:"Failed to load comments",console.error("Error loading comments:",n)}finally{if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting final state update");return}this.isLoading=!1,this.render()}});f(this,"buildCommentTree",t=>{const n=new Map,a=[];t.forEach(c=>{n.set(c.id,c)}),t.forEach(c=>{if(c.replyTo&&n.has(c.replyTo)){const h=n.get(c.replyTo);h.replies.push(c),h.replies.sort((g,y)=>g.created_at-y.created_at)}else a.push(c)});const s=(c,h)=>{for(const g of c)g.depth=h,g.replies&&g.replies.length&&s(g.replies,h+1)};return s(a,0),a.sort((c,h)=>h.created_at-c.created_at)});f(this,"initializeUser",async()=>{if(this.hasNip07=this.detectNip07Extension(),console.log("NIP-07 extension detected:",this.hasNip07),this.hasNip07&&this.commentAs==="user")try{this.userPublicKey=await window.nostr.getPublicKey(),console.log("Successfully connected to NIP-07 extension, public key:",this.userPublicKey),this.userPrivateKey=null,this.anonPrivateKeyHex=null}catch(t){console.warn("NIP-07 extension available but failed to get public key:",t),this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null}if(!this.userPublicKey){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,this.userPrivateKey=t;const{getPublicKey:n}=await xe(async()=>{const{getPublicKey:a}=await import("../assets/pure-jrVhRVpB.js");return{getPublicKey:a}},__vite__mapDeps([0,1]));this.userPublicKey=n(new Uint8Array(t.match(/.{1,2}/g).map(a=>parseInt(a,16)))),console.log("Using anonymous key for user:",this.userPublicKey)}if(this.commentAs==="anon"&&!this.anonPrivateKeyHex){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,console.log("Ensured anonymous key is available")}if(this.userPublicKey){try{console.log("Fetching profile for user:",this.userPublicKey);const t=await this.nostrService.getProfile({pubkey:this.userPublicKey});console.log("Profile fetched for current user:",t),t?(this.currentUserProfile=t,console.log("Set currentUserProfile to:",this.currentUserProfile)):(this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"../../assets/default_dp.png"},console.log("Set fallback currentUserProfile to:",this.currentUserProfile))}catch(t){console.error("Error fetching current user profile:",t),this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"../../assets/default_dp.png"},console.log("Set error fallback currentUserProfile to:",this.currentUserProfile)}this.render()}});f(this,"submitComment",async t=>{if(t.trim()){this.userPublicKey||await this.initializeUser(),this.isSubmitting=!0,this.render();try{const n=[];if(n.push(["I",this.baseUrl]),this.replyingToComment){const{rootId:d}=this.findRootAndParent(this.replyingToComment);n.push(["e",d||this.replyingToComment,"","root"]),n.push(["e",this.replyingToComment,"","reply"]),n.push(["k","1111"])}const a={kind:1111,pubkey:this.userPublicKey,content:t.trim(),created_at:Math.floor(Date.now()/1e3),tags:n};let s;if(console.log(`[nostr-comment] Signing attempt - commentAs: ${this.commentAs}, hasNip07: ${!!window.nostr}, anonKey: ${!!this.anonPrivateKeyHex}, userKey: ${!!this.userPrivateKey}`),this.commentAs==="user"&&this.hasNip07&&window.nostr){console.log("[nostr-comment] Using NIP-07 extension to sign");try{s=await window.nostr.signEvent(a),console.log("[nostr-comment] Successfully signed with NIP-07 extension")}catch(d){throw console.error("[nostr-comment] Failed to sign with NIP-07 extension:",d),new Error("Failed to sign with NIP-07 extension. Please check if your extension is unlocked.")}}else if(this.commentAs==="anon"&&this.anonPrivateKeyHex){console.log("[nostr-comment] Using anonymous private key to sign");const{finalizeEvent:d}=await xe(async()=>{const{finalizeEvent:D}=await import("../assets/pure-jrVhRVpB.js");return{finalizeEvent:D}},__vite__mapDeps([0,1])),E=new Uint8Array(this.anonPrivateKeyHex.match(/.{1,2}/g).map(D=>parseInt(D,16)));s=d(a,E)}else if(this.userPrivateKey){console.log("[nostr-comment] Using local private key to sign (fallback)");const{finalizeEvent:d}=await xe(async()=>{const{finalizeEvent:D}=await import("../assets/pure-jrVhRVpB.js");return{finalizeEvent:D}},__vite__mapDeps([0,1])),E=new Uint8Array(this.userPrivateKey.match(/.{1,2}/g).map(D=>parseInt(D,16)));s=d(a,E)}else throw console.error("[nostr-comment] No signing method available - commentAs:",this.commentAs,"hasNip07:",this.hasNip07,"anonKey:",!!this.anonPrivateKeyHex,"userKey:",!!this.userPrivateKey),new Error("No signing method available. Please check your NIP-07 extension or switch to anonymous mode.");await new en(this.nostrService.getNDK(),s).publish();const h={id:s.id,pubkey:s.pubkey,content:s.content,created_at:s.created_at,replies:[],replyTo:this.replyingToComment||void 0,depth:0};if(this.currentUserProfile)h.userProfile=this.currentUserProfile;else{try{const d=await this.nostrService.getProfile({pubkey:s.pubkey});d&&(h.userProfile=d,this.currentUserProfile=d)}catch{console.warn("Could not fetch profile for new comment")}h.userProfile||(h.userProfile={name:this.commentAs==="anon"?"Anonymous":`User ${s.pubkey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${s.pubkey.slice(0,8)}`,image:"../../assets/default_dp.png"})}this.replyingToComment?this.addReplyToComment(h,this.replyingToComment):this.comments.unshift(h);const g=n.find(d=>d[0]==="e"&&d[3]==="root"),y=n.find(d=>d[0]==="e"&&d[3]==="reply");if(console.log(`[nostr-comment] send: "${a.content}" root=${g?g[1]:"(none)"} parent=${y?y[1]:"(none)"} `),this.replyingToComment){const d=this.shadow.querySelector(".inline-reply-form"),E=d==null?void 0:d.querySelector('[data-role="comment-input"]');E&&(E.value="")}else{const d=this.shadow.querySelector(".modern-comment-form"),E=d==null?void 0:d.querySelector('[data-role="comment-input"]');E&&(E.value="")}this.replyingToComment=null}catch(n){console.error("Failed to submit comment:",n);let a="Failed to submit comment: "+(n instanceof Error?n.message:"Unknown error");n instanceof Error&&n.message.includes("NIP-07")&&(n.message.includes("extension is unlocked")?a="Please unlock your Nostr extension (nos2x/Alby) and try again.":n.message.includes("getPublicKey")?a="Please authorize this website in your Nostr extension.":a="Nostr extension error. Please check if your extension is working properly."),this.showError(a)}finally{this.isSubmitting=!1,this.render()}}});f(this,"addReplyToComment",(t,n)=>{const a=s=>{for(const c of s){if(c.id===n)return t.depth=(c.depth||0)+1,c.replies.push(t),c.replies.sort((h,g)=>h.created_at-g.created_at),!0;if(c.replies.length>0&&a(c.replies))return!0}return!1};a(this.comments)});f(this,"startReply",t=>{this.replyingToComment=null,this.render(),setTimeout(()=>{this.replyingToComment=t,this.render(),setTimeout(()=>{const n=this.shadow.querySelector(".inline-reply-form"),a=n==null?void 0:n.querySelector('[data-role="comment-input"]');a&&a.focus()},100)},10)});f(this,"cancelReply",()=>{this.replyingToComment=null,this.render()});this.shadow=this.attachShadow({mode:"open"})}findRootAndParent(t){let n,a;const s=(c,h,g)=>{var y;for(const d of c){const E=h??d.id;if(d.id===t)return n=E,a=g,!0;if((y=d.replies)!=null&&y.length&&s(d.replies,E,d.id))return!0}return!1};return s(this.comments),{rootId:n,parentId:a}}async connectedCallback(){if(!this.rendered)try{this.getTheme(),this.baseUrl=this.getBaseUrl(),await this.initializeUser(),await this.loadComments(),this.setupNip07StateMonitoring(),this.rendered=!0}catch(t){console.error("Error in connectedCallback:",t),this.isError=!0,this.errorMessage="Failed to initialize comment component",this.render()}}static get observedAttributes(){return["relays","theme","url","readonly","placeholder"]}async attributeChangedCallback(t,n,a){t==="relays"&&(this.nostrService.connectToNostr(this.getRelays()),await this.loadComments()),t==="theme"&&(this.getTheme(),this.render()),t==="url"&&(this.baseUrl=this.getBaseUrl(),await this.loadComments()),["readonly","placeholder"].includes(t)&&this.render()}disconnectedCallback(){this.removeEventListeners(),this.nip07MonitoringInterval&&(clearInterval(this.nip07MonitoringInterval),this.nip07MonitoringInterval=null)}attachEventListeners(){this.removeEventListeners(),this.shadow.querySelectorAll('[data-role="submit-comment"]').forEach(t=>{const n=a=>{a.preventDefault();const s=a.target.closest(".modern-comment-form, .inline-reply-form"),c=s==null?void 0:s.querySelector('[data-role="comment-input"]');c&&this.submitComment(c.value)};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}),this.shadow.querySelectorAll('[data-role="comment-input"]').forEach(t=>{const n=a=>{const s=a;s.key==="Enter"&&(s.ctrlKey||s.metaKey)&&(s.preventDefault(),this.submitComment(t.value))};t.addEventListener("keydown",n),this.eventListeners.push({element:t,type:"keydown",handler:n})}),this.shadow.querySelectorAll('[data-role="cancel-reply"]').forEach(t=>{const n=a=>{a.preventDefault(),this.cancelReply()};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}),this.shadow.querySelectorAll(".reply-btn").forEach(t=>{const n=a=>{a.preventDefault();const s=a.currentTarget.getAttribute("data-comment-id");s&&this.startReply(s)};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}),this.shadow.querySelectorAll('[data-role="toggle-as-user"]').forEach(t=>{if(!this.hasNip07)t.disabled=!0,t.title="NIP-07 extension not detected";else{const n=async a=>{a.preventDefault(),this.commentAs!=="user"&&(this.commentAs="user",this.userPrivateKey=null,this.anonPrivateKeyHex=null,await this.initializeUser())};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})}}),this.shadow.querySelectorAll('[data-role="toggle-as-anon"]').forEach(t=>{t.disabled=!1;const n=async a=>{a.preventDefault(),this.commentAs!=="anon"&&(this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null,await this.initializeUser())};t.addEventListener("click",n),this.eventListeners.push({element:t,type:"click",handler:n})})}attachAvatarErrorHandlers(){this.shadow.querySelectorAll("img[src]").forEach(t=>{const n=a=>{const s=a.target;if(s.src===this.getDefaultAvatarUrl()){console.warn("Avatar fallback also failed, preventing infinite loop");return}s.src=this.getDefaultAvatarUrl()};t.addEventListener("error",n),this.eventListeners.push({element:t,type:"error",handler:n})})}removeEventListeners(){this.eventListeners.forEach(({element:t,type:n,handler:a})=>{t.removeEventListener(n,a)}),this.eventListeners=[]}showError(t){const n=document.createElement("div");n.className="nostr-comment-error",n.style.cssText=`
|
|
905
905
|
position: fixed;
|
|
906
906
|
top: 20px;
|
|
907
907
|
right: 20px;
|
|
@@ -915,7 +915,7 @@ var Xt=Object.defineProperty;var Zt=(o,r,t)=>r in o?Xt(o,r,{enumerable:!0,config
|
|
|
915
915
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
916
916
|
font-size: 14px;
|
|
917
917
|
line-height: 1.4;
|
|
918
|
-
`,n.textContent=t,document.body.appendChild(n);const a=t.includes("NIP-07")?8e3:5e3;setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},a)}getDefaultAvatarUrl(){try{return new URL("
|
|
918
|
+
`,n.textContent=t,document.body.appendChild(n);const a=t.includes("NIP-07")?8e3:5e3;setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},a)}getDefaultAvatarUrl(){try{return new URL("/assets/default_dp-NQ3TGrtT.png",import.meta.url).toString()}catch(t){return console.warn("Failed to resolve default avatar URL with import.meta.url, using relative path:",t),"../../assets/default_dp.png"}}async ensureAnonKey(){const t="nostr-comment-anon-private-key";try{const s=localStorage.getItem(t);if(s&&s.match(/^[a-f0-9]{64}$/))return s}catch(s){console.warn("Failed to read from localStorage:",s)}const{generateSecretKey:n}=await xe(async()=>{const{generateSecretKey:s}=await import("../assets/pure-jrVhRVpB.js");return{generateSecretKey:s}},__vite__mapDeps([0,1])),a=Array.from(n()).map(s=>s.toString(16).padStart(2,"0")).join("");try{localStorage.setItem(t,a)}catch(s){console.warn("Failed to write to localStorage, using ephemeral key:",s)}return a}render(){this.classList.toggle("dark",this.theme==="dark"),this.classList.toggle("loading",this.isLoading),this.classList.toggle("error-container",this.isError);const t=this.hasAttribute("readonly"),n=this.getAttribute("placeholder")||"Write a comment...",a=sn(this.isLoading,this.isError,this.errorMessage,this.comments,t,n,this.isSubmitting,this.currentUserProfile,this.replyingToComment,this.commentAs,this.hasNip07),s=Pn.sanitize(a,{ALLOWED_TAGS:["div","span","button","textarea","img","a","h3","h4","p","ul","li","small","strong","em"],ALLOWED_ATTR:["class","data-role","data-comment-id","data-depth","src","alt","href","target","rel","placeholder","rows","disabled"],ALLOW_DATA_ATTR:!1});this.shadow.innerHTML=`
|
|
919
919
|
${ln(this.theme)}
|
|
920
920
|
<div class="nostr-comment-wrapper">
|
|
921
921
|
${s}
|