diff --git a/README.md b/README.md index db83d42..18792b7 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,11 @@ programmed relays.

This is an installable personal website that is accessible through chrome-based and firefox browsers. The website is built with PWA Builder and Lit Web Components. It utilizes the Nostr -protocol to fetch kinds 0, 1, and 30023 notes from a personal relay and display then (profile metadata, short text, and long form notes.)

+protocol to fetch profile metadata, short text, and long form notes (event kinds 0, 1, and 30023) from a relay.

-

If you're on safari browsers, try visiting the webpage then tapping on the arrow +

If you're on any chrome-based, firefox or safari browser try visiting the webpage then tapping on the arrow pointing up in the bottom toolbar. Scroll down a bit to tap on "Add to Home Screen". If you're on a chromium-based browser you should be able to do the same.

@@ -32,7 +32,7 @@ If you're on a chromium-based browser you should be able to do the same.

  • refactor
  • dropdown menu a la Medium
  • long form blog view
  • -
  • +
  • include instructions as preloaded content
  • @@ -41,6 +41,6 @@ If you're on a chromium-based browser you should be able to do the same.

    ## How to try it out -Visit https://miguelalmodo.com/dist to try installing to your +Visit https://miguelalmodo.com/dist2 to try installing to your smartphone home screen. diff --git a/dist2/assets/icons/192x192.png b/dist2/assets/icons/192x192.png new file mode 100644 index 0000000..e63fa2f Binary files /dev/null and b/dist2/assets/icons/192x192.png differ diff --git a/dist2/assets/icons/24x24.png b/dist2/assets/icons/24x24.png new file mode 100644 index 0000000..067fbdb Binary files /dev/null and b/dist2/assets/icons/24x24.png differ diff --git a/dist2/assets/icons/48x48.png b/dist2/assets/icons/48x48.png new file mode 100644 index 0000000..f3d4666 Binary files /dev/null and b/dist2/assets/icons/48x48.png differ diff --git a/dist2/assets/icons/512x512.png b/dist2/assets/icons/512x512.png new file mode 100644 index 0000000..59ae864 Binary files /dev/null and b/dist2/assets/icons/512x512.png differ diff --git a/dist2/assets/icons/casto_kingdom.png b/dist2/assets/icons/casto_kingdom.png new file mode 100755 index 0000000..ba4a4b8 Binary files /dev/null and b/dist2/assets/icons/casto_kingdom.png differ diff --git a/dist2/assets/icons/icon_192.png b/dist2/assets/icons/icon_192.png new file mode 100644 index 0000000..897fa3d Binary files /dev/null and b/dist2/assets/icons/icon_192.png differ diff --git a/dist2/assets/icons/icon_24.png b/dist2/assets/icons/icon_24.png new file mode 100644 index 0000000..cadeeda Binary files /dev/null and b/dist2/assets/icons/icon_24.png differ diff --git a/dist2/assets/icons/icon_48.png b/dist2/assets/icons/icon_48.png new file mode 100644 index 0000000..69d5b2e Binary files /dev/null and b/dist2/assets/icons/icon_48.png differ diff --git a/dist2/assets/icons/icon_512.png b/dist2/assets/icons/icon_512.png new file mode 100644 index 0000000..238a51b Binary files /dev/null and b/dist2/assets/icons/icon_512.png differ diff --git a/dist2/assets/img/default_pfp.png b/dist2/assets/img/default_pfp.png new file mode 100644 index 0000000..0f5b1ff Binary files /dev/null and b/dist2/assets/img/default_pfp.png differ diff --git a/dist2/assets/readme/build-output.png b/dist2/assets/readme/build-output.png new file mode 100644 index 0000000..749e512 Binary files /dev/null and b/dist2/assets/readme/build-output.png differ diff --git a/dist2/assets/readme/codespace-button.png b/dist2/assets/readme/codespace-button.png new file mode 100644 index 0000000..dadeb9f Binary files /dev/null and b/dist2/assets/readme/codespace-button.png differ diff --git a/dist2/assets/readme/copy-starter.png b/dist2/assets/readme/copy-starter.png new file mode 100644 index 0000000..14a1001 Binary files /dev/null and b/dist2/assets/readme/copy-starter.png differ diff --git a/dist2/assets/readme/git-clone.png b/dist2/assets/readme/git-clone.png new file mode 100644 index 0000000..289fcb5 Binary files /dev/null and b/dist2/assets/readme/git-clone.png differ diff --git a/dist2/assets/readme/intro.png b/dist2/assets/readme/intro.png new file mode 100644 index 0000000..f998dbe Binary files /dev/null and b/dist2/assets/readme/intro.png differ diff --git a/dist2/assets/readme/local-button.png b/dist2/assets/readme/local-button.png new file mode 100644 index 0000000..cc4a001 Binary files /dev/null and b/dist2/assets/readme/local-button.png differ diff --git a/dist2/assets/readme/new-repo-from-starter.png b/dist2/assets/readme/new-repo-from-starter.png new file mode 100644 index 0000000..02e4b38 Binary files /dev/null and b/dist2/assets/readme/new-repo-from-starter.png differ diff --git a/dist2/assets/readme/pwa-running.png b/dist2/assets/readme/pwa-running.png new file mode 100644 index 0000000..1bd2e02 Binary files /dev/null and b/dist2/assets/readme/pwa-running.png differ diff --git a/dist2/assets/readme/pwa-starter-overview.png b/dist2/assets/readme/pwa-starter-overview.png new file mode 100644 index 0000000..93067fa Binary files /dev/null and b/dist2/assets/readme/pwa-starter-overview.png differ diff --git a/dist2/assets/readme/static-web-app-slash.png b/dist2/assets/readme/static-web-app-slash.png new file mode 100644 index 0000000..9f70f6a Binary files /dev/null and b/dist2/assets/readme/static-web-app-slash.png differ diff --git a/dist2/assets/readme/use-this-template.png b/dist2/assets/readme/use-this-template.png new file mode 100644 index 0000000..296e4bf Binary files /dev/null and b/dist2/assets/readme/use-this-template.png differ diff --git a/dist2/assets/readme/vscode-in-browser.png b/dist2/assets/readme/vscode-in-browser.png new file mode 100644 index 0000000..93e3b57 Binary files /dev/null and b/dist2/assets/readme/vscode-in-browser.png differ diff --git a/dist2/assets/screenshots/screen.png b/dist2/assets/screenshots/screen.png new file mode 100644 index 0000000..330869f Binary files /dev/null and b/dist2/assets/screenshots/screen.png differ diff --git a/dist2/assets/screenshots/widget-screen.png b/dist2/assets/screenshots/widget-screen.png new file mode 100644 index 0000000..be5d827 Binary files /dev/null and b/dist2/assets/screenshots/widget-screen.png differ diff --git a/dist2/code/app-about-BGKiJfUr.js b/dist2/code/app-about-BGKiJfUr.js new file mode 100644 index 0000000..6e59a3a --- /dev/null +++ b/dist2/code/app-about-BGKiJfUr.js @@ -0,0 +1,57 @@ +import{i as l,r as p,x as h,s as m,t as c}from"./index-COc6jZBc.js";const d=l` + @media(min-width: 1000px) { + sl-card { + max-width: 70vw; + } + } +`;var u=Object.defineProperty,y=Object.getOwnPropertyDescriptor,f=(n,o,a,t)=>{for(var e=t>1?void 0:t?y(o,a):o,s=n.length-1,r;s>=0;s--)(r=n[s])&&(e=(t?r(o,a,e):r(e))||e);return t&&e&&u(o,a,e),e};let i=class extends p{render(){return h` + + +
    +

    Frequently Asked Questions

    + + +

    What am I looking at?

    + +

    + This is a personal micro-social media client that can be installed to + your desktop or smartphone home screen. You can sign in via an extension + to display your profile data and notes from my relay. You + can compose a note using a rich text editor I built with Prosemirror. +

    + + + +

    How do I install this on my home screen?

    +

    Look for "Add to Home Screen" in your browser toolbar + to install it to your homescreen.

    + +

    What is Nostr?

    +

    Notes and Other Stuff Transmitted Over Relays is a simple open source + social media protocol that enables anybody to implement social media functionalities + into their websites.

    + +
    +

    Technology Used

    + + +
    +
    + `}};i.styles=[m,d,l` + + `];i=f([c("app-about")],i);export{i as AppAbout}; +//# sourceMappingURL=app-about-BGKiJfUr.js.map diff --git a/dist2/code/app-about-BGKiJfUr.js.map b/dist2/code/app-about-BGKiJfUr.js.map new file mode 100644 index 0000000..22075d1 --- /dev/null +++ b/dist2/code/app-about-BGKiJfUr.js.map @@ -0,0 +1 @@ +{"version":3,"file":"app-about-BGKiJfUr.js","sources":["../../src/pages/app-about/about-styles.ts","../../src/pages/app-about/app-about.ts"],"sourcesContent":["import { css } from 'lit';\n\n// these styles can be imported from any component\n// for an example of how to use this, check /pages/about-about.ts\nexport const styles = css`\n @media(min-width: 1000px) {\n sl-card {\n max-width: 70vw;\n }\n }\n`;","import { LitElement, html, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\n\nimport { styles } from './about-styles';\n\nimport { styles as sharedStyles } from '../../styles/shared-styles'\nimport '@shoelace-style/shoelace/dist/components/card/card.js';\n\n@customElement('app-about')\nexport class AppAbout extends LitElement {\n static styles = [\n sharedStyles,\n styles,\n css`\n\n `\n ]\n\n render() {\n return html`\n \n\n
    \n

    Frequently Asked Questions

    \n\n\n

    What am I looking at?

    \n\n

    \n This is a personal micro-social media client that can be installed to\n your desktop or smartphone home screen. You can sign in via an extension\n to display your profile data and notes from my relay. You\n can compose a note using a rich text editor I built with Prosemirror.\n

    \n\n\n\n

    How do I install this on my home screen?

    \n

    Look for \"Add to Home Screen\" in your browser toolbar\n to install it to your homescreen.

    \n\n

    What is Nostr?

    \n

    Notes and Other Stuff Transmitted Over Relays is a simple open source\n social media protocol that enables anybody to implement social media functionalities\n into their websites.

    \n\n
    \n

    Technology Used

    \n\n \n
    \n
    \n `;\n }\n}\n"],"names":["styles","css","AppAbout","LitElement","html","sharedStyles","__decorateClass","customElement"],"mappings":"oEAIO,MAAMA,EAASC;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA,kMCKT,IAAAC,EAAN,cAAuBC,CAAW,CASvC,QAAS,CACA,OAAAC;AAAAA,iCACsB,EAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAAA,CAgDrC,EA3DaF,EACJ,OAAS,CACdG,EACAL,EACAC;AAAAA;AAAAA,KAGF,EAPWC,EAANI,EAAA,CADNC,EAAc,WAAW,CAAA,EACbL,CAAA"} \ No newline at end of file diff --git a/dist2/code/app-write-DLE2Mxxa.js b/dist2/code/app-write-DLE2Mxxa.js new file mode 100644 index 0000000..a748003 --- /dev/null +++ b/dist2/code/app-write-DLE2Mxxa.js @@ -0,0 +1,51 @@ +import{r as To,x as Eo,s as Do,i as Ao,n as Ji,e as Ro,t as Io}from"./index-COc6jZBc.js";function I(r){this.content=r}I.prototype={constructor:I,find:function(r){for(var e=0;e>1}};I.from=function(r){if(r instanceof I)return r;var e=[];if(r)for(var t in r)e.push(t,r[t]);return new I(e)};function $i(r,e,t){for(let n=0;;n++){if(n==r.childCount||n==e.childCount)return r.childCount==e.childCount?null:t;let i=r.child(n),s=e.child(n);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)t++;return t}if(i.content.size||s.content.size){let o=$i(i.content,s.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function Wi(r,e,t,n){for(let i=r.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:t,b:n};let o=r.child(--i),l=e.child(--s),a=o.nodeSize;if(o==l){t-=a,n-=a;continue}if(!o.sameMarkup(l))return{a:t,b:n};if(o.isText&&o.text!=l.text){let h=0,c=Math.min(o.text.length,l.text.length);for(;he&&n(a,i+l,s||null,o)!==!1&&a.content.size){let c=l+1;a.nodesBetween(Math.max(0,e-c),Math.min(a.content.size,t-c),n,i+c)}l=h}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let h=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&h||l.isTextblock)&&n&&(o?o=!1:s+=n),s+=h},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(n)&&(i[i.length-1]=t.withText(t.text+n.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),n.push(l),i+=l.nodeSize),o=a}return new L(n,i)}cutByIndex(e,t){return e==t?L.empty:e==0&&t==this.content.length?this:new L(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-n.nodeSize;return i[e]=t,new L(i,s)}addToStart(e){return new L([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new L(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,i=0;;n++){let s=this.child(n),o=i+s.nodeSize;if(o>=e)return o==e||t>0?$t(n+1,o):$t(n,i);i=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return L.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return new L(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return L.empty;let t,n=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),n=!0),t&&t.push(s)}}return t||(t=e.slice()),n||t.push(this),t}removeFromSet(e){for(let t=0;tn.type.rank-i.type.rank),t}}C.none=[];let nn=class extends Error{},S=class Ge{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let n=Ki(this.content,e+this.openStart,t);return n&&new Ge(n,this.openStart,this.openEnd)}removeBetween(e,t){return new Ge(qi(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return Ge.empty;let n=t.openStart||0,i=t.openEnd||0;if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Ge(y.fromJSON(e,t.content),n,i)}static maxOpen(e,t=!0){let n=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)n++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new Ge(e,n,i)}};S.empty=new S(y.empty,0,0);function qi(r,e,t){let{index:n,offset:i}=r.findIndex(e),s=r.maybeChild(n),{index:o,offset:l}=r.findIndex(t);if(i==e||s.isText){if(l!=t&&!r.child(o).isText)throw new RangeError("Removing non-flat range");return r.cut(0,e).append(r.cut(t))}if(n!=o)throw new RangeError("Removing non-flat range");return r.replaceChild(n,s.copy(qi(s.content,e-i-1,t-i-1)))}function Ki(r,e,t,n){let{index:i,offset:s}=r.findIndex(e),o=r.maybeChild(i);if(s==e||o.isText)return r.cut(0,e).append(t).append(r.cut(e));let l=Ki(o.content,e-s-1,t);return l&&r.replaceChild(i,o.copy(l))}function zo(r,e,t){if(t.openStart>r.depth)throw new nn("Inserted content deeper than insertion position");if(r.depth-t.openStart!=e.depth-t.openEnd)throw new nn("Inconsistent open depths");return Hi(r,e,t,0)}function Hi(r,e,t,n){let i=r.index(n),s=r.node(n);if(i==e.index(n)&&n=0&&r.isText&&r.sameMarkup(e[t])?e[t]=r.withText(e[t].text+r.text):e.push(r)}function kt(r,e,t,n){let i=(e||r).node(t),s=0,o=e?e.index(t):i.childCount;r&&(s=r.index(t),r.depth>t?s++:r.textOffset&&(Pe(r.nodeAfter,n),s++));for(let l=s;li&&Kn(r,e,i+1),o=n.depth>i&&Kn(t,n,i+1),l=[];return kt(null,r,i,l),s&&o&&e.index(i)==t.index(i)?(Ui(s,o),Pe(Be(s,Gi(r,e,t,n,i+1)),l)):(s&&Pe(Be(s,rn(r,e,i+1)),l),kt(e,t,i,l),o&&Pe(Be(o,rn(t,n,i+1)),l)),kt(n,null,i,l),new y(l)}function rn(r,e,t){let n=[];if(kt(null,r,t,n),r.depth>t){let i=Kn(r,e,t+1);Pe(Be(i,rn(r,e,t+1)),n)}return kt(e,null,t,n),new y(n)}function vo(r,e){let t=e.depth-r.openStart,i=e.node(t).copy(r.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(y.from(i));return{start:i.resolveNoCache(r.openStart+t),end:i.resolveNoCache(i.content.size-r.openEnd-t)}}class Mt{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],i=e.child(t);return n?e.child(t).cut(n):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new Fo(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let n=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),h=s-a;if(n.push(o,l,i+a),!h||(o=o.child(l),o.isText))break;s=h-1,i+=a+1}return new Mt(t,n,s)}static resolveCached(e,t){let n=Rr.get(e);if(n)for(let s=0;se&&this.nodesBetween(e,t,s=>(n.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Yi(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,n=y.empty,i=0,s=n.childCount){let o=this.contentMatchAt(e).matchFragment(n,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let n;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,n)}let i=y.fromJSON(e,t.content),s=e.nodeType(t.type).create(t.attrs,i,n);return s.type.checkAttrs(s.attrs),s}};Fe.prototype.text=void 0;class sn extends Fe{constructor(e,t,n,i){if(super(e,t,null,i),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Yi(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new sn(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new sn(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Yi(r,e){for(let t=r.length-1;t>=0;t--)e=r[t].type.name+"("+e+")";return e}class $e{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let n=new Lo(e,t);if(n.next==null)return $e.empty;let i=ji(n);n.next&&n.err("Unexpected trailing text");let s=Uo(Ho(i));return Go(s,n),s}matchType(e){for(let t=0;th.createAndFill()));for(let h=0;h=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let i=0;i{let s=i+(n.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(n.next[o].next);return s}).join(` +`)}}$e.empty=new $e(!0);class Lo{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function ji(r){let e=[];do e.push(Jo(r));while(r.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Jo(r){let e=[];do e.push($o(r));while(r.next&&r.next!=")"&&r.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function $o(r){let e=Ko(r);for(;;)if(r.eat("+"))e={type:"plus",expr:e};else if(r.eat("*"))e={type:"star",expr:e};else if(r.eat("?"))e={type:"opt",expr:e};else if(r.eat("{"))e=Wo(r,e);else break;return e}function Ir(r){/\D/.test(r.next)&&r.err("Expected number, got '"+r.next+"'");let e=Number(r.next);return r.pos++,e}function Wo(r,e){let t=Ir(r),n=t;return r.eat(",")&&(r.next!="}"?n=Ir(r):n=-1),r.eat("}")||r.err("Unclosed braced range"),{type:"range",min:t,max:n,expr:e}}function qo(r,e){let t=r.nodeTypes,n=t[e];if(n)return[n];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&r.err("No node type or group '"+e+"' found"),i}function Ko(r){if(r.eat("(")){let e=ji(r);return r.eat(")")||r.err("Missing closing paren"),e}else if(/\W/.test(r.next))r.err("Unexpected token '"+r.next+"'");else{let e=qo(r,r.next).map(t=>(r.inline==null?r.inline=t.isInline:r.inline!=t.isInline&&r.err("Mixing inline and block content"),{type:"name",value:t}));return r.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Ho(r){let e=[[]];return i(s(r,0),t()),e;function t(){return e.push([])-1}function n(o,l,a){let h={term:a,to:l};return e[o].push(h),h}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,h)=>a.concat(s(h,l)),[]);if(o.type=="seq")for(let a=0;;a++){let h=s(o.exprs[a],l);if(a==o.exprs.length-1)return h;i(h,l=t())}else if(o.type=="star"){let a=t();return n(l,a),i(s(o.expr,a),a),[n(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[n(a)]}else{if(o.type=="opt")return[n(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let h=0;h{r[o].forEach(({term:l,to:a})=>{if(!l)return;let h;for(let c=0;c{h||i.push([l,h=[]]),h.indexOf(c)==-1&&h.push(c)})})});let s=e[n.join(",")]=new $e(n.indexOf(r.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:Qi(this.attrs,e)}create(e=null,t,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Fe(this,this.computeAttrs(e),y.from(t),C.setFrom(n))}createChecked(e=null,t,n){return t=y.from(t),this.checkContent(t),new Fe(this,this.computeAttrs(e),t,C.setFrom(n))}createAndFill(e=null,t,n){if(e=this.computeAttrs(e),t=y.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(y.empty,!0);return s?new Fe(this,e,t.append(s),C.setFrom(n)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let n=0;n-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tn[s]=new ts(s,t,o));let i=t.spec.topNode||"doc";if(!n[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let s in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function Yo(r,e,t){let n=t.split("|");return i=>{let s=i===null?"null":typeof i;if(n.indexOf(s)<0)throw new RangeError(`Expected value of type ${n} for attribute ${e} on type ${r}, got ${s}`)}}class jo{constructor(e,t,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?Yo(e,t,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class mn{constructor(e,t,n,i){this.name=e,this.rank=t,this.schema=n,this.spec=i,this.attrs=es(e,i.attrs),this.excluded=null;let s=Zi(this.attrs);this.instance=s?new C(this,s):null}create(e=null){return!e&&this.instance?this.instance:new C(this,Qi(this.attrs,e))}static compile(e,t){let n=Object.create(null),i=0;return e.forEach((s,o)=>n[s]=new mn(s,i++,t,o)),n}removeFromSet(e){for(var t=0;t-1}}class Xo{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=I.from(e.nodes),t.marks=I.from(e.marks||{}),this.nodes=vr.compile(this.spec.nodes,this),this.marks=mn.compile(this.spec.marks,this);let n=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=n[o]||(n[o]=$e.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Pr(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Pr(this,o.split(" "))}this.nodeFromJSON=this.nodeFromJSON.bind(this),this.markFromJSON=this.markFromJSON.bind(this),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,n,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof vr){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,n,i)}text(e,t){let n=this.nodes.text;return new sn(n,n.defaultAttrs,e,C.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeFromJSON(e){return Fe.fromJSON(this,e)}markFromJSON(e){return C.fromJSON(this,e)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Pr(r,e){let t=[];for(let n=0;n-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[n]+"'")}return t}function Zo(r){return r.tag!=null}function Qo(r){return r.style!=null}class Tt{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let n=this.matchedStyles=[];t.forEach(i=>{if(Zo(i))this.tags.push(i);else if(Qo(i)){let s=/[^=]*/.exec(i.style)[0];n.indexOf(s)<0&&n.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let n=new Fr(this,t,!1);return n.addAll(e,C.none,t.from,t.to),n.finish()}parseSlice(e,t={}){let n=new Fr(this,t,!0);return n.addAll(e,C.none,t.from,t.to),S.maxOpen(n.finish())}matchTag(e,t,n){for(let i=n?this.tags.indexOf(n)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function n(i){let s=i.priority==null?50:i.priority,o=0;for(;o{n(o=Vr(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{n(o=Vr(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Tt(e,Tt.schemaRules(e)))}}const ns={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},_o={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},rs={ol:!0,ul:!0},Et=1,Un=2,xt=4;function Br(r,e,t){return e!=null?(e?Et:0)|(e==="full"?Un:0):r&&r.whitespace=="pre"?Et|Un:t&~xt}class Wt{constructor(e,t,n,i,s,o){this.type=e,this.attrs=t,this.marks=n,this.solid=i,this.options=o,this.content=[],this.activeMarks=C.none,this.match=s||(o&xt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(y.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let n=this.type.contentMatch,i;return(i=n.findWrapping(e.type))?(this.match=n,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Et)){let n=this.content[this.content.length-1],i;if(n&&n.isText&&(i=/[ \t\r\n\u000c]+$/.exec(n.text))){let s=n;n.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=y.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(y.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!ns.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Fr{constructor(e,t,n){this.parser=e,this.options=t,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Br(null,t.preserveWhitespace,0)|(n?xt:0);i?s=new Wt(i.type,i.attrs,C.none,!0,t.topMatch||i.type.contentMatch,o):n?s=new Wt(null,null,C.none,!0,null,o):s=new Wt(e.schema.topNodeType,null,C.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let n=e.nodeValue,i=this.top,s=i.options&Un?"full":this.localPreserveWS||(i.options&Et)>0;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(s)s!=="full"?n=n.replace(/\r?\n|\r/g," "):n=n.replace(/\r\n?/g,` +`);else if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let o=i.content[i.content.length-1],l=e.previousSibling;(!o||l&&l.nodeName=="BR"||o.isText&&/[ \t\r\n\u000c]$/.test(o.text))&&(n=n.slice(1))}n&&this.insertNode(this.parser.schema.text(n),t),this.findInText(e)}else this.findInside(e)}addElement(e,t,n){let i=this.localPreserveWS,s=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let o=e.nodeName.toLowerCase(),l;rs.hasOwnProperty(o)&&this.parser.normalizeLists&&el(e);let a=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(l=this.parser.matchTag(e,this,n));e:if(a?a.ignore:_o.hasOwnProperty(o))this.findInside(e),this.ignoreFallback(e,t);else if(!a||a.skip||a.closeParent){a&&a.closeParent?this.open=Math.max(0,this.open-1):a&&a.skip.nodeType&&(e=a.skip);let h,c=this.needsBlock;if(ns.hasOwnProperty(o))s.content.length&&s.content[0].isInline&&this.open&&(this.open--,s=this.top),h=!0,s.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break e}let f=a&&a.skip?t:this.readStyles(e,t);f&&this.addAll(e,f),h&&this.sync(s),this.needsBlock=c}else{let h=this.readStyles(e,t);h&&this.addElementByRule(e,a,h,a.consuming===!1?l:void 0)}this.localPreserveWS=i}leafFallback(e,t){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(` +`),t)}ignoreFallback(e,t){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),t)}readStyles(e,t){let n=e.style;if(n&&n.length)for(let i=0;i!a.clearMark(h)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,n,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),n)||this.leafFallback(e,n);else{let a=this.enter(o,t.attrs||null,n,t.preserveWhitespace);a&&(s=!0,n=a)}else{let a=this.parser.schema.marks[t.mark];n=n.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,n,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,n));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,n),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,n,i){let s=n||0;for(let o=n?e.childNodes[n]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t){let n,i;for(let s=this.open;s>=0;s--){let o=this.nodes[s],l=o.findWrapping(e);if(l&&(!n||n.length>l.length)&&(n=l,i=o,!l.length)||o.solid)break}if(!n)return null;this.sync(i);for(let s=0;s(o.type?o.type.allowsMarkType(h.type):Lr(h.type,e))?(a=h.addToSet(a),!1):!0),this.nodes.push(new Wt(e,t,a,i,null,l)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=Et)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let i=n.length-1;i>=0;i--)e+=n[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),n=this.options.context,i=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),s=-(n?n.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let h=t[l];if(h==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let c=a>0||a==0&&i?this.nodes[a].type:n&&a>=s?n.node(a-s).type:null;if(!c||c.name!=h&&!c.isInGroup(h))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let t in this.parser.schema.nodes){let n=this.parser.schema.nodes[t];if(n.isTextblock&&n.defaultAttrs)return n}}}function el(r){for(let e=r.firstChild,t=null;e;e=e.nextSibling){let n=e.nodeType==1?e.nodeName.toLowerCase():null;n&&rs.hasOwnProperty(n)&&t?(t.appendChild(e),e=t):n=="li"?t=e:n&&(t=null)}}function tl(r,e){return(r.matches||r.msMatchesSelector||r.webkitMatchesSelector||r.mozMatchesSelector).call(r,e)}function Vr(r){let e={};for(let t in r)e[t]=r[t];return e}function Lr(r,e){let t=e.schema.nodes;for(let n in t){let i=t[n];if(!i.allowsMarkType(r))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(n),n=s.dom)}return n}serializeMark(e,t,n={}){let i=this.marks[e.type.name];return i&&Gt(Cn(n),i(e,t),null,e.attrs)}static renderSpec(e,t,n=null,i){return Gt(e,t,n,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new at(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=Jr(e.nodes);return t.text||(t.text=n=>n.text),t}static marksFromSchema(e){return Jr(e.marks)}}function Jr(r){let e={};for(let t in r){let n=r[t].spec.toDOM;n&&(e[t]=n)}return e}function Cn(r){return r.document||window.document}const $r=new WeakMap;function nl(r){let e=$r.get(r);return e===void 0&&$r.set(r,e=rl(r)),e}function rl(r){let e=null;function t(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")e||(e=[]),e.push(n);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?r.createElementNS(t,i):r.createElement(i),h=e[1],c=1;if(h&&typeof h=="object"&&h.nodeType==null&&!Array.isArray(h)){c=2;for(let f in h)if(h[f]!=null){let d=f.indexOf(" ");d>0?a.setAttributeNS(f.slice(0,d),f.slice(d+1),h[f]):a.setAttribute(f,h[f])}}for(let f=c;fc)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else{let{dom:p,contentDOM:u}=Gt(r,d,t,n);if(a.appendChild(p),u){if(l)throw new RangeError("Multiple content holes");l=u}}}return{dom:a,contentDOM:l}}const is=65535,ss=Math.pow(2,16);function il(r,e){return r+e*ss}function Wr(r){return r&is}function sl(r){return(r-(r&is))/ss}const ls=1,as=2,Yt=4,hs=8;let Gn=class{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&hs)>0}get deletedBefore(){return(this.delInfo&(ls|Yt))>0}get deletedAfter(){return(this.delInfo&(as|Yt))>0}get deletedAcross(){return(this.delInfo&Yt)>0}},We=class Ye{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&Ye.empty)return Ye.empty}recover(e){let t=0,n=Wr(e);if(!this.inverted)for(let i=0;ie)break;let h=this.ranges[l+s],c=this.ranges[l+o],f=a+h;if(e<=f){let d=h?e==a?-1:e==f?1:t:t,p=a+i+(d<0?0:c);if(n)return p;let u=e==(t<0?a:f)?null:il(l/3,e-a),m=e==a?as:e==f?ls:Yt;return(t<0?e!=a:e!=f)&&(m|=hs),new Gn(p,m,u)}i+=c-h}return n?e+i:new Gn(e+i,0,null)}touches(e,t){let n=0,i=Wr(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let h=this.ranges[l+s],c=a+h;if(e<=c&&l==i*3)return!0;n+=this.ranges[l+o]-h}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e.maps[t].invert(),i!=null&&i>t?n-i-1:void 0)}}invert(){let e=new _e;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let n=this.from;ns&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return J.fromReplace(e,this.from,this.to,s)}invert(){return new Pt(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new ft(t.pos,n.pos,this.mark)}merge(e){return e instanceof ft&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ft(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new ft(t.from,t.to,e.markFromJSON(t.mark))}};F.jsonID("addMark",fr);let Pt=class ut extends F{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new S(cr(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return J.fromReplace(e,this.from,this.to,n)}invert(){return new fr(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new ut(t.pos,n.pos,this.mark)}merge(e){return e instanceof ut&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ut(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ut(t.from,t.to,e.markFromJSON(t.mark))}};F.jsonID("removeMark",Pt);let ur=class dt extends F{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return J.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return J.fromReplace(e,this.pos,this.pos+1,new S(y.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let n=this.mark.addToSet(t.marks);if(n.length==t.marks.length){for(let i=0;in.pos?null:new jt(t.pos,n.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new jt(t.from,t.to,t.gapFrom,t.gapTo,S.fromJSON(e,t.slice),t.insert,!!t.structure)}};F.jsonID("replaceAround",pe);function jn(r,e,t){let n=r.resolve(e),i=t-e,s=n.depth;for(;i>0&&s>0&&n.indexAfter(s)==n.node(s).childCount;)s--,i--;if(i>0){let o=n.node(s).maybeChild(n.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function ol(r,e,t,n){let i=[],s=[],o,l;r.doc.nodesBetween(e,t,(a,h,c)=>{if(!a.isInline)return;let f=a.marks;if(!n.isInSet(f)&&c.type.allowsMarkType(n.type)){let d=Math.max(h,e),p=Math.min(h+a.nodeSize,t),u=n.addToSet(f);for(let m=0;mr.step(a)),s.forEach(a=>r.step(a))}function ll(r,e,t,n){let i=[],s=0;r.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(n instanceof mn){let h=o.marks,c;for(;c=n.isInSet(h);)(a||(a=[])).push(c),h=c.removeFromSet(h)}else n?n.isInSet(o.marks)&&(a=[n]):a=o.marks;if(a&&a.length){let h=Math.min(l+o.nodeSize,t);for(let c=0;cr.step(new Pt(o.from,o.to,o.style)))}function pr(r,e,t,n=t.contentMatch,i=!0){let s=r.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)r.step(o[a])}function al(r,e,t){return(e==0||r.canReplace(e,r.childCount))&&(t==r.childCount||r.canReplace(0,t))}function mr(r){let t=r.parent.content.cutByIndex(r.startIndex,r.endIndex);for(let n=r.depth;;--n){let i=r.$from.node(n),s=r.$from.index(n),o=r.$to.indexAfter(n);if(nt;u--)m||n.index(u)>0?(m=!0,c=y.from(n.node(u).copy(c)),f++):a--;let d=y.empty,p=0;for(let u=s,m=!1;u>t;u--)m||i.after(u+1)=0;o--){if(n.size){let l=t[o].type.contentMatch.matchFragment(n);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=y.from(t[o].type.create(t[o].attrs,n))}let i=e.start,s=e.end;r.step(new pe(i,s,i,s,new S(n,0,0),t.length,!0))}function fl(r,e,t,n,i){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=r.steps.length;r.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(n,a)&&ul(r.doc,r.mapping.slice(s).map(l),n)){let h=null;if(n.schema.linebreakReplacement){let p=n.whitespace=="pre",u=!!n.contentMatch.matchType(n.schema.linebreakReplacement);p&&!u?h=!1:!p&&u&&(h=!0)}h===!1&&fs(r,o,l,s),pr(r,r.mapping.slice(s).map(l,1),n,void 0,h===null);let c=r.mapping.slice(s),f=c.map(l,1),d=c.map(l+o.nodeSize,1);return r.step(new pe(f,d,f+1,d-1,new S(y.from(n.create(a,null,o.marks)),0,0),1,!0)),h===!0&&cs(r,o,l,s),!1}})}function cs(r,e,t,n){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=r.mapping.slice(n).map(t+1+s+o.index);r.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function fs(r,e,t,n){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=r.mapping.slice(n).map(t+1+s);r.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function ul(r,e,t){let n=r.resolve(e),i=n.index();return n.parent.canReplaceWith(i,i+1,t)}function dl(r,e,t,n,i){let s=r.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(n,null,i||s.marks);if(s.isLeaf)return r.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);r.step(new pe(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new S(y.from(o),0,0),1,!0))}function Xt(r,e,t=1,n){let i=r.resolve(e),s=i.depth-t,o=n&&n[n.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let h=i.depth-1,c=t-2;h>s;h--,c--){let f=i.node(h),d=i.index(h);if(f.type.spec.isolating)return!1;let p=f.content.cutByIndex(d,f.childCount),u=n&&n[c+1];u&&(p=p.replaceChild(0,u.type.create(u.attrs)));let m=n&&n[c]||f;if(!f.canReplace(d+1,f.childCount)||!m.type.validContent(p))return!1}let l=i.indexAfter(s),a=n&&n[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function pl(r,e,t=1,n){let i=r.doc.resolve(e),s=y.empty,o=y.empty;for(let l=i.depth,a=i.depth-t,h=t-1;l>a;l--,h--){s=y.from(i.node(l).copy(s));let c=n&&n[h];o=y.from(c?c.type.create(c.attrs,o):i.node(l).copy(o))}r.step(new de(e,e,new S(s.append(o),t,t),!0))}function us(r,e){let t=r.resolve(e),n=t.index();return gl(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(n,n+1)}function ml(r,e){e.content.size||r.type.compatibleContent(e.type);let t=r.contentMatchAt(r.childCount),{linebreakReplacement:n}=r.type.schema;for(let i=0;i=0;i--){let s=n.index(i);if(n.node(i).canReplaceWith(s,s,t))return n.before(i+1);if(s>0)return null}if(n.parentOffset==n.parent.content.size)for(let i=n.depth-1;i>=0;i--){let s=n.indexAfter(i);if(n.node(i).canReplaceWith(s,s,t))return n.after(i+1);if(s=0;o--){let l=o==n.depth?0:n.pos<=(n.start(o+1)+n.end(o+1))/2?-1:1,a=n.index(o)+(l>0?1:0),h=n.node(o),c=!1;if(s==1)c=h.canReplace(a,a,i);else{let f=h.contentMatchAt(a).findWrapping(i.firstChild.type);c=f&&h.canReplaceWith(a,a,f[0])}if(c)return l==0?n.pos:l<0?n.before(o+1):n.after(o+1)}return null}function gr(r,e,t=e,n=S.empty){if(e==t&&!n.size)return null;let i=r.resolve(e),s=r.resolve(t);return ds(i,s,n)?new de(e,t,n):new xl(i,s,n).fit()}function ds(r,e,t){return!t.openStart&&!t.openEnd&&r.start()==e.start()&&r.parent.canReplace(r.index(),e.index(),t.content)}class xl{constructor(e,t,n){this.$from=e,this.$to=t,this.unplaced=n,this.frontier=[],this.placed=y.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=y.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let h=this.findFittable();h?this.placeNodes(h):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,n=this.$from,i=this.close(e<0?this.$to:n.doc.resolve(e));if(!i)return null;let s=this.placed,o=n.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new S(s,o,l);return e>-1?new pe(n.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||n.pos!=this.$to.pos?new de(n.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,n=0,i=this.unplaced.openEnd;n1&&(i=0),s.type.spec.isolating&&i<=n){e=n;break}t=s.content}for(let t=1;t<=2;t++)for(let n=t==1?e:this.unplaced.openStart;n>=0;n--){let i,s=null;n?(s=On(this.unplaced.content,n-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:h}=this.frontier[l],c,f=null;if(t==1&&(o?h.matchType(o.type)||(f=h.fillBefore(y.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:n,frontierDepth:l,parent:s,inject:f};if(t==2&&o&&(c=h.findWrapping(o.type)))return{sliceDepth:n,frontierDepth:l,parent:s,wrap:c};if(s&&h.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:n}=this.unplaced,i=On(e,t);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new S(e,t+1,Math.max(n,i.size+t>=e.size-n?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:n}=this.unplaced,i=On(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new S(pt(e,t-1,1),t-1,s?t-1:n)}else this.unplaced=new S(pt(e,t,1),t,n)}placeNodes({sliceDepth:e,frontierDepth:t,parent:n,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(f=g,c.push(ps(m.mark(d.allowedMarks(m.marks)),h==1?a:0,h==l.childCount?p:-1)))}let u=h==l.childCount;u||(p=-1),this.placed=mt(this.placed,t,y.from(c)),this.frontier[t].match=f,u&&p<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--n);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:n,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:h}=this.frontier[l],c=Mn(e,l,h,a,!0);if(!c||c.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=mt(this.placed,t.depth,t.fit)),e=t.move;for(let n=t.depth+1;n<=e.depth;n++){let i=e.node(n),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(n));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,n){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=mt(this.placed,this.depth,y.from(e.create(t,n))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(y.empty,!0);t.childCount&&(this.placed=mt(this.placed,this.frontier.length,t))}}function pt(r,e,t){return e==0?r.cutByIndex(t,r.childCount):r.replaceChild(0,r.firstChild.copy(pt(r.firstChild.content,e-1,t)))}function mt(r,e,t){return e==0?r.append(t):r.replaceChild(r.childCount-1,r.lastChild.copy(mt(r.lastChild.content,e-1,t)))}function On(r,e){for(let t=0;t1&&(n=n.replaceChild(0,ps(n.firstChild,e-1,n.childCount==1?t-1:0))),e>0&&(n=r.type.contentMatch.fillBefore(n).append(n),t<=0&&(n=n.append(r.type.contentMatch.matchFragment(n).fillBefore(y.empty,!0)))),r.copy(n)}function Mn(r,e,t,n,i){let s=r.node(e),o=i?r.indexAfter(e):r.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=n.fillBefore(s.content,!0,o);return l&&!bl(t,s.content,o)?l:null}function bl(r,e,t){for(let n=t;n0;d--,p--){let u=i.node(d).type.spec;if(u.defining||u.definingAsContext||u.isolating)break;o.indexOf(d)>-1?l=d:i.before(d)==p&&o.splice(1,0,-d)}let a=o.indexOf(l),h=[],c=n.openStart;for(let d=n.content,p=0;;p++){let u=d.firstChild;if(h.push(u),p==n.openStart)break;d=u.content}for(let d=c-1;d>=0;d--){let p=h[d],u=wl(p.type);if(u&&!p.sameMarkup(i.node(Math.abs(l)-1)))c=d;else if(u||!p.type.isTextblock)break}for(let d=n.openStart;d>=0;d--){let p=(d+c+1)%(n.openStart+1),u=h[p];if(u)for(let m=0;m=0&&(r.replace(e,t,n),!(r.steps.length>f));d--){let p=o[d];p<0||(e=i.before(p),t=s.after(p))}}function ms(r,e,t,n,i){if(en){let s=i.contentMatchAt(0),o=s.fillBefore(r).append(r);r=o.append(s.matchFragment(o).fillBefore(y.empty,!0))}return r}function Nl(r,e,t,n){if(!n.isInline&&e==t&&r.doc.resolve(e).parent.content.size){let i=Sl(r.doc,e,n.type);i!=null&&(e=t=i)}r.replaceRange(e,t,new S(y.from(n),0,0))}function Ol(r,e,t){let n=r.doc.resolve(e),i=r.doc.resolve(t),s=gs(n,i);for(let o=0;o0&&(a||n.node(l-1).canReplace(n.index(l-1),i.indexAfter(l-1))))return r.delete(n.before(l),i.after(l))}for(let o=1;o<=n.depth&&o<=i.depth;o++)if(e-n.start(o)==n.depth-o&&t>n.end(o)&&i.end(o)-t!=i.depth-o&&n.start(o-1)==i.start(o-1)&&n.node(o-1).canReplace(n.index(o-1),i.index(o-1)))return r.delete(n.before(o),t);r.delete(e,t)}function gs(r,e){let t=[],n=Math.min(r.depth,e.depth);for(let i=n;i>=0;i--){let s=r.start(i);if(se.pos+(e.depth-i)||r.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==r.depth&&i==e.depth&&r.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}let ys=class Zt extends F{constructor(e,t,n){super(),this.pos=e,this.attr=t,this.value=n}apply(e){let t=e.nodeAt(this.pos);if(!t)return J.fail("No node at attribute step's position");let n=Object.create(null);for(let s in t.attrs)n[s]=t.attrs[s];n[this.attr]=this.value;let i=t.type.create(n,null,t.marks);return J.fromReplace(e,this.pos,this.pos+1,new S(y.from(i),0,t.isLeaf?0:1))}getMap(){return We.empty}invert(e){return new Zt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Zt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Zt(t.pos,t.attr,t.value)}};F.jsonID("attr",ys);let Ss=class Xn extends F{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let n=e.type.create(t,e.content,e.marks);return J.ok(n)}getMap(){return We.empty}invert(e){return new Xn(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Xn(t.attr,t.value)}};F.jsonID("docAttr",Ss);let rt=class extends Error{};rt=function r(e){let t=Error.call(this,e);return t.__proto__=r.prototype,t};rt.prototype=Object.create(Error.prototype);rt.prototype.constructor=rt;rt.prototype.name="TransformError";class Ml{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new _e}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new rt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,n=S.empty){let i=gr(this.doc,e,t,n);return i&&this.step(i),this}replaceWith(e,t,n){return this.replace(e,t,new S(y.from(n),0,0))}delete(e,t){return this.replace(e,t,S.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,n){return Cl(this,e,t,n),this}replaceRangeWith(e,t,n){return Nl(this,e,t,n),this}deleteRange(e,t){return Ol(this,e,t),this}lift(e,t){return hl(this,e,t),this}join(e,t=1){return yl(this,e,t),this}wrap(e,t){return cl(this,e,t),this}setBlockType(e,t=e,n,i=null){return fl(this,e,t,n,i),this}setNodeMarkup(e,t,n=null,i){return dl(this,e,t,n,i),this}setNodeAttribute(e,t,n){return this.step(new ys(e,t,n)),this}setDocAttribute(e,t){return this.step(new Ss(e,t)),this}addNodeMark(e,t){return this.step(new ur(e,t)),this}removeNodeMark(e,t){if(!(t instanceof C)){let n=this.doc.nodeAt(e);if(!n)throw new RangeError("No node at position "+e);if(t=t.isInSet(n.marks),!t)return this}return this.step(new dr(e,t)),this}split(e,t=1,n){return pl(this,e,t,n),this}addMark(e,t,n){return ol(this,e,t,n),this}removeMark(e,t,n){return ll(this,e,t,n),this}clearIncompatible(e,t,n){return pr(this,e,t,n),this}}const Tn=Object.create(null);let w=class{constructor(e,t,n){this.$anchor=e,this.$head=t,this.ranges=n||[new Tl(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?je(e.node(0),e.node(s),e.before(s+1),e.index(s),t,n):je(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,n);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new ce(e.node(0))}static atStart(e){return je(e,e,0,0,1)||new ce(e)}static atEnd(e){return je(e,e,e.content.size,e.childCount,-1)||new ce(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=Tn[t.type];if(!n)throw new RangeError(`No selection type ${t.type} defined`);return n.fromJSON(e,t)}static jsonID(e,t){if(e in Tn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Tn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return M.between(this.$anchor,this.$head).getBookmark()}};w.prototype.visible=!0;let Tl=class{constructor(e,t){this.$from=e,this.$to=t}},qr=!1;function Kr(r){!qr&&!r.parent.inlineContent&&(qr=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+r.parent.type.name+")"))}let M=class gt extends w{constructor(e,t=e){Kr(e),Kr(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let n=e.resolve(t.map(this.head));if(!n.parent.inlineContent)return w.near(n);let i=e.resolve(t.map(this.anchor));return new gt(i.parent.inlineContent?i:n,n)}replace(e,t=S.empty){if(super.replace(e,t),t==S.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof gt&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new ks(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new gt(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,n=t){let i=e.resolve(t);return new this(i,n==t?i:e.resolve(n))}static between(e,t,n){let i=e.pos-t.pos;if((!n||i)&&(n=i>=0?1:-1),!t.parent.inlineContent){let s=w.findFrom(t,n,!0)||w.findFrom(t,-n,!0);if(s)t=s.$head;else return w.near(t,n)}return e.parent.inlineContent||(i==0?e=t:(e=(w.findFrom(e,-n,!0)||w.findFrom(e,n,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&x.isSelectable(l))return x.create(r,t-(i<0?l.nodeSize:0))}else{let a=je(r,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Hr(r,e,t){let n=r.steps.length-1;if(n{o==null&&(o=c)}),r.setSelection(w.near(r.doc.resolve(o),t))}const Ur=1,qt=2,Gr=4;class Al extends Ml{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=qt,this}ensureMarks(e){return C.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&qt)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~qt,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let n=this.selection;return t&&(e=e.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||C.none))),n.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,n){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(n==null&&(n=t),n=n??t,!e)return this.deleteRange(t,n);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=n==t?o.marks():o.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(t,n,i.text(e,s)),this.selection.empty||this.setSelection(w.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Gr,this}get scrolledIntoView(){return(this.updated&Gr)>0}}function Yr(r,e){return!e||!r?r:r.bind(e)}let St=class{constructor(e,t,n){this.name=e,this.init=Yr(t.init,n),this.apply=Yr(t.apply,n)}};const Rl=[new St("doc",{init(r){return r.doc||r.schema.topNodeType.createAndFill()},apply(r){return r.doc}}),new St("selection",{init(r,e){return r.selection||w.atStart(e.doc)},apply(r){return r.selection}}),new St("storedMarks",{init(r){return r.storedMarks||null},apply(r,e,t,n){return n.selection.$cursor?r.storedMarks:null}}),new St("scrollToSelection",{init(){return 0},apply(r,e){return r.scrolledIntoView?e+1:e}})];class En{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Rl.slice(),t&&t.forEach(n=>{if(this.pluginsByKey[n.key])throw new RangeError("Adding different instances of a keyed plugin ("+n.key+")");this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state&&this.fields.push(new St(n.key,n.spec.state,n))})}}class Qe{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let n=0;nn.toJSON())),e&&typeof e=="object")for(let n in e){if(n=="doc"||n=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[n],s=i.spec.state;s&&s.toJSON&&(t[n]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,n){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new En(e.schema,e.plugins),s=new Qe(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Fe.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=w.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(n)for(let l in n){let a=n[l],h=a.spec.state;if(a.key==o.name&&h&&h.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=h.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function ws(r,e,t){for(let n in r){let i=r[n];i instanceof Function?i=i.bind(e):n=="handleDOMEvents"&&(i=ws(i,e,{})),t[n]=i}return t}let yr=class{constructor(e){this.spec=e,this.props={},e.props&&ws(e.props,this,this.props),this.key=e.key?e.key.key:Cs("plugin")}getState(e){return e[this.key]}};const Dn=Object.create(null);function Cs(r){return r in Dn?r+"$"+ ++Dn[r]:(Dn[r]=0,r+"$")}class Sr{constructor(e="key"){this.key=Cs(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const z=function(r){for(var e=0;;e++)if(r=r.previousSibling,!r)return e},Dt=function(r){let e=r.assignedSlot||r.parentNode;return e&&e.nodeType==11?e.host:e};let Zn=null;const oe=function(r,e,t){let n=Zn||(Zn=document.createRange());return n.setEnd(r,t??r.nodeValue.length),n.setStart(r,e||0),n},Il=function(){Zn=null},qe=function(r,e,t,n){return t&&(jr(r,e,t,n,-1)||jr(r,e,t,n,1))},zl=/^(img|br|input|textarea|hr)$/i;function jr(r,e,t,n,i){for(;;){if(r==t&&e==n)return!0;if(e==(i<0?0:j(r))){let s=r.parentNode;if(!s||s.nodeType!=1||Bt(r)||zl.test(r.nodeName)||r.contentEditable=="false")return!1;e=z(r)+(i<0?0:1),r=s}else if(r.nodeType==1){if(r=r.childNodes[e+(i<0?-1:0)],r.contentEditable=="false")return!1;e=i<0?j(r):0}else return!1}}function j(r){return r.nodeType==3?r.nodeValue.length:r.childNodes.length}function vl(r,e){for(;;){if(r.nodeType==3&&e)return r;if(r.nodeType==1&&e>0){if(r.contentEditable=="false")return null;r=r.childNodes[e-1],e=j(r)}else if(r.parentNode&&!Bt(r))e=z(r),r=r.parentNode;else return null}}function Pl(r,e){for(;;){if(r.nodeType==3&&e2),Y=it||(re?/Mac/.test(re.platform):!1),Ll=re?/Win/.test(re.platform):!1,he=/Android \d/.test(Me),Ft=!!Xr&&"webkitFontSmoothing"in Xr.documentElement.style,Jl=Ft?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function $l(r){let e=r.defaultView&&r.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:r.documentElement.clientWidth,top:0,bottom:r.documentElement.clientHeight}}function se(r,e){return typeof r=="number"?r:r[e]}function Wl(r){let e=r.getBoundingClientRect(),t=e.width/r.offsetWidth||1,n=e.height/r.offsetHeight||1;return{left:e.left,right:e.left+r.clientWidth*t,top:e.top,bottom:e.top+r.clientHeight*n}}function Zr(r,e,t){let n=r.someProp("scrollThreshold")||0,i=r.someProp("scrollMargin")||5,s=r.dom.ownerDocument;for(let o=t||r.dom;o;o=Dt(o)){if(o.nodeType!=1)continue;let l=o,a=l==s.body,h=a?$l(s):Wl(l),c=0,f=0;if(e.toph.bottom-se(n,"bottom")&&(f=e.bottom-e.top>h.bottom-h.top?e.top+se(i,"top")-h.top:e.bottom-h.bottom+se(i,"bottom")),e.lefth.right-se(n,"right")&&(c=e.right-h.right+se(i,"right")),c||f)if(a)s.defaultView.scrollBy(c,f);else{let d=l.scrollLeft,p=l.scrollTop;f&&(l.scrollTop+=f),c&&(l.scrollLeft+=c);let u=l.scrollLeft-d,m=l.scrollTop-p;e={left:e.left-u,top:e.top-m,right:e.right-u,bottom:e.bottom-m}}if(a||/^(fixed|sticky)$/.test(getComputedStyle(o).position))break}}function ql(r){let e=r.dom.getBoundingClientRect(),t=Math.max(0,e.top),n,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){n=l,i=a.top;break}}return{refDOM:n,refTop:i,stack:Ms(r.dom)}}function Ms(r){let e=[],t=r.ownerDocument;for(let n=r;n&&(e.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),r!=t);n=Dt(n));return e}function Kl({refDOM:r,refTop:e,stack:t}){let n=r?r.getBoundingClientRect().top:0;Ts(t,n==0?0:n-e)}function Ts(r,e){for(let t=0;t=l){o=Math.max(u.bottom,o),l=Math.min(u.top,l);let m=u.left>e.left?u.left-e.left:u.right=(u.left+u.right)/2?1:0));continue}}else u.top>e.top&&!a&&u.left<=e.left&&u.right>=e.left&&(a=c,h={left:Math.max(u.left,Math.min(u.right,e.left)),top:u.top});!t&&(e.left>=u.right&&e.top>=u.top||e.left>=u.left&&e.top>=u.bottom)&&(s=f+1)}}return!t&&a&&(t=a,i=h,n=0),t&&t.nodeType==3?Ul(t,i):!t||n&&t.nodeType==1?{node:r,offset:s}:Es(t,i)}function Ul(r,e){let t=r.nodeValue.length,n=document.createRange();for(let i=0;i=(s.left+s.right)/2?1:0)}}return{node:r,offset:0}}function kr(r,e){return r.left>=e.left-1&&r.left<=e.right+1&&r.top>=e.top-1&&r.top<=e.bottom+1}function Gl(r,e){let t=r.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return r.docView.posFromDOM(n,i,s)}function jl(r,e,t,n){let i=-1;for(let s=e,o=!1;s!=r.dom;){let l=r.docView.nearestDesc(s,!0),a;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&(!o&&a.left>n.left||a.top>n.top?i=l.posBefore:(!o&&a.right-1?i:r.docView.posFromDOM(e,t,-1)}function Ds(r,e,t){let n=r.childNodes.length;if(n&&t.tope.top&&i++}let h;Ft&&i&&n.nodeType==1&&(h=n.childNodes[i-1]).nodeType==1&&h.contentEditable=="false"&&h.getBoundingClientRect().top>=e.top&&i--,n==r.dom&&i==n.childNodes.length-1&&n.lastChild.nodeType==1&&e.top>n.lastChild.getBoundingClientRect().bottom?l=r.state.doc.content.size:(i==0||n.nodeType!=1||n.childNodes[i-1].nodeName!="BR")&&(l=jl(r,n,i,e))}l==null&&(l=Yl(r,o,e));let a=r.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function Qr(r){return r.top=0&&i==n.nodeValue.length?(a--,c=1):t<0?a--:h++,ht(ye(oe(n,a,h),c),c<0)}if(!r.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==j(n))){let a=n.childNodes[i-1];if(a.nodeType==1)return An(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==j(n))){let a=n.childNodes[i-1],h=a.nodeType==3?oe(a,j(a)-(o?0:1)):a.nodeType==1&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(h)return ht(ye(h,1),!1)}if(s==null&&i=0)}function ht(r,e){if(r.width==0)return r;let t=e?r.left:r.right;return{top:r.top,bottom:r.bottom,left:t,right:t}}function An(r,e){if(r.height==0)return r;let t=e?r.top:r.bottom;return{top:t,bottom:t,left:r.left,right:r.right}}function Rs(r,e,t){let n=r.state,i=r.root.activeElement;n!=e&&r.updateState(e),i!=r.dom&&r.focus();try{return t()}finally{n!=e&&r.updateState(n),i!=r.dom&&i&&i.focus()}}function Ql(r,e,t){let n=e.selection,i=t=="up"?n.$from:n.$to;return Rs(r,e,()=>{let{node:s}=r.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=r.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=As(r,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(l.nodeType==1)a=l.getClientRects();else if(l.nodeType==3)a=oe(l,0,l.nodeValue.length).getClientRects();else continue;for(let h=0;hc.top+1&&(t=="up"?o.top-c.top>(c.bottom-o.top)*2:c.bottom-o.bottom>(o.bottom-c.top)*2))return!1}}return!0})}const _l=/[\u0590-\u08ac]/;function ea(r,e,t){let{$head:n}=e.selection;if(!n.parent.isTextblock)return!1;let i=n.parentOffset,s=!i,o=i==n.parent.content.size,l=r.domSelection();return l?!_l.test(n.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:Rs(r,e,()=>{let{focusNode:a,focusOffset:h,anchorNode:c,anchorOffset:f}=r.domSelectionRange(),d=l.caretBidiLevel;l.modify("move",t,"character");let p=n.depth?r.docView.domAfterPos(n.before()):r.dom,{focusNode:u,focusOffset:m}=r.domSelectionRange(),g=u&&!p.contains(u.nodeType==1?u:u.parentNode)||a==u&&h==m;try{l.collapse(c,f),a&&(a!=c||h!=f)&&l.extend&&l.extend(a,h)}catch{}return d!=null&&(l.caretBidiLevel=d),g}):n.pos==n.start()||n.pos==n.end()}let _r=null,ei=null,ti=!1;function ta(r,e,t){return _r==e&&ei==t?ti:(_r=e,ei=t,ti=t=="up"||t=="down"?Ql(r,e,t):ea(r,e,t))}const X=0,ni=1,Ae=2,ie=3;class Vt{constructor(e,t,n,i){this.parent=e,this.children=t,this.dom=n,this.contentDOM=i,this.dirty=X,n.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,n){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tz(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??n>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let n=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(n&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))n=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let n=t;n;n=n.parent)if(n==this)return t}posFromDOM(e,t,n){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,n)}return-1}descAt(e){for(let t=0,n=0;te||o instanceof zs){i=e-s;break}s=l}if(i)return this.children[n].domFromPos(i-this.children[n].border,t);for(let s;n&&!(s=this.children[n-1]).size&&s instanceof Is&&s.side>=0;n--);if(t<=0){let s,o=!0;for(;s=n?this.children[n-1]:null,!(!s||s.dom.parentNode==this.contentDOM);n--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?z(s.dom)+1:0}}else{let s,o=!0;for(;s=n=c&&t<=h-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,c);e=o;for(let f=l;f>0;f--){let d=this.children[f-1];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(1)){i=z(d.dom)+1;break}e-=d.size}i==-1&&(i=0)}if(i>-1&&(h>t||l==this.children.length-1)){t=h;for(let c=l+1;cu&&ot){let u=l;l=a,a=u}let p=document.createRange();p.setEnd(a.node,a.offset),p.setStart(l.node,l.offset),h.removeAllRanges(),h.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let n=0,i=0;i=n:en){let l=n+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==n||t==o?Ae:ni,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=ie:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Ae:ie}n=o}this.dirty=Ae}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let n=e==1?Ae:ni;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==X&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get side(){return this.widget.type.side}}class na extends Vt{constructor(e,t,n,i){super(e,[],t,null),this.textDOM=n,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Ke extends Vt{constructor(e,t,n,i,s){super(e,[],n,i),this.mark=t,this.spec=s}static create(e,t,n,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,n);return(!o||!o.dom)&&(o=at.renderSpec(document,t.type.spec.toDOM(t,n),null,t.attrs)),new Ke(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&ie||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=ie&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=X){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty0&&(s=nr(s,0,e,n));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},n,i),c=h&&h.dom,f=h&&h.contentDOM;if(t.isText){if(!c)c=document.createTextNode(t.text);else if(c.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else c||({dom:c,contentDOM:f}=at.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!f&&!t.isText&&c.nodeName!="BR"&&(c.hasAttribute("contenteditable")||(c.contentEditable="false"),t.type.spec.draggable&&(c.draggable=!0));let d=c;return c=Bs(c,n,t),h?a=new ra(e,t,n,i,c,f||null,d,h,s,o+1):t.isText?new yn(e,t,n,i,c,d,s):new Ce(e,t,n,i,c,f||null,d,s,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let n=this.children[t];if(this.dom.contains(n.dom.parentNode)){e.contentElement=n.dom.parentNode;break}}e.contentElement||(e.getContent=()=>y.empty)}return e}matchesNode(e,t,n){return this.dirty==X&&e.eq(this.node)&&on(t,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let n=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new sa(this,o&&o.node,e);aa(this.node,this.innerDeco,(h,c,f)=>{h.spec.marks?a.syncToMarks(h.spec.marks,n,e):h.type.side>=0&&!f&&a.syncToMarks(c==this.node.childCount?C.none:this.node.child(c).marks,n,e),a.placeWidget(h,e,i)},(h,c,f,d)=>{a.syncToMarks(h.marks,n,e);let p;a.findNodeMatch(h,c,f,d)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(h,c,f,p,e)||a.updateNextNode(h,c,f,e,d,i)||a.addNode(h,c,f,e,i),i+=h.nodeSize}),a.syncToMarks([],n,e),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==Ae)&&(o&&this.protectLocalComposition(e,o),vs(this.contentDOM,this.children,e),it&&ha(this.dom))}localCompositionInfo(e,t){let{from:n,to:i}=e.state.selection;if(!(e.state.selection instanceof M)||nt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=ca(this.node.content,o,n-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:n,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new na(this,s,t,i);e.input.compositionNodes.push(o),this.children=nr(this.children,n,n+i.length,e,o)}update(e,t,n,i){return this.dirty==ie||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,n,i),!0)}updateInner(e,t,n,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=n,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=X}updateOuterDeco(e){if(on(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=Ps(this.dom,this.nodeDOM,tr(this.outerDeco,this.node,t),tr(e,this.node,t)),this.dom!=n&&(n.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.dom.draggable=!0)}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.dom.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function ri(r,e,t,n,i){Bs(n,e,r);let s=new Ce(void 0,r,e,t,n,n,n,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class yn extends Ce{constructor(e,t,n,i,s,o,l){super(e,t,n,i,s,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,n,i){return this.dirty==ie||this.dirty!=X&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=X||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=X,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,n){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,n)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,n){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new yn(this.parent,i,this.outerDeco,this.innerDeco,s,s,n)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=ie)}get domAtom(){return!1}isText(e){return this.node.text==e}}class zs extends Vt{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==X&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class ra extends Ce{constructor(e,t,n,i,s,o,l,a,h,c){super(e,t,n,i,s,o,l,h,c),this.spec=a}update(e,t,n,i){if(this.dirty==ie)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,n);return s&&this.updateInner(e,t,n,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,n,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,n,i){this.spec.setSelection?this.spec.setSelection(e,t,n.root):super.setSelection(e,t,n,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function vs(r,e,t){let n=r.firstChild,i=!1;for(let s=0;s>1,o=Math.min(s,e.length);for(;i-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let a=Ke.create(this.top,e[s],t,n);this.top.children.splice(this.index,0,a),this.top=a,this.changed=!0}this.index=0,s++}}findNodeMatch(e,t,n,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,n))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(n){let h=t.children[n-1];if(h instanceof Ke)t=h,n=h.children.length;else{l=h,n--;break}}else{if(t==e)break e;n=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=r.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function la(r,e){return r.type.side-e.type.side}function aa(r,e,t,n){let i=e.locals(r),s=0;if(i.length==0){for(let h=0;hs;)l.push(i[o++]);let u=s+d.nodeSize;if(d.isText){let g=u;o!g.inline):l.slice();n(d,m,e.forChild(s,d),p),s=u}}function ha(r){if(r.nodeName=="UL"||r.nodeName=="OL"){let e=r.style.cssText;r.style.cssText=e+"; list-style: square !important",window.getComputedStyle(r).listStyle,r.style.cssText=e}}function ca(r,e,t,n){for(let i=0,s=0;i=t){if(s>=n&&a.slice(n-e.length-l,n-l)==e)return n-e.length;let h=l=0&&h+e.length+l>=t)return l+h;if(t==n&&a.length>=n+e.length-l&&a.slice(n-l,n-l+e.length)==e)return n}}return-1}function nr(r,e,t,n,i){let s=[];for(let o=0,l=0;o=t||c<=e?s.push(a):(ht&&s.push(a.slice(t-h,a.size,n)))}return s}function xr(r,e=null){let t=r.domSelectionRange(),n=r.state.doc;if(!t.focusNode)return null;let i=r.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=r.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=n.resolve(o),a,h;if(gn(t)){for(a=o;i&&!i.node;)i=i.parent;let f=i.node;if(i&&f.isAtom&&x.isSelectable(f)&&i.parent&&!(f.isInline&&Bl(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;h=new x(o==d?l:n.resolve(d))}}else{if(t instanceof r.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let f=o,d=o;for(let p=0;p{(t.anchorNode!=n||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",r.input.hideSelectionGuard),setTimeout(()=>{(!Fs(r)||r.state.selection.visible)&&r.dom.classList.remove("ProseMirror-hideselection")},20))})}function ua(r){let e=r.domSelection(),t=document.createRange();if(!e)return;let n=r.cursorWrapper.dom,i=n.nodeName=="IMG";i?t.setStart(n.parentNode,z(n)+1):t.setStart(n,0),t.collapse(!0),e.removeAllRanges(),e.addRange(t),!i&&!r.state.selection.visible&&H&&we<=11&&(n.disabled=!0,n.disabled=!1)}function Vs(r,e){if(e instanceof x){let t=r.docView.descAt(e.from);t!=r.lastSelectedViewDesc&&(ai(r),t&&t.selectNode(),r.lastSelectedViewDesc=t)}else ai(r)}function ai(r){r.lastSelectedViewDesc&&(r.lastSelectedViewDesc.parent&&r.lastSelectedViewDesc.deselectNode(),r.lastSelectedViewDesc=void 0)}function br(r,e,t,n){return r.someProp("createSelectionBetween",i=>i(r,e,t))||M.between(e,t,n)}function hi(r){return r.editable&&!r.hasFocus()?!1:Ls(r)}function Ls(r){let e=r.domSelectionRange();if(!e.anchorNode)return!1;try{return r.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(r.editable||r.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function da(r){let e=r.docView.domFromPos(r.state.selection.anchor,0),t=r.domSelectionRange();return qe(e.node,e.offset,t.anchorNode,t.anchorOffset)}function rr(r,e){let{$anchor:t,$head:n}=r.selection,i=e>0?t.max(n):t.min(n),s=i.parent.inlineContent?i.depth?r.doc.resolve(e>0?i.after():i.before()):null:i;return s&&w.findFrom(s,e)}function Se(r,e){return r.dispatch(r.state.tr.setSelection(e).scrollIntoView()),!0}function ci(r,e,t){let n=r.state.selection;if(n instanceof M)if(t.indexOf("s")>-1){let{$head:i}=n,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=r.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Se(r,new M(n.$anchor,o))}else if(n.empty){if(r.endOfTextblock(e>0?"forward":"backward")){let i=rr(r.state,e);return i&&i instanceof x?Se(r,i):!1}else if(!(Y&&t.indexOf("m")>-1)){let i=n.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=r.docView.descAt(l))&&!o.contentDOM?x.isSelectable(s)?Se(r,new x(e<0?r.state.doc.resolve(i.pos-s.nodeSize):i)):Ft?Se(r,new M(r.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(n instanceof x&&n.node.isInline)return Se(r,new M(e>0?n.$to:n.$from));{let i=rr(r.state,e);return i?Se(r,i):!1}}}function ln(r){return r.nodeType==3?r.nodeValue.length:r.childNodes.length}function wt(r,e){let t=r.pmViewDesc;return t&&t.size==0&&(e<0||r.nextSibling||r.nodeName!="BR")}function Ue(r,e){return e<0?pa(r):ma(r)}function pa(r){let e=r.domSelectionRange(),t=e.focusNode,n=e.focusOffset;if(!t)return;let i,s,o=!1;for(ee&&t.nodeType==1&&n0){if(t.nodeType!=1)break;{let l=t.childNodes[n-1];if(wt(l,-1))i=t,s=--n;else if(l.nodeType==3)t=l,n=t.nodeValue.length;else break}}else{if(Js(t))break;{let l=t.previousSibling;for(;l&&wt(l,-1);)i=t.parentNode,s=z(l),l=l.previousSibling;if(l)t=l,n=ln(t);else{if(t=t.parentNode,t==r.dom)break;n=0}}}o?ir(r,t,n):i&&ir(r,i,s)}function ma(r){let e=r.domSelectionRange(),t=e.focusNode,n=e.focusOffset;if(!t)return;let i=ln(t),s,o;for(;;)if(n{r.state==i&&fe(r)},50)}function fi(r,e){let t=r.state.doc.resolve(e);if(!(B||Ll)&&t.parent.inlineContent){let i=r.coordsAtPos(e);if(e>t.start()){let s=r.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(r.dom).direction=="rtl"?"rtl":"ltr"}function ui(r,e,t){let n=r.state.selection;if(n instanceof M&&!n.empty||t.indexOf("s")>-1||Y&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=n;if(!i.parent.inlineContent||r.endOfTextblock(e<0?"up":"down")){let o=rr(r.state,e);if(o&&o instanceof x)return Se(r,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=n instanceof ce?w.near(o,e):w.findFrom(o,e);return l?Se(r,l):!1}return!1}function di(r,e){if(!(r.state.selection instanceof M))return!0;let{$head:t,$anchor:n,empty:i}=r.state.selection;if(!t.sameParent(n))return!0;if(!i)return!1;if(r.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=r.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),r.dispatch(o),!0}return!1}function pi(r,e,t){r.domObserver.stop(),e.contentEditable=t,r.domObserver.start()}function Sa(r){if(!$||r.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=r.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let n=e.firstChild;pi(r,n,"true"),setTimeout(()=>pi(r,n,"false"),20)}return!1}function ka(r){let e="";return r.ctrlKey&&(e+="c"),r.metaKey&&(e+="m"),r.altKey&&(e+="a"),r.shiftKey&&(e+="s"),e}function xa(r,e){let t=e.keyCode,n=ka(e);if(t==8||Y&&t==72&&n=="c")return di(r,-1)||Ue(r,-1);if(t==46&&!e.shiftKey||Y&&t==68&&n=="c")return di(r,1)||Ue(r,1);if(t==13||t==27)return!0;if(t==37||Y&&t==66&&n=="c"){let i=t==37?fi(r,r.state.selection.from)=="ltr"?-1:1:-1;return ci(r,i,n)||Ue(r,i)}else if(t==39||Y&&t==70&&n=="c"){let i=t==39?fi(r,r.state.selection.from)=="ltr"?1:-1:1;return ci(r,i,n)||Ue(r,i)}else{if(t==38||Y&&t==80&&n=="c")return ui(r,-1,n)||Ue(r,-1);if(t==40||Y&&t==78&&n=="c")return Sa(r)||ui(r,1,n)||Ue(r,1);if(n==(Y?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function $s(r,e){r.someProp("transformCopied",p=>{e=p(e,r)});let t=[],{content:n,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&n.childCount==1&&n.firstChild.childCount==1;){i--,s--;let p=n.firstChild;t.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),n=p.content}let o=r.someProp("clipboardSerializer")||at.fromSchema(r.state.schema),l=Gs(),a=l.createElement("div");a.appendChild(o.serializeFragment(n,{document:l}));let h=a.firstChild,c,f=0;for(;h&&h.nodeType==1&&(c=Us[h.nodeName.toLowerCase()]);){for(let p=c.length-1;p>=0;p--){let u=l.createElement(c[p]);for(;a.firstChild;)u.appendChild(a.firstChild);a.appendChild(u),f++}h=a.firstChild}h&&h.nodeType==1&&h.setAttribute("data-pm-slice",`${i} ${s}${f?` -${f}`:""} ${JSON.stringify(t)}`);let d=r.someProp("clipboardTextSerializer",p=>p(e,r))||e.content.textBetween(0,e.content.size,` + +`);return{dom:a,text:d,slice:e}}function Ws(r,e,t,n,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=e&&(n||s||!t);if(a){if(r.someProp("transformPastedText",d=>{e=d(e,s||n,r)}),s)return e?new S(y.from(r.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0):S.empty;let f=r.someProp("clipboardTextParser",d=>d(e,i,n,r));if(f)l=f;else{let d=i.marks(),{schema:p}=r.state,u=at.fromSchema(p);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(u.serializeNode(p.text(m,d)))})}}else r.someProp("transformPastedHTML",f=>{t=f(t,r)}),o=Na(t),Ft&&Oa(o);let h=o&&o.querySelector("[data-pm-slice]"),c=h&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(h.getAttribute("data-pm-slice")||"");if(c&&c[3])for(let f=+c[3];f>0;f--){let d=o.firstChild;for(;d&&d.nodeType!=1;)d=d.nextSibling;if(!d)break;o=d}if(l||(l=(r.someProp("clipboardParser")||r.someProp("domParser")||Tt.fromSchema(r.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||c),context:i,ruleFromNode(d){return d.nodeName=="BR"&&!d.nextSibling&&d.parentNode&&!ba.test(d.parentNode.nodeName)?{ignore:!0}:null}})),c)l=Ma(mi(l,+c[1],+c[2]),c[4]);else if(l=S.maxOpen(wa(l.content,i),!0),l.openStart||l.openEnd){let f=0,d=0;for(let p=l.content.firstChild;f{l=f(l,r)}),l}const ba=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function wa(r,e){if(r.childCount<2)return r;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(r.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),h;if(!a)return o=null;if(h=o.length&&s.length&&Ks(a,s,l,o[o.length-1],0))o[o.length-1]=h;else{o.length&&(o[o.length-1]=Hs(o[o.length-1],s.length));let c=qs(l,a);o.push(c),i=i.matchType(c.type),s=a}}),o)return y.from(o)}return r}function qs(r,e,t=0){for(let n=e.length-1;n>=t;n--)r=e[n].create(null,y.from(r));return r}function Ks(r,e,t,n,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(y.empty,!0))),r.replaceChild(e<0?0:r.childCount-1,o.copy(l))}function mi(r,e,t){return et})),In.createHTML(r)):r}function Na(r){let e=/^(\s*]*>)*/.exec(r);e&&(r=r.slice(e[0].length));let t=Gs().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(r),i;if((i=n&&Us[n[1].toLowerCase()])&&(r=i.map(s=>"<"+s+">").join("")+r+i.map(s=>"").reverse().join("")),t.innerHTML=Ca(r),i)for(let s=0;s=0;l-=2){let a=t.nodes[n[l]];if(!a||a.hasRequiredAttrs())break;i=y.from(a.create(n[l+1],i)),s++,o++}return new S(i,s,o)}const W={},q={},Ta={touchstart:!0,touchmove:!0};class Ea{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:""},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Da(r){for(let e in W){let t=W[e];r.dom.addEventListener(e,r.input.eventHandlers[e]=n=>{Ra(r,n)&&!wr(r,n)&&(r.editable||!(n.type in q))&&t(r,n)},Ta[e]?{passive:!0}:void 0)}$&&r.dom.addEventListener("input",()=>null),or(r)}function be(r,e){r.input.lastSelectionOrigin=e,r.input.lastSelectionTime=Date.now()}function Aa(r){r.domObserver.stop();for(let e in r.input.eventHandlers)r.dom.removeEventListener(e,r.input.eventHandlers[e]);clearTimeout(r.input.composingTimeout),clearTimeout(r.input.lastIOSEnterFallbackTimeout)}function or(r){r.someProp("handleDOMEvents",e=>{for(let t in e)r.input.eventHandlers[t]||r.dom.addEventListener(t,r.input.eventHandlers[t]=n=>wr(r,n))})}function wr(r,e){return r.someProp("handleDOMEvents",t=>{let n=t[e.type];return n?n(r,e)||e.defaultPrevented:!1})}function Ra(r,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=r.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function Ia(r,e){!wr(r,e)&&W[e.type]&&(r.editable||!(e.type in q))&&W[e.type](r,e)}q.keydown=(r,e)=>{let t=e;if(r.input.shiftKey=t.keyCode==16||t.shiftKey,!js(r,t)&&(r.input.lastKeyCode=t.keyCode,r.input.lastKeyCodeTime=Date.now(),!(he&&B&&t.keyCode==13)))if(t.keyCode!=229&&r.domObserver.forceFlush(),it&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let n=Date.now();r.input.lastIOSEnter=n,r.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{r.input.lastIOSEnter==n&&(r.someProp("handleKeyDown",i=>i(r,De(13,"Enter"))),r.input.lastIOSEnter=0)},200)}else r.someProp("handleKeyDown",n=>n(r,t))||xa(r,t)?t.preventDefault():be(r,"key")};q.keyup=(r,e)=>{e.keyCode==16&&(r.input.shiftKey=!1)};q.keypress=(r,e)=>{let t=e;if(js(r,t)||!t.charCode||t.ctrlKey&&!t.altKey||Y&&t.metaKey)return;if(r.someProp("handleKeyPress",i=>i(r,t))){t.preventDefault();return}let n=r.state.selection;if(!(n instanceof M)||!n.$from.sameParent(n.$to)){let i=String.fromCharCode(t.charCode);!/[\r\n]/.test(i)&&!r.someProp("handleTextInput",s=>s(r,n.$from.pos,n.$to.pos,i))&&r.dispatch(r.state.tr.insertText(i).scrollIntoView()),t.preventDefault()}};function Sn(r){return{left:r.clientX,top:r.clientY}}function za(r,e){let t=e.x-r.clientX,n=e.y-r.clientY;return t*t+n*n<100}function Cr(r,e,t,n,i){if(n==-1)return!1;let s=r.state.doc.resolve(n);for(let o=s.depth+1;o>0;o--)if(r.someProp(e,l=>o>s.depth?l(r,t,s.nodeAfter,s.before(o),i,!0):l(r,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function et(r,e,t){if(r.focused||r.focus(),r.state.selection.eq(e))return;let n=r.state.tr.setSelection(e);n.setMeta("pointer",!0),r.dispatch(n)}function va(r,e){if(e==-1)return!1;let t=r.state.doc.resolve(e),n=t.nodeAfter;return n&&n.isAtom&&x.isSelectable(n)?(et(r,new x(t)),!0):!1}function Pa(r,e){if(e==-1)return!1;let t=r.state.selection,n,i;t instanceof x&&(n=t.node);let s=r.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(x.isSelectable(l)){n&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(et(r,x.create(r.state.doc,i)),!0):!1}function Ba(r,e,t,n,i){return Cr(r,"handleClickOn",e,t,n)||r.someProp("handleClick",s=>s(r,e,n))||(i?Pa(r,t):va(r,t))}function Fa(r,e,t,n){return Cr(r,"handleDoubleClickOn",e,t,n)||r.someProp("handleDoubleClick",i=>i(r,e,n))}function Va(r,e,t,n){return Cr(r,"handleTripleClickOn",e,t,n)||r.someProp("handleTripleClick",i=>i(r,e,n))||La(r,t,n)}function La(r,e,t){if(t.button!=0)return!1;let n=r.state.doc;if(e==-1)return n.inlineContent?(et(r,M.create(n,0,n.content.size)),!0):!1;let i=n.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)et(r,M.create(n,l+1,l+1+o.content.size));else if(x.isSelectable(o))et(r,x.create(n,l));else continue;return!0}}function Nr(r){return an(r)}const Ys=Y?"metaKey":"ctrlKey";W.mousedown=(r,e)=>{let t=e;r.input.shiftKey=t.shiftKey;let n=Nr(r),i=Date.now(),s="singleClick";i-r.input.lastClick.time<500&&za(t,r.input.lastClick)&&!t[Ys]&&(r.input.lastClick.type=="singleClick"?s="doubleClick":r.input.lastClick.type=="doubleClick"&&(s="tripleClick")),r.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s};let o=r.posAtCoords(Sn(t));o&&(s=="singleClick"?(r.input.mouseDown&&r.input.mouseDown.done(),r.input.mouseDown=new Ja(r,o,t,!!n)):(s=="doubleClick"?Fa:Va)(r,o.pos,o.inside,t)?t.preventDefault():be(r,"pointer"))};class Ja{constructor(e,t,n,i){this.view=e,this.pos=t,this.event=n,this.flushed=i,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!n[Ys],this.allowDefault=n.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let c=e.state.doc.resolve(t.pos);s=c.parent,o=c.depth?c.before():0}const l=i?null:n.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&a.dom.nodeType==1?a.dom:null;let{selection:h}=e.state;(n.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||h instanceof x&&h.from<=o&&h.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&ee&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),be(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>fe(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(Sn(e))),this.updateAllowDefault(e),this.allowDefault||!t?be(this.view,"pointer"):Ba(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||$&&this.mightDrag&&!this.mightDrag.node.isAtom||B&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(et(this.view,w.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):be(this.view,"pointer")}move(e){this.updateAllowDefault(e),be(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}W.touchstart=r=>{r.input.lastTouch=Date.now(),Nr(r),be(r,"pointer")};W.touchmove=r=>{r.input.lastTouch=Date.now(),be(r,"pointer")};W.contextmenu=r=>Nr(r);function js(r,e){return r.composing?!0:$&&Math.abs(e.timeStamp-r.input.compositionEndedAt)<500?(r.input.compositionEndedAt=-2e8,!0):!1}const $a=he?5e3:-1;q.compositionstart=q.compositionupdate=r=>{if(!r.composing){r.domObserver.flush();let{state:e}=r,t=e.selection.$to;if(e.selection instanceof M&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)))r.markCursor=r.state.storedMarks||t.marks(),an(r,!0),r.markCursor=null;else if(an(r,!e.selection.empty),ee&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let n=r.domSelectionRange();for(let i=n.focusNode,s=n.focusOffset;i&&i.nodeType==1&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(o.nodeType==3){let l=r.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}r.input.composing=!0}Xs(r,$a)};q.compositionend=(r,e)=>{r.composing&&(r.input.composing=!1,r.input.compositionEndedAt=e.timeStamp,r.input.compositionPendingChanges=r.domObserver.pendingRecords().length?r.input.compositionID:0,r.input.compositionNode=null,r.input.compositionPendingChanges&&Promise.resolve().then(()=>r.domObserver.flush()),r.input.compositionID++,Xs(r,20))};function Xs(r,e){clearTimeout(r.input.composingTimeout),e>-1&&(r.input.composingTimeout=setTimeout(()=>an(r),e))}function Zs(r){for(r.composing&&(r.input.composing=!1,r.input.compositionEndedAt=qa());r.input.compositionNodes.length>0;)r.input.compositionNodes.pop().markParentsDirty()}function Wa(r){let e=r.domSelectionRange();if(!e.focusNode)return null;let t=vl(e.focusNode,e.focusOffset),n=Pl(e.focusNode,e.focusOffset);if(t&&n&&t!=n){let i=n.pmViewDesc,s=r.domObserver.lastChangedTextNode;if(t==s||n==s)return s;if(!i||!i.isText(n.nodeValue))return n;if(r.input.compositionNode==n){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return n}}return t||n}function qa(){let r=document.createEvent("Event");return r.initEvent("event",!0,!0),r.timeStamp}function an(r,e=!1){if(!(he&&r.domObserver.flushingSoon>=0)){if(r.domObserver.forceFlush(),Zs(r),e||r.docView&&r.docView.dirty){let t=xr(r);return t&&!t.eq(r.state.selection)?r.dispatch(r.state.tr.setSelection(t)):(r.markCursor||e)&&!r.state.selection.empty?r.dispatch(r.state.tr.deleteSelection()):r.updateState(r.state),!0}return!1}}function Ka(r,e){if(!r.dom.parentNode)return;let t=r.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),i=document.createRange();i.selectNodeContents(e),r.dom.blur(),n.removeAllRanges(),n.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),r.focus()},50)}const At=H&&we<15||it&&Jl<604;W.copy=q.cut=(r,e)=>{let t=e,n=r.state.selection,i=t.type=="cut";if(n.empty)return;let s=At?null:t.clipboardData,o=n.content(),{dom:l,text:a}=$s(r,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Ka(r,l),i&&r.dispatch(r.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Ha(r){return r.openStart==0&&r.openEnd==0&&r.content.childCount==1?r.content.firstChild:null}function Ua(r,e){if(!r.dom.parentNode)return;let t=r.input.shiftKey||r.state.selection.$from.parent.type.spec.code,n=r.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let i=r.input.shiftKey&&r.input.lastKeyCode!=45;setTimeout(()=>{r.focus(),n.parentNode&&n.parentNode.removeChild(n),t?Rt(r,n.value,null,i,e):Rt(r,n.textContent,n.innerHTML,i,e)},50)}function Rt(r,e,t,n,i){let s=Ws(r,e,t,n,r.state.selection.$from);if(r.someProp("handlePaste",a=>a(r,i,s||S.empty)))return!0;if(!s)return!1;let o=Ha(s),l=o?r.state.tr.replaceSelectionWith(o,n):r.state.tr.replaceSelection(s);return r.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Qs(r){let e=r.getData("text/plain")||r.getData("Text");if(e)return e;let t=r.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}q.paste=(r,e)=>{let t=e;if(r.composing&&!he)return;let n=At?null:t.clipboardData,i=r.input.shiftKey&&r.input.lastKeyCode!=45;n&&Rt(r,Qs(n),n.getData("text/html"),i,t)?t.preventDefault():Ua(r,t)};class _s{constructor(e,t,n){this.slice=e,this.move=t,this.node=n}}const eo=Y?"altKey":"ctrlKey";W.dragstart=(r,e)=>{let t=e,n=r.input.mouseDown;if(n&&n.done(),!t.dataTransfer)return;let i=r.state.selection,s=i.empty?null:r.posAtCoords(Sn(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof x?i.to-1:i.to))){if(n&&n.mightDrag)o=x.create(r.state.doc,n.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let f=r.docView.nearestDesc(t.target,!0);f&&f.node.type.spec.draggable&&f!=r.docView&&(o=x.create(r.state.doc,f.posBefore))}}let l=(o||r.state.selection).content(),{dom:a,text:h,slice:c}=$s(r,l);(!t.dataTransfer.files.length||!B||Os>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(At?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",At||t.dataTransfer.setData("text/plain",h),r.dragging=new _s(c,!t[eo],o)};W.dragend=r=>{let e=r.dragging;window.setTimeout(()=>{r.dragging==e&&(r.dragging=null)},50)};q.dragover=q.dragenter=(r,e)=>e.preventDefault();q.drop=(r,e)=>{let t=e,n=r.dragging;if(r.dragging=null,!t.dataTransfer)return;let i=r.posAtCoords(Sn(t));if(!i)return;let s=r.state.doc.resolve(i.pos),o=n&&n.slice;o?r.someProp("transformPasted",u=>{o=u(o,r)}):o=Ws(r,Qs(t.dataTransfer),At?null:t.dataTransfer.getData("text/html"),!1,s);let l=!!(n&&!t[eo]);if(r.someProp("handleDrop",u=>u(r,t,o||S.empty,l))){t.preventDefault();return}if(!o)return;t.preventDefault();let a=o?kl(r.state.doc,s.pos,o):s.pos;a==null&&(a=s.pos);let h=r.state.tr;if(l){let{node:u}=n;u?u.replace(h):h.deleteSelection()}let c=h.mapping.map(a),f=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,d=h.doc;if(f?h.replaceRangeWith(c,c,o.content.firstChild):h.replaceRange(c,c,o),h.doc.eq(d))return;let p=h.doc.resolve(c);if(f&&x.isSelectable(o.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(o.content.firstChild))h.setSelection(new x(p));else{let u=h.mapping.map(a);h.mapping.maps[h.mapping.maps.length-1].forEach((m,g,k,T)=>u=T),h.setSelection(br(r,p,h.doc.resolve(u)))}r.focus(),r.dispatch(h.setMeta("uiEvent","drop"))};W.focus=r=>{r.input.lastFocus=Date.now(),r.focused||(r.domObserver.stop(),r.dom.classList.add("ProseMirror-focused"),r.domObserver.start(),r.focused=!0,setTimeout(()=>{r.docView&&r.hasFocus()&&!r.domObserver.currentSelection.eq(r.domSelectionRange())&&fe(r)},20))};W.blur=(r,e)=>{let t=e;r.focused&&(r.domObserver.stop(),r.dom.classList.remove("ProseMirror-focused"),r.domObserver.start(),t.relatedTarget&&r.dom.contains(t.relatedTarget)&&r.domObserver.currentSelection.clear(),r.focused=!1)};W.beforeinput=(r,e)=>{if(B&&he&&e.inputType=="deleteContentBackward"){r.domObserver.flushSoon();let{domChangeCount:n}=r.input;setTimeout(()=>{if(r.input.domChangeCount!=n||(r.dom.blur(),r.focus(),r.someProp("handleKeyDown",s=>s(r,De(8,"Backspace")))))return;let{$cursor:i}=r.state.selection;i&&i.pos>0&&r.dispatch(r.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let r in q)W[r]=q[r];function It(r,e){if(r==e)return!0;for(let t in r)if(r[t]!==e[t])return!1;for(let t in e)if(!(t in r))return!1;return!0}class hn{constructor(e,t){this.toDOM=e,this.spec=t||Ve,this.side=this.spec.side||0}map(e,t,n,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new Q(s-n,s-n,this)}valid(){return!0}eq(e){return this==e||e instanceof hn&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&It(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Ne{constructor(e,t){this.attrs=e,this.spec=t||Ve}map(e,t,n,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-n,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-n;return s>=o?null:new Q(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&n.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,n,i+l,s)}}map(e,t,n){return this==P||e.maps.length==0?this:this.mapInner(e,t,0,0,n||Ve)}mapInner(e,t,n,i,s){let o;for(let l=0;l{let h=a+n,c;if(c=no(t,l,h)){for(i||(i=this.children.slice());sl&&f.to=e){this.children[l]==e&&(n=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof Ne){let h=Math.max(s,a.from)-s,c=Math.min(o,a.to)-s;hi.map(e,t,Ve));return xe.from(n)}forChild(e,t){if(t.isLeaf)return D.empty;let n=[];for(let i=0;it instanceof D)?e:e.reduce((t,n)=>t.concat(n instanceof D?n:n.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-u-(p-d);for(let k=0;kT+c-f)continue;let K=l[k]+c-f;p>=K?l[k+1]=d<=K?-2:-1:d>=c&&g&&(l[k]+=g,l[k+1]+=g)}f+=g}),c=t.maps[h].map(c,-1)}let a=!1;for(let h=0;h=n.content.size){a=!0;continue}let d=t.map(r[h+1]+s,-1),p=d-i,{index:u,offset:m}=n.content.findIndex(f),g=n.maybeChild(u);if(g&&m==f&&m+g.nodeSize==p){let k=l[h+2].mapInner(t,g,c+1,r[h]+s+1,o);k!=P?(l[h]=f,l[h+1]=p,l[h+2]=k):(l[h+1]=-2,a=!0)}else a=!0}if(a){let h=Ya(l,r,e,t,i,s,o),c=cn(h,n,0,o);e=c.local;for(let f=0;ft&&o.to{let h=no(r,l,a+t);if(h){s=!0;let c=cn(h,l,t+a+1,n);c!=P&&i.push(a,a+l.nodeSize,c)}});let o=to(s?ro(r):r,-t).sort(Le);for(let l=0;l0;)e++;r.splice(e,0,t)}function zn(r){let e=[];return r.someProp("decorations",t=>{let n=t(r.state);n&&n!=P&&e.push(n)}),r.cursorWrapper&&e.push(D.create(r.state.doc,[r.cursorWrapper.deco])),xe.from(e)}const ja={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Xa=H&&we<=11;class Za{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Qa{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Za,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(n=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),Xa&&(this.onCharData=n=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,ja)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(hi(this.view)){if(this.suppressingSelectionUpdates)return fe(this.view);if(H&&we<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&qe(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,n;for(let s=e.focusNode;s;s=Dt(s))t.add(s);for(let s=e.anchorNode;s;s=Dt(s))if(t.has(s)){n=s;break}let i=n&&this.view.docView.nearestDesc(n);if(i&&i.ignoreMutation({type:"selection",target:n.nodeType==3?n.parentNode:n}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let n=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&hi(e)&&!this.ignoreSelectionChange(n),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let c=0;cf.nodeName=="BR");if(c.length==2){let[f,d]=c;f.parentNode&&f.parentNode.parentNode==d.parentNode?d.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let d of c){let p=d.parentNode;p&&p.nodeName=="LI"&&(!f||th(e,f)!=p)&&d.remove()}}}let h=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),_a(e)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(n)||fe(e),this.currentSelection.set(n))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let n=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(n==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!n||n.ignoreMutation(e))return null;if(e.type=="childList"){for(let c=0;ci;g--){let k=n.childNodes[g-1],T=k.pmViewDesc;if(k.nodeName=="BR"&&!T){s=g;break}if(!T||T.size)break}let f=r.state.doc,d=r.someProp("domParser")||Tt.fromSchema(r.state.schema),p=f.resolve(o),u=null,m=d.parse(n,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:i,to:s,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:h,ruleFromNode:rh,context:p});if(h&&h[0].pos!=null){let g=h[0].pos,k=h[1]&&h[1].pos;k==null&&(k=g),u={anchor:g+o,head:k+o}}return{doc:m,sel:u,from:o,to:l}}function rh(r){let e=r.pmViewDesc;if(e)return e.parseRule();if(r.nodeName=="BR"&&r.parentNode){if($&&/^(ul|ol)$/i.test(r.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}else if(r.parentNode.lastChild==r||$&&/^(tr|table)$/i.test(r.parentNode.nodeName))return{ignore:!0}}else if(r.nodeName=="IMG"&&r.getAttribute("mark-placeholder"))return{ignore:!0};return null}const ih=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function sh(r,e,t,n,i){let s=r.input.compositionPendingChanges||(r.composing?r.input.compositionID:0);if(r.input.compositionPendingChanges=0,e<0){let b=r.input.lastSelectionTime>Date.now()-50?r.input.lastSelectionOrigin:null,ge=xr(r,b);if(ge&&!r.state.selection.eq(ge)){if(B&&he&&r.input.lastKeyCode===13&&Date.now()-100Mo(r,De(13,"Enter"))))return;let Jt=r.state.tr.setSelection(ge);b=="pointer"?Jt.setMeta("pointer",!0):b=="key"&&Jt.scrollIntoView(),s&&Jt.setMeta("composition",s),r.dispatch(Jt)}return}let o=r.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=r.state.doc.resolve(t).after(l+1);let a=r.state.selection,h=nh(r,e,t),c=r.state.doc,f=c.slice(h.from,h.to),d,p;r.input.lastKeyCode===8&&Date.now()-100Date.now()-225||he)&&i.some(b=>b.nodeType==1&&!ih.test(b.nodeName))&&(!u||u.endA>=u.endB)&&r.someProp("handleKeyDown",b=>b(r,De(13,"Enter")))){r.input.lastIOSEnter=0;return}if(!u)if(n&&a instanceof M&&!a.empty&&a.$head.sameParent(a.$anchor)&&!r.composing&&!(h.sel&&h.sel.anchor!=h.sel.head))u={start:a.from,endA:a.to,endB:a.to};else{if(h.sel){let b=bi(r,r.state.doc,h.sel);if(b&&!b.eq(r.state.selection)){let ge=r.state.tr.setSelection(b);s&&ge.setMeta("composition",s),r.dispatch(ge)}}return}r.state.selection.fromr.state.selection.from&&u.start<=r.state.selection.from+2&&r.state.selection.from>=h.from?u.start=r.state.selection.from:u.endA=r.state.selection.to-2&&r.state.selection.to<=h.to&&(u.endB+=r.state.selection.to-u.endA,u.endA=r.state.selection.to)),H&&we<=11&&u.endB==u.start+1&&u.endA==u.start&&u.start>h.from&&h.doc.textBetween(u.start-h.from-1,u.start-h.from+1)=="  "&&(u.start--,u.endA--,u.endB--);let m=h.doc.resolveNoCache(u.start-h.from),g=h.doc.resolveNoCache(u.endB-h.from),k=c.resolve(u.start),T=m.sameParent(g)&&m.parent.inlineContent&&k.end()>=u.endA,K;if((it&&r.input.lastIOSEnter>Date.now()-225&&(!T||i.some(b=>b.nodeName=="DIV"||b.nodeName=="P"))||!T&&m.posb(r,De(13,"Enter")))){r.input.lastIOSEnter=0;return}if(r.state.selection.anchor>u.start&&lh(c,u.start,u.endA,m,g)&&r.someProp("handleKeyDown",b=>b(r,De(8,"Backspace")))){he&&B&&r.domObserver.suppressSelectionUpdates();return}B&&u.endB==u.start&&(r.input.lastChromeDelete=Date.now()),he&&!T&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&h.sel&&h.sel.anchor==h.sel.head&&h.sel.head==u.endA&&(u.endB-=2,g=h.doc.resolveNoCache(u.endB-h.from),setTimeout(()=>{r.someProp("handleKeyDown",function(b){return b(r,De(13,"Enter"))})},20));let me=u.start,Te=u.endA,U,bn,Lt;if(T){if(m.pos==g.pos)H&&we<=11&&m.parentOffset==0&&(r.domObserver.suppressSelectionUpdates(),setTimeout(()=>fe(r),20)),U=r.state.tr.delete(me,Te),bn=c.resolve(u.start).marksAcross(c.resolve(u.endA));else if(u.endA==u.endB&&(Lt=oh(m.parent.content.cut(m.parentOffset,g.parentOffset),k.parent.content.cut(k.parentOffset,u.endA-k.start()))))U=r.state.tr,Lt.type=="add"?U.addMark(me,Te,Lt.mark):U.removeMark(me,Te,Lt.mark);else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let b=m.parent.textBetween(m.parentOffset,g.parentOffset);if(r.someProp("handleTextInput",ge=>ge(r,me,Te,b)))return;U=r.state.tr.insertText(b,me,Te)}}if(U||(U=r.state.tr.replace(me,Te,h.doc.slice(u.start-h.from,u.endB-h.from))),h.sel){let b=bi(r,U.doc,h.sel);b&&!(B&&r.composing&&b.empty&&(u.start!=u.endB||r.input.lastChromeDeletee.content.size?null:br(r,e.resolve(t.anchor),e.resolve(t.head))}function oh(r,e){let t=r.firstChild.marks,n=e.firstChild.marks,i=t,s=n,o,l,a;for(let c=0;cc.mark(l.addToSet(c.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=c=>c.mark(l.removeFromSet(c.marks));else return null;let h=[];for(let c=0;ct||vn(o,!0,!1)0&&(e||r.indexAfter(n)==r.node(n).childCount);)n--,i++,e=!1;if(t){let s=r.node(n).maybeChild(r.indexAfter(n));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function ah(r,e,t,n,i){let s=r.findDiffStart(e,t);if(s==null)return null;let{a:o,b:l}=r.findDiffEnd(e,t+r.size,t+e.size);if(i=="end"){let a=Math.max(0,s-Math.min(o,l));n-=o+a-s}if(o=o?s-n:0;s-=a,s&&s=l?s-n:0;s-=a,s&&s=56320&&e<=57343&&t>=55296&&t<=56319}class hh{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Ea,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(Ti),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Oi(this),Ni(this),this.nodeViews=Mi(this),this.docView=ri(this.state.doc,Ci(this),zn(this),this.dom,this),this.domObserver=new Qa(this,(n,i,s,o)=>sh(this,n,i,s,o)),this.domObserver.start(),Da(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&or(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Ti),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let n in this._props)t[n]=this._props[n];t.state=this.state;for(let n in e)t[n]=e[n];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var n;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Zs(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let p=Mi(this);fh(p,this.nodeViews)&&(this.nodeViews=p,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&or(this),this.editable=Oi(this),Ni(this);let a=zn(this),h=Ci(this),c=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",f=s||!this.docView.matchesNode(e.doc,h,a);(f||!e.selection.eq(i.selection))&&(o=!0);let d=c=="preserve"&&o&&this.dom.style.overflowAnchor==null&&ql(this);if(o){this.domObserver.stop();let p=f&&(H||B)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&ch(i.selection,e.selection);if(f){let u=B?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Wa(this)),(s||!this.docView.update(e.doc,h,a,this))&&(this.docView.updateOuterDeco(h),this.docView.destroy(),this.docView=ri(e.doc,h,a,this.dom,this)),u&&!this.trackWrites&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&da(this))?fe(this,p):(Vs(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((n=this.dragging)===null||n===void 0)&&n.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),c=="reset"?this.dom.scrollTop=0:c=="to selection"?this.scrollToSelection():d&&Kl(d)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof x){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&Zr(this,t.getBoundingClientRect(),e)}else Zr(this,this.coordsAtPos(this.state.selection.head,1),e)}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&this.state.doc.nodeAt(s))==n.node&&(i=s)}this.dragging=new _s(e.slice,e.move,i<0?void 0:x.create(this.state.doc,i))}someProp(e,t){let n=this._props&&this._props[e],i;if(n!=null&&(i=t?t(n):n))return i;for(let o=0;ot.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Xl(this,e)}coordsAtPos(e,t=1){return As(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,n=-1){let i=this.docView.posFromDOM(e,t,n);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return ta(this,t||this.state,e)}pasteHTML(e,t){return Rt(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return Rt(this,e,null,!0,t||new ClipboardEvent("paste"))}destroy(){this.docView&&(Aa(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],zn(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Il())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return Ia(this,e)}dispatch(e){let t=this._props.dispatchTransaction;t?t.call(this,e):this.updateState(this.state.apply(e))}domSelectionRange(){let e=this.domSelection();return e?$&&this.root.nodeType===11&&Fl(this.dom.ownerDocument)==this.dom&&eh(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}function Ci(r){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(r.editable),r.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(r.state)),t)for(let n in t)n=="class"?e.class+=" "+t[n]:n=="style"?e.style=(e.style?e.style+";":"")+t[n]:!e[n]&&n!="contenteditable"&&n!="nodeName"&&(e[n]=String(t[n]))}),e.translate||(e.translate="no"),[Q.node(0,r.state.doc.content.size,e)]}function Ni(r){if(r.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),r.cursorWrapper={dom:e,deco:Q.widget(r.state.selection.from,e,{raw:!0,marks:r.markCursor})}}else r.cursorWrapper=null}function Oi(r){return!r.someProp("editable",e=>e(r.state)===!1)}function ch(r,e){let t=Math.min(r.$anchor.sharedDepth(r.head),e.$anchor.sharedDepth(e.head));return r.$anchor.start(t)!=e.$anchor.start(t)}function Mi(r){let e=Object.create(null);function t(n){for(let i in n)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=n[i])}return r.someProp("nodeViews",t),r.someProp("markViews",t),e}function fh(r,e){let t=0,n=0;for(let i in r){if(r[i]!=e[i])return!0;t++}for(let i in e)n++;return t!=n}function Ti(r){if(r.spec.state||r.spec.filterTransaction||r.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var Oe={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},fn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},uh=typeof navigator<"u"&&/Mac/.test(navigator.platform),dh=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var v=0;v<10;v++)Oe[48+v]=Oe[96+v]=String(v);for(var v=1;v<=24;v++)Oe[v+111]="F"+v;for(var v=65;v<=90;v++)Oe[v]=String.fromCharCode(v+32),fn[v]=String.fromCharCode(v);for(var Pn in Oe)fn.hasOwnProperty(Pn)||(fn[Pn]=Oe[Pn]);function ph(r){var e=uh&&r.metaKey&&r.shiftKey&&!r.ctrlKey&&!r.altKey||dh&&r.shiftKey&&r.key&&r.key.length==1||r.key=="Unidentified",t=!e&&r.key||(r.shiftKey?fn:Oe)[r.keyCode]||r.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function io(r,e,t){for(let n=0;;n++){if(n==r.childCount||n==e.childCount)return r.childCount==e.childCount?null:t;let i=r.child(n),s=e.child(n);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)t++;return t}if(i.content.size||s.content.size){let o=io(i.content,s.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function so(r,e,t,n){for(let i=r.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:t,b:n};let o=r.child(--i),l=e.child(--s),a=o.nodeSize;if(o==l){t-=a,n-=a;continue}if(!o.sameMarkup(l))return{a:t,b:n};if(o.isText&&o.text!=l.text){let h=0,c=Math.min(o.text.length,l.text.length);for(;he&&n(a,i+l,s||null,o)!==!1&&a.content.size){let c=l+1;a.nodesBetween(Math.max(0,e-c),Math.min(a.content.size,t-c),n,i+c)}l=h}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let h=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&h||l.isTextblock)&&n&&(o?o=!1:s+=n),s+=h},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,n=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(n)&&(i[i.length-1]=t.withText(t.text+n.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),n.push(l),i+=l.nodeSize),o=a}return new O(n,i)}cutByIndex(e,t){return e==t?O.empty:e==0&&t==this.content.length?this:new O(this.content.slice(e,t))}replaceChild(e,t){let n=this.content[e];if(n==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-n.nodeSize;return i[e]=t,new O(i,s)}addToStart(e){return new O([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new O(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,i=0;;n++){let s=this.child(n),o=i+s.nodeSize;if(o>=e)return o==e||t>0?Kt(n+1,o):Kt(n,i);i=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return O.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return new O(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return O.empty;let t,n=0;for(let i=0;i0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return N.empty;let n=t.openStart||0,i=t.openEnd||0;if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new N(O.fromJSON(e,t.content),n,i)}static maxOpen(e,t=!0){let n=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)n++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new N(e,n,i)}}N.empty=new N(O.empty,0,0);function oo(r,e,t){let{index:n,offset:i}=r.findIndex(e),s=r.maybeChild(n),{index:o,offset:l}=r.findIndex(t);if(i==e||s.isText){if(l!=t&&!r.child(o).isText)throw new RangeError("Removing non-flat range");return r.cut(0,e).append(r.cut(t))}if(n!=o)throw new RangeError("Removing non-flat range");return r.replaceChild(n,s.copy(oo(s.content,e-i-1,t-i-1)))}function lo(r,e,t,n){let{index:i,offset:s}=r.findIndex(e),o=r.maybeChild(i);if(s==e||o.isText)return r.cut(0,e).append(t).append(r.cut(e));let l=lo(o.content,e-s-1,t);return l&&r.replaceChild(i,o.copy(l))}const ao=65535,ho=Math.pow(2,16);function gh(r,e){return r+e*ho}function Ei(r){return r&ao}function yh(r){return(r-(r&ao))/ho}const co=1,fo=2,_t=4,uo=8;class Di{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&uo)>0}get deletedBefore(){return(this.delInfo&(co|_t))>0}get deletedAfter(){return(this.delInfo&(fo|_t))>0}get deletedAcross(){return(this.delInfo&_t)>0}}class G{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&G.empty)return G.empty}recover(e){let t=0,n=Ei(e);if(!this.inverted)for(let i=0;ie)break;let h=this.ranges[l+s],c=this.ranges[l+o],f=a+h;if(e<=f){let d=h?e==a?-1:e==f?1:t:t,p=a+i+(d<0?0:c);if(n)return p;let u=e==(t<0?a:f)?null:gh(l/3,e-a),m=e==a?fo:e==f?co:_t;return(t<0?e!=a:e!=f)&&(m|=uo),new Di(p,m,u)}i+=c-h}return n?e+i:new Di(e+i,0,null)}touches(e,t){let n=0,i=Ei(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let h=this.ranges[l+s],c=a+h;if(e<=c&&l==i*3)return!0;n+=this.ranges[l+o]-h}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let i=0,s=0;i!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return E.fromReplace(e,this.from,this.to,s)}invert(){return new ze(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new Ie(t.pos,n.pos,this.mark)}merge(e){return e instanceof Ie&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ie(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Ie(t.from,t.to,e.markFromJSON(t.mark))}}V.jsonID("addMark",Ie);class ze extends V{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new N(Tr(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return E.fromReplace(e,this.from,this.to,n)}invert(){return new Ie(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),n=e.mapResult(this.to,-1);return t.deleted&&n.deleted||t.pos>=n.pos?null:new ze(t.pos,n.pos,this.mark)}merge(e){return e instanceof ze&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ze(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ze(t.from,t.to,e.markFromJSON(t.mark))}}V.jsonID("removeMark",ze);class ve extends V{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return E.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return E.fromReplace(e,this.pos,this.pos+1,new N(O.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let n=this.mark.addToSet(t.marks);if(n.length==t.marks.length){for(let i=0;in.pos?null:new tt(t.pos,n.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new tt(t.from,t.to,t.gapFrom,t.gapTo,N.fromJSON(e,t.slice),t.insert,!!t.structure)}}V.jsonID("replaceAround",tt);function lr(r,e,t){let n=r.resolve(e),i=t-e,s=n.depth;for(;i>0&&s>0&&n.indexAfter(s)==n.node(s).childCount;)s--,i--;if(i>0){let o=n.node(s).maybeChild(n.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}class Ct extends V{constructor(e,t,n){super(),this.pos=e,this.attr=t,this.value=n}apply(e){let t=e.nodeAt(this.pos);if(!t)return E.fail("No node at attribute step's position");let n=Object.create(null);for(let s in t.attrs)n[s]=t.attrs[s];n[this.attr]=this.value;let i=t.type.create(n,null,t.marks);return E.fromReplace(e,this.pos,this.pos+1,new N(O.from(i),0,t.isLeaf?0:1))}getMap(){return G.empty}invert(e){return new Ct(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Ct(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Ct(t.pos,t.attr,t.value)}}V.jsonID("attr",Ct);class un extends V{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let n=e.type.create(t,e.content,e.marks);return E.ok(n)}getMap(){return G.empty}invert(e){return new un(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new un(t.attr,t.value)}}V.jsonID("docAttr",un);let vt=class extends Error{};vt=function r(e){let t=Error.call(this,e);return t.__proto__=r.prototype,t};vt.prototype=Object.create(Error.prototype);vt.prototype.constructor=vt;vt.prototype.name="TransformError";const Vn=Object.create(null);class A{constructor(e,t,n){this.$anchor=e,this.$head=t,this.ranges=n||[new Sh(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?Ze(e.node(0),e.node(s),e.before(s+1),e.index(s),t,n):Ze(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,n);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new ue(e.node(0))}static atStart(e){return Ze(e,e,0,0,1)||new ue(e)}static atEnd(e){return Ze(e,e,e.content.size,e.childCount,-1)||new ue(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=Vn[t.type];if(!n)throw new RangeError(`No selection type ${t.type} defined`);return n.fromJSON(e,t)}static jsonID(e,t){if(e in Vn)throw new RangeError("Duplicate use of selection JSON ID "+e);return Vn[e]=t,t.prototype.jsonID=e,t}getBookmark(){return ne.between(this.$anchor,this.$head).getBookmark()}}A.prototype.visible=!0;class Sh{constructor(e,t){this.$from=e,this.$to=t}}let Ai=!1;function Ri(r){!Ai&&!r.parent.inlineContent&&(Ai=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+r.parent.type.name+")"))}class ne extends A{constructor(e,t=e){Ri(e),Ri(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let n=e.resolve(t.map(this.head));if(!n.parent.inlineContent)return A.near(n);let i=e.resolve(t.map(this.anchor));return new ne(i.parent.inlineContent?i:n,n)}replace(e,t=N.empty){if(super.replace(e,t),t==N.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof ne&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new kn(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new ne(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,n=t){let i=e.resolve(t);return new this(i,n==t?i:e.resolve(n))}static between(e,t,n){let i=e.pos-t.pos;if((!n||i)&&(n=i>=0?1:-1),!t.parent.inlineContent){let s=A.findFrom(t,n,!0)||A.findFrom(t,-n,!0);if(s)t=s.$head;else return A.near(t,n)}return e.parent.inlineContent||(i==0?e=t:(e=(A.findFrom(e,-n,!0)||A.findFrom(e,n,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&_.isSelectable(l))return _.create(r,t-(i<0?l.nodeSize:0))}else{let a=Ze(r,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ii(r,e,t){let n=r.steps.length-1;if(n{o==null&&(o=c)}),r.setSelection(A.near(r.doc.resolve(o),t))}function zi(r,e){return!e||!r?r:r.bind(e)}class Ht{constructor(e,t,n){this.name=e,this.init=zi(t.init,n),this.apply=zi(t.apply,n)}}new Ht("doc",{init(r){return r.doc||r.schema.topNodeType.createAndFill()},apply(r){return r.doc}}),new Ht("selection",{init(r,e){return r.selection||A.atStart(e.doc)},apply(r){return r.selection}}),new Ht("storedMarks",{init(r){return r.storedMarks||null},apply(r,e,t,n){return n.selection.$cursor?r.storedMarks:null}}),new Ht("scrollToSelection",{init(){return 0},apply(r,e){return r.scrolledIntoView?e+1:e}});function po(r,e,t){for(let n in r){let i=r[n];i instanceof Function?i=i.bind(e):n=="handleDOMEvents"&&(i=po(i,e,{})),t[n]=i}return t}class xh{constructor(e){this.spec=e,this.props={},e.props&&po(e.props,this,this.props),this.key=e.key?e.key.key:bh("plugin")}getState(e){return e[this.key]}}const Ln=Object.create(null);function bh(r){return r in Ln?r+"$"+ ++Ln[r]:(Ln[r]=0,r+"$")}const wh=typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):!1;function Ch(r){let e=r.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let n,i,s,o;for(let l=0;l127)&&(s=Oe[n.keyCode])&&s!=i){let l=e[Jn(s,n)];if(l&&l(t.state,t.dispatch,t))return!0}}return!1}}const mo=(r,e)=>r.selection.empty?!1:(e&&e(r.tr.deleteSelection().scrollIntoView()),!0);function Mh(r,e){let{$cursor:t}=r.selection;return!t||(e?!e.endOfTextblock("backward",r):t.parentOffset>0)?null:t}const Th=(r,e,t)=>{let n=Mh(r,t);if(!n)return!1;let i=go(n);if(!i){let o=n.blockRange(),l=o&&mr(o);return l==null?!1:(e&&e(r.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(So(r,i,e,-1))return!0;if(n.parent.content.size==0&&(st(s,"end")||x.isSelectable(s)))for(let o=n.depth;;o--){let l=gr(r.doc,n.before(o),n.after(o),S.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==n.depth-1?(e&&e(r.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1};function st(r,e,t=!1){for(let n=r;n;n=e=="start"?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(t&&n.childCount!=1)return!1}return!1}const Eh=(r,e,t)=>{let{$head:n,empty:i}=r.selection,s=n;if(!i)return!1;if(n.parent.isTextblock){if(t?!t.endOfTextblock("backward",r):n.parentOffset>0)return!1;s=go(n)}let o=s&&s.nodeBefore;return!o||!x.isSelectable(o)?!1:(e&&e(r.tr.setSelection(x.create(r.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function go(r){if(!r.parent.type.spec.isolating)for(let e=r.depth-1;e>=0;e--){if(r.index(e)>0)return r.doc.resolve(r.before(e+1));if(r.node(e).type.spec.isolating)break}return null}function Dh(r,e){let{$cursor:t}=r.selection;return!t||(e?!e.endOfTextblock("forward",r):t.parentOffset{let n=Dh(r,t);if(!n)return!1;let i=yo(n);if(!i)return!1;let s=i.nodeAfter;if(So(r,i,e,1))return!0;if(n.parent.content.size==0&&(st(s,"start")||x.isSelectable(s))){let o=gr(r.doc,n.before(),n.after(),S.empty);if(o&&o.slice.size{let{$head:n,empty:i}=r.selection,s=n;if(!i)return!1;if(n.parent.isTextblock){if(t?!t.endOfTextblock("forward",r):n.parentOffset=0;e--){let t=r.node(e);if(r.index(e)+1{let{$head:t,$anchor:n}=r.selection;return!t.parent.type.spec.code||!t.sameParent(n)?!1:(e&&e(r.tr.insertText(` +`).scrollIntoView()),!0)};function Dr(r){for(let e=0;e{let{$head:t,$anchor:n}=r.selection;if(!t.parent.type.spec.code||!t.sameParent(n))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Dr(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=r.tr.replaceWith(l,l,o.createAndFill());a.setSelection(w.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},vh=(r,e)=>{let t=r.selection,{$from:n,$to:i}=t;if(t instanceof ce||n.parent.inlineContent||i.parent.inlineContent)return!1;let s=Dr(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!n.parentOffset&&i.index(){let{$cursor:t}=r.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(Xt(r.doc,s))return e&&e(r.tr.split(s).scrollIntoView()),!0}let n=t.blockRange(),i=n&&mr(n);return i==null?!1:(e&&e(r.tr.lift(n,i).scrollIntoView()),!0)};function Bh(r){return(e,t)=>{let{$from:n,$to:i}=e.selection;if(e.selection instanceof x&&e.selection.node.isBlock)return!n.parentOffset||!Xt(e.doc,n.pos)?!1:(t&&t(e.tr.split(n.pos).scrollIntoView()),!0);if(!n.depth)return!1;let s=[],o,l,a=!1,h=!1;for(let p=n.depth;;p--)if(n.node(p).isBlock){a=n.end(p)==n.pos+(n.depth-p),h=n.start(p)==n.pos-(n.depth-p),l=Dr(n.node(p-1).contentMatchAt(n.indexAfter(p-1))),s.unshift(a&&l?{type:l}:null),o=p;break}else{if(p==1)return!1;s.unshift(null)}let c=e.tr;(e.selection instanceof M||e.selection instanceof ce)&&c.deleteSelection();let f=c.mapping.map(n.pos),d=Xt(c.doc,f,s.length,s);if(d||(s[0]=l?{type:l}:null,d=Xt(c.doc,f,s.length,s)),c.split(f,s.length,s),!a&&h&&n.node(o).type!=l){let p=c.mapping.map(n.before(o)),u=c.doc.resolve(p);l&&n.node(o-1).canReplaceWith(u.index(),u.index()+1,l)&&c.setNodeMarkup(c.mapping.map(n.before(o)),l)}return t&&t(c.scrollIntoView()),!0}}const Fh=Bh(),Vh=(r,e)=>(e&&e(r.tr.setSelection(new ce(r.doc))),!0);function Lh(r,e,t){let n=e.nodeBefore,i=e.nodeAfter,s=e.index();return!n||!i||!n.type.compatibleContent(i.type)?!1:!n.content.size&&e.parent.canReplace(s-1,s)?(t&&t(r.tr.delete(e.pos-n.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||us(r.doc,e.pos))?!1:(t&&t(r.tr.join(e.pos).scrollIntoView()),!0)}function So(r,e,t,n){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&Lh(r,e,t))return!0;let h=!a&&e.parent.canReplace(e.index(),e.index()+1);if(h&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let p=e.pos+s.nodeSize,u=y.empty;for(let k=o.length-1;k>=0;k--)u=y.from(o[k].create(null,u));u=y.from(i.copy(u));let m=r.tr.step(new pe(e.pos-1,p,e.pos,p,new S(u,1,0),o.length,!0)),g=m.doc.resolve(p+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&us(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let c=s.type.spec.isolating||n>0&&a?null:w.findFrom(e,1),f=c&&c.$from.blockRange(c.$to),d=f&&mr(f);if(d!=null&&d>=e.depth)return t&&t(r.tr.lift(f,d).scrollIntoView()),!0;if(h&&st(s,"start",!0)&&st(i,"end")){let p=i,u=[];for(;u.push(p),!p.isTextblock;)p=p.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,m.content)){if(t){let k=y.empty;for(let K=u.length-1;K>=0;K--)k=y.from(u[K].copy(k));let T=r.tr.step(new pe(e.pos-u.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new S(k,u.length,0),0,!0));t(T.scrollIntoView())}return!0}}return!1}function ko(r){return function(e,t){let n=e.selection,i=r<0?n.$from:n.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(M.create(e.doc,r<0?i.start(s):i.end(s)))),!0):!1}}const Jh=ko(-1),$h=ko(1);function Wh(r,e,t,n){for(let i=0;i{if(l||!n)return!1;l=a.inlineContent&&a.type.allowsMarkType(t)}),l)return!0}return!1}function dn(r,e=null,t){let n=t!==!1;return function(i,s){let{empty:o,$cursor:l,ranges:a}=i.selection;if(o&&!l||!Wh(i.doc,a,r,n))return!1;if(s)if(l)r.isInSet(i.storedMarks||l.marks())?s(i.tr.removeStoredMark(r)):s(i.tr.addStoredMark(r.create(e)));else{let h,c=i.tr;h=!a.some(f=>i.doc.rangeHasMark(f.$from.pos,f.$to.pos,r));for(let f=0;f=t?R.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};R.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};R.prototype.forEach=function(e,t,n){t===void 0&&(t=0),n===void 0&&(n=this.length),t<=n?this.forEachInner(e,t,n,0):this.forEachInvertedInner(e,t,n,0)};R.prototype.map=function(e,t,n){t===void 0&&(t=0),n===void 0&&(n=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,n),i};R.from=function(e){return e instanceof R?e:e&&e.length?new bo(e):R.empty};var bo=function(r){function e(n){r.call(this),this.values=n}r&&(e.__proto__=r),e.prototype=Object.create(r&&r.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=pn)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=pn)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e}(R);R.empty=new bo([]);var Hh=function(r){function e(t,n){r.call(this),this.left=t,this.right=n,this.length=t.length+n.length,this.depth=Math.max(t.depth,n.depth)+1}return r&&(e.__proto__=r),e.prototype=Object.create(r&&r.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(n){return nl&&this.right.forEachInner(n,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(n,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(n,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(n-s,i-s):this.left.slice(n,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(n){var i=this.right.leafAppend(n);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(n){var i=this.left.leafPrepend(n);if(i)return new e(i,this.right)},e.prototype.appendInner=function(n){return this.left.depth>=Math.max(this.right.depth,n.depth)+1?new e(this.left,new e(this.right,n)):new e(this,n)},e}(R);const Uh=500;class Z{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let i,s;t&&(i=this.remapping(n,this.items.length),s=i.maps.length);let o=e.tr,l,a,h=[],c=[];return this.items.forEach((f,d)=>{if(!f.step){i||(i=this.remapping(n,d+1),s=i.maps.length),s--,c.push(f);return}if(i){c.push(new te(f.map));let p=f.step.map(i.slice(s)),u;p&&o.maybeStep(p).doc&&(u=o.mapping.maps[o.mapping.maps.length-1],h.push(new te(u,void 0,void 0,h.length+c.length))),s--,u&&i.appendMap(u,s)}else o.maybeStep(f.step);if(f.selection)return l=i?f.selection.map(i.slice(s)):f.selection,a=new Z(this.items.slice(0,n).append(c.reverse().concat(h)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,n,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let c=0;cYh&&(l=Gh(l,h),o-=h),new Z(l.append(s),o)}remapping(e,t){let n=new _e;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?n.maps.length-i.mirrorOffset:void 0;n.appendMap(i.map,o)},e,t),n}addMaps(e){return this.eventCount==0?this:new Z(this.items.append(e.map(t=>new te(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let n=[],i=Math.max(0,this.items.length-t),s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(d=>{d.selection&&l--},i);let a=t;this.items.forEach(d=>{let p=s.getMirror(--a);if(p==null)return;o=Math.min(o,p);let u=s.maps[p];if(d.step){let m=e.steps[p].invert(e.docs[p]),g=d.selection&&d.selection.map(s.slice(a+1,p));g&&l++,n.push(new te(u,m,g))}else n.push(new te(u))},i);let h=[];for(let d=t;dUh&&(f=f.compress(this.items.length-n.length)),f}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),n=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(n)),h=a&&a.getMap();if(n--,h&&t.appendMap(h,n),a){let c=o.selection&&o.selection.map(t.slice(n));c&&s++;let f=new te(h.invert(),a,c),d,p=i.length-1;(d=i.length&&i[p].merge(f))?i[p]=d:i.push(f)}}else o.map&&n--},this.items.length,0),new Z(R.from(i.reverse()),s)}}Z.empty=new Z(R.empty,0);function Gh(r,e){let t;return r.forEach((n,i)=>{if(n.selection&&e--==0)return t=i,!1}),r.slice(t)}class te{constructor(e,t,n,i){this.map=e,this.step=t,this.selection=n,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new te(t.getMap().invert(),t,this.selection)}}}class ke{constructor(e,t,n,i,s){this.done=e,this.undone=t,this.prevRanges=n,this.prevTime=i,this.prevComposition=s}}const Yh=20;function jh(r,e,t,n){let i=t.getMeta(Je),s;if(i)return i.historyState;t.getMeta(Qh)&&(r=new ke(r.done,r.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return r;if(o&&o.getMeta(Je))return o.getMeta(Je).redo?new ke(r.done.addTransform(t,void 0,n,en(e)),r.undone,Pi(t.mapping.maps),r.prevTime,r.prevComposition):new ke(r.done,r.undone.addTransform(t,void 0,n,en(e)),null,r.prevTime,r.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=r.prevTime==0||!o&&r.prevComposition!=l&&(r.prevTime<(t.time||0)-n.newGroupDelay||!Xh(t,r.prevRanges)),h=o?Wn(r.prevRanges,t.mapping):Pi(t.mapping.maps);return new ke(r.done.addTransform(t,a?e.selection.getBookmark():void 0,n,en(e)),Z.empty,h,t.time,l??r.prevComposition)}else return(s=t.getMeta("rebased"))?new ke(r.done.rebased(t,s),r.undone.rebased(t,s),Wn(r.prevRanges,t.mapping),r.prevTime,r.prevComposition):new ke(r.done.addMaps(t.mapping.maps),r.undone.addMaps(t.mapping.maps),Wn(r.prevRanges,t.mapping),r.prevTime,r.prevComposition)}function Xh(r,e){if(!e)return!1;if(!r.docChanged)return!0;let t=!1;return r.mapping.maps[0].forEach((n,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Pi(r){let e=[];for(let t=r.length-1;t>=0&&e.length==0;t--)r[t].forEach((n,i,s,o)=>e.push(s,o));return e}function Wn(r,e){if(!r)return null;let t=[];for(let n=0;n{let i=Je.getState(t);if(!i||(r?i.undone:i.done).eventCount==0)return!1;if(n){let s=Zh(i,t,r);s&&n(e?s.scrollIntoView():s)}return!0}}const Co=wo(!1,!0),No=wo(!0,!0);function nt(){var r=arguments[0];typeof r=="string"&&(r=document.createElement(r));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var i=t[n];typeof i=="string"?r.setAttribute(n,i):i!=null&&(r[n]=i)}e++}for(;e{s.preventDefault(),n.classList.contains(Ot+"-disabled")||t.run(e.state,e.dispatch,e,s)});function i(s){if(t.select){let l=t.select(s);if(n.style.display=l?"":"none",!l)return!1}let o=!0;if(t.enable&&(o=t.enable(s)||!1,Li(n,Ot+"-disabled",!o)),t.active){let l=o&&t.active(s)||!1;Li(n,Ot+"-active",l)}return!0}return{dom:n,update:i}}}function Vi(r,e){return r._props.translate?r._props.translate(e):e}function ic(r,e){return t=>{let n=!1;for(let i=0;i"u")return!1;let r=navigator.userAgent;return!/Edge\/\d/.test(r)&&/AppleWebKit/.test(r)&&/Mobile\/\w+/.test(r)}function ac(r){return new yr({view(e){return new hc(e,r)}})}class hc{constructor(e,t){this.editorView=e,this.options=t,this.spacer=null,this.maxHeight=0,this.widthForMaxHeight=0,this.floating=!1,this.scrollHandler=null,this.wrapper=nt("div",{class:Ut+"-wrapper"}),this.menu=this.wrapper.appendChild(nt("div",{class:Ut})),this.menu.className=Ut,e.dom.parentNode&&e.dom.parentNode.replaceChild(this.wrapper,e.dom),this.wrapper.appendChild(e.dom);let{dom:n,update:i}=sc(this.editorView,this.options.content);if(this.contentUpdate=i,this.menu.appendChild(n),this.update(),t.floating&&!lc()){this.updateFloat();let s=uc(this.wrapper);this.scrollHandler=o=>{let l=this.editorView.root;(l.body||l).contains(this.wrapper)?this.updateFloat(o.target.getBoundingClientRect?o.target:void 0):s.forEach(a=>a.removeEventListener("scroll",this.scrollHandler))},s.forEach(o=>o.addEventListener("scroll",this.scrollHandler))}}update(){this.contentUpdate(this.editorView.state),this.floating?this.updateScrollCursor():(this.menu.offsetWidth!=this.widthForMaxHeight&&(this.widthForMaxHeight=this.menu.offsetWidth,this.maxHeight=0),this.menu.offsetHeight>this.maxHeight&&(this.maxHeight=this.menu.offsetHeight,this.menu.style.minHeight=this.maxHeight+"px"))}updateScrollCursor(){let e=this.editorView.root.getSelection();if(!e.focusNode)return;let t=e.getRangeAt(0).getClientRects(),n=t[cc(e)?0:t.length-1];if(!n)return;let i=this.menu.getBoundingClientRect();if(n.topi.top){let s=fc(this.wrapper);s&&(s.scrollTop-=i.bottom-n.top)}}updateFloat(e){let t=this.wrapper,n=t.getBoundingClientRect(),i=e?Math.max(0,e.getBoundingClientRect().top):0;if(this.floating)if(n.top>=i||n.bottom(this.editorView.dom.ownerDocument.defaultView||window).innerHeight?"none":"",e&&(this.menu.style.top=i+"px")}else if(n.top=this.menu.offsetHeight+10){this.floating=!0;let s=this.menu.getBoundingClientRect();this.menu.style.left=s.left+"px",this.menu.style.width=s.width+"px",e&&(this.menu.style.top=i+"px"),this.menu.style.position="fixed",this.spacer=nt("div",{class:Ut+"-spacer",style:`height: ${s.height}px`}),t.insertBefore(this.spacer,this.menu)}}destroy(){this.wrapper.parentNode&&this.wrapper.parentNode.replaceChild(this.editorView.dom,this.wrapper)}}function cc(r){return r.anchorNode==r.focusNode?r.anchorOffset>r.focusOffset:r.anchorNode.compareDocumentPosition(r.focusNode)==Node.DOCUMENT_POSITION_FOLLOWING}function fc(r){for(let e=r.parentNode;e;e=e.parentNode)if(e.scrollHeight>e.clientHeight)return e}function uc(r){let e=[r.ownerDocument.defaultView||window];for(let t=r.parentNode;t;t=t.parentNode)e.push(t);return e}const dc=new Sr("menuPlugin");function pc(r){const e=new Fi({title:"Bold",run:dn(r.marks.bold),active:i=>i.selection.$head.marks().some(s=>s.type===r.marks.bold)}),t=new Fi({title:"Italic",run:dn(r.marks.italic),active:i=>i.selection.$head.marks().some(s=>s.type===r.marks.italic)});return ac({content:[[e,t]],floating:!0}),console.log("Creating menu plugin"),new yr({key:dc})}var mc=Object.defineProperty,gc=Object.getOwnPropertyDescriptor,xn=(r,e,t,n)=>{for(var i=n>1?void 0:n?gc(e,t):e,s=r.length-1,o;s>=0;s--)(o=r[s])&&(i=(n?o(e,t,i):o(i))||i);return n&&i&&mc(e,t,i),i};const ot=new Xo({nodes:{text:{group:"inline"},star:{inline:!0,group:"inline",toDOM(){return["star","⭐"]},parseDOM:[{tag:"star"}]},paragraph:{group:"block",content:"inline*",toDOM(){return["p",0]},parseDOM:[{tag:"p"}]},boring_paragraph:{group:"block",content:"text*",marks:"",toDOM(){return["p",{class:"boring"},0]},parseDOM:[{tag:"p.boring",priority:60}]},doc:{content:"block+"}},marks:{shouting:{toDOM(){return["shouting",0]},parseDOM:[{tag:"shouting"}]},link:{attrs:{href:{}},toDOM(r){return["a",{href:r.attrs.href},0]},parseDOM:[{tag:"a",getAttrs(r){return{href:r}}}],inclusive:!1}}}),yc=pc(ot);function Sc(r,e){const t=ot.nodes.star,{$from:n}=r.selection;return n.parent.canReplaceWith(n.index(),n.index(),t)?(e&&e(r.tr.replaceSelectionWith(t.create())),!0):!1}function kc(r,e){let{doc:t,selection:n}=r;if(n.empty)return!1;let i=null;return!t.rangeHasMark(n.from,n.to,ot.marks.link)&&(i={href:prompt("Link to where?","")},!i.href)?!1:dn(ot.marks.link,i)(r,e)}const xc=ar({"Ctrl-Space":Sc,"Ctrl-b":(r,e)=>(console.log("Ctrl-b pressed, toggling shouting mark..."),dn(ot.marks.shouting)(r,e)),"Ctrl-q":(r,e)=>(console.log("you should have just gotten an alert"),kc(r,e))});let lt=class extends To{constructor(){super(...arguments),this.placeholder="Compose your note..."}async firstUpdated(){console.log("Welcome to the compose page"),await this.updateComplete,this.initializeEditor()}initializeEditor(){if(!this.editorContainer){console.error("Editor container not here");return}const r=ot.nodes.doc.createAndFill();if(!r){console.error("failed to create initial document");return}const e=Qe.create({doc:r,plugins:[yc,_h(),ar({"Mod-z":Co,"Mod-y":No}),ar(Kh),xc]});let t=new hh(this.editorContainer,{state:e,dispatchTransaction(n){console.log("Document size went from",n.before.content.size,"to",n.doc.content.size);let i=t.state.apply(n);t.updateState(i)}});this.editorView=t,console.log(e.plugins),console.log("editor initialized")}disconnectedCallback(){super.disconnectedCallback(),this.editorView&&(this.editorView.destroy(),this.editorView=null)}render(){return Eo` + + +
    +
    + + +
    +

    Editor Demo

    +
    + + + +

    Instructions

    +

    Click inside the white text area to highlight with your cursor. + You can type and press enter to insert a new block below.

    +
    +

    Try to highlight a piece of text, then CTRL+X to cut and + CTRL+V to paste.


    +

    Press Ctrl+Space to add a yellow star to the document.

    +

    Press Ctrl+B over a highlighted selection to add a "shouting" + mark and format it all caps and red.

    + +
    + +
    +
    +
    + `}};lt.styles=[Do,Ao` + :host { + display: block; + } + + shouting { + all: unset; /* Remove inherited or conflicting styles */ + font-weight: bold; + text-transform: uppercase; + color: red; /* Add a visible color for debugging */ +} + + `];xn([Ji({type:String})],lt.prototype,"placeholder",2);xn([Ji({type:String})],lt.prototype,"value",2);xn([Ro("#editor")],lt.prototype,"editorContainer",2);lt=xn([Io("app-write")],lt);export{lt as AppWrite,ot as customSchema}; +//# sourceMappingURL=app-write-DLE2Mxxa.js.map diff --git a/dist2/code/app-write-DLE2Mxxa.js.map b/dist2/code/app-write-DLE2Mxxa.js.map new file mode 100644 index 0000000..74161d4 --- /dev/null +++ b/dist2/code/app-write-DLE2Mxxa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"app-write-DLE2Mxxa.js","sources":["../../node_modules/orderedmap/dist/index.js","../../node_modules/prosemirror-model/dist/index.js","../../node_modules/prosemirror-transform/dist/index.js","../../node_modules/prosemirror-state/dist/index.js","../../node_modules/prosemirror-view/dist/index.js","../../../node_modules/w3c-keyname/index.js","../../../node_modules/prosemirror-model/dist/index.js","../../../node_modules/prosemirror-transform/dist/index.js","../../../node_modules/prosemirror-state/dist/index.js","../../../node_modules/prosemirror-keymap/dist/index.js","../../node_modules/prosemirror-commands/dist/index.js","../../node_modules/rope-sequence/dist/index.js","../../node_modules/prosemirror-history/dist/index.js","../../node_modules/crelt/index.js","../../node_modules/prosemirror-menu/dist/index.js","../../src/components/menu-plugin.ts","../../src/pages/app-write/app-write.ts"],"sourcesContent":["// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n this.content = content;\n}\n\nOrderedMap.prototype = {\n constructor: OrderedMap,\n\n find: function(key) {\n for (var i = 0; i < this.content.length; i += 2)\n if (this.content[i] === key) return i\n return -1\n },\n\n // :: (string) → ?any\n // Retrieve the value stored under `key`, or return undefined when\n // no such key exists.\n get: function(key) {\n var found = this.find(key);\n return found == -1 ? undefined : this.content[found + 1]\n },\n\n // :: (string, any, ?string) → OrderedMap\n // Create a new map by replacing the value of `key` with a new\n // value, or adding a binding to the end of the map. If `newKey` is\n // given, the key of the binding will be replaced with that key.\n update: function(key, value, newKey) {\n var self = newKey && newKey != key ? this.remove(newKey) : this;\n var found = self.find(key), content = self.content.slice();\n if (found == -1) {\n content.push(newKey || key, value);\n } else {\n content[found + 1] = value;\n if (newKey) content[found] = newKey;\n }\n return new OrderedMap(content)\n },\n\n // :: (string) → OrderedMap\n // Return a map with the given key removed, if it existed.\n remove: function(key) {\n var found = this.find(key);\n if (found == -1) return this\n var content = this.content.slice();\n content.splice(found, 2);\n return new OrderedMap(content)\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the start of the map.\n addToStart: function(key, value) {\n return new OrderedMap([key, value].concat(this.remove(key).content))\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the end of the map.\n addToEnd: function(key, value) {\n var content = this.remove(key).content.slice();\n content.push(key, value);\n return new OrderedMap(content)\n },\n\n // :: (string, string, any) → OrderedMap\n // Add a key after the given key. If `place` is not found, the new\n // key is added to the end.\n addBefore: function(place, key, value) {\n var without = this.remove(key), content = without.content.slice();\n var found = without.find(place);\n content.splice(found == -1 ? content.length : found, 0, key, value);\n return new OrderedMap(content)\n },\n\n // :: ((key: string, value: any))\n // Call the given function for each key/value pair in the map, in\n // order.\n forEach: function(f) {\n for (var i = 0; i < this.content.length; i += 2)\n f(this.content[i], this.content[i + 1]);\n },\n\n // :: (union) → OrderedMap\n // Create a new map by prepending the keys in this map that don't\n // appear in `map` before the keys in `map`.\n prepend: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(map.content.concat(this.subtract(map).content))\n },\n\n // :: (union) → OrderedMap\n // Create a new map by appending the keys in this map that don't\n // appear in `map` after the keys in `map`.\n append: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(this.subtract(map).content.concat(map.content))\n },\n\n // :: (union) → OrderedMap\n // Create a map containing all the keys in this map that don't\n // appear in `map`.\n subtract: function(map) {\n var result = this;\n map = OrderedMap.from(map);\n for (var i = 0; i < map.content.length; i += 2)\n result = result.remove(map.content[i]);\n return result\n },\n\n // :: () → Object\n // Turn ordered map into a plain object.\n toObject: function() {\n var result = {};\n this.forEach(function(key, value) { result[key] = value; });\n return result\n },\n\n // :: number\n // The amount of keys in this map.\n get size() {\n return this.content.length >> 1\n }\n};\n\n// :: (?union) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nexport default OrderedMap;\n","import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n for (let j = 0; childA.text[j] == childB.text[j]; j++)\n pos++;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++;\n posA--;\n posB--;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n else\n child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos, round = -1) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos || round > 0)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return new Fragment(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n type.checkAttrs(mark.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/*\nReplaceError = function(this: any, message: string) {\n let err = Error.call(this, message)\n ;(err as any).__proto__ = ReplaceError.prototype\n return err\n} as any\n\nReplaceError.prototype = Object.create(Error.prototype)\nReplaceError.prototype.constructor = ReplaceError\nReplaceError.prototype.name = \"ReplaceError\"\n*/\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n target[last] = child.withText(target[last].text + child.text);\n else\n target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n node.type.checkContent(content);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n }\n else {\n if (openStart)\n addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd)\n addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--)\n node = $along.node(i).copy(Fragment.from(node));\n return { start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++)\n str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively between\n the given two positions that are relative to start of this\n node's content. The callback is invoked with the node, its\n position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n this.type.checkAttrs(this.attrs);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n mark.type.checkAttrs(mark.attrs);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size)\n obj.content = this.content.toJSON();\n if (this.marks.length)\n obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n node.type.checkAttrs(node.attrs);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n stream.err(\"Mixing inline and block content\");\n return { type: \"name\", value: type };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let given = value && value[name];\n if (given === undefined) {\n let attr = attrs[name];\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n built[name] = given;\n }\n return built;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let name in values)\n if (!(name in attrs))\n throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);\n for (let name in attrs) {\n let attr = attrs[name];\n if (attr.validate)\n attr.validate(values[name]);\n }\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"node\", this.name);\n }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"mark\", this.name);\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\")\n type = this.nodeType(type);\n else if (!(type instanceof NodeType))\n throw new RangeError(\"Invalid node type: \" + type);\n else if (type.schema != this)\n throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n Deserialize a node from its JSON representation. This method is\n bound.\n */\n nodeFromJSON(json) {\n return Node.fromJSON(this, json);\n }\n /**\n Deserialize a mark from its JSON representation. This method is\n bound.\n */\n markFromJSON(json) {\n return Mark.fromJSON(this, json);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match)\n content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n value = value.slice(1);\n }\n }\n else if (preserveWS !== \"full\") {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n else {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n if (value)\n this.insertNode(this.parser.schema.text(value), marks);\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks)) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node, marks) {\n let route, sync;\n for (let depth = this.open; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid)\n break;\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n if (structure.nodeType != null)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType != null)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n throw new RangeError(\"Content hole must be the only child of its parent node\");\n return { dom, contentDOM: dom };\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n","import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(\n /**\n The step maps in this mapping.\n */\n maps = [], \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this.maps, this.mirror, from, to);\n }\n /**\n @internal\n */\n copy() {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null)\n this.setMirror(this.maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this.maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this.maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let removed = [], added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n removing.to = end;\n else\n removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start)\n adding.to = end;\n else\n added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf)\n return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, tr.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or a mark of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n if (!(mark instanceof Mark)) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n mark = mark.isInSet(node.marks);\n if (!mark)\n return this;\n }\n this.step(new RemoveNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split.\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n to = to == null ? from : to;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n","import { TextSelection, NodeSelection, AllSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n};\nconst parentNode = function (node) {\n let parent = node.assignedSlot || node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nconst textRange = function (node, from, to) {\n let range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range;\n};\nconst clearReusedRange = function () {\n reusedRange = null;\n};\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n let parent = node.parentNode;\n if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n node.contentEditable == \"false\")\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (node.nodeType == 1) {\n node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (node.contentEditable == \"false\")\n return false;\n off = dir < 0 ? nodeSize(node) : 0;\n }\n else {\n return false;\n }\n }\n}\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction textNodeBefore$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset)\n return node;\n if (node.nodeType == 1 && offset > 0) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction textNodeAfter$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset < node.nodeValue.length)\n return node;\n if (node.nodeType == 1 && offset < node.childNodes.length) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset];\n offset = 0;\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction isOnEdge(node, offset, parent) {\n for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent)\n return true;\n let index = domIndex(node);\n node = node.parentNode;\n if (!node)\n return false;\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\nfunction hasBlockDesc(dom) {\n let desc;\n for (let cur = dom; cur; cur = cur.parentNode)\n if (desc = cur.pmViewDesc)\n break;\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n if (doc.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n let pos = doc.caretPositionFromPoint(x, y);\n // Clip the offset, because Chrome will return a text offset\n // into nodes, which can't be treated as a regular DOM\n // offset\n if (pos)\n return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n }\n catch (_) { }\n }\n if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range)\n return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n let vp = doc.defaultView && doc.defaultView.visualViewport;\n if (vp)\n return {\n left: 0, right: vp.width,\n top: 0, bottom: vp.height\n };\n return { left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n let rect = node.getBoundingClientRect();\n // Adjust for elements with style \"transform: scale()\"\n let scaleX = (rect.width / node.offsetWidth) || 1;\n let scaleY = (rect.height / node.offsetHeight) || 1;\n // Make sure scrollbar width isn't included in the rectangle\n return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n let doc = view.dom.ownerDocument;\n for (let parent = startDOM || view.dom;; parent = parentNode(parent)) {\n if (!parent)\n break;\n if (parent.nodeType != 1)\n continue;\n let elt = parent;\n let atTop = elt == doc.body;\n let bounding = atTop ? windowRect(doc) : clientRect(elt);\n let moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n }\n else {\n let startX = elt.scrollLeft, startY = elt.scrollTop;\n if (moveY)\n elt.scrollTop += moveY;\n if (moveX)\n elt.scrollLeft += moveX;\n let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;\n rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n }\n }\n if (atTop || /^(fixed|sticky)$/.test(getComputedStyle(parent).position))\n break;\n }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n let refDOM, refTop;\n for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n let dom = view.root.elementFromPoint(x, y);\n if (!dom || dom == view.dom || !view.dom.contains(dom))\n continue;\n let localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break;\n }\n }\n return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n let stack = [], doc = dom.ownerDocument;\n for (let cur = dom; cur; cur = parentNode(cur)) {\n stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n if (dom == doc)\n break;\n }\n return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n for (let i = 0; i < stack.length; i++) {\n let { dom, top, left } = stack[i];\n if (dom.scrollTop != top + dTop)\n dom.scrollTop = top + dTop;\n if (dom.scrollLeft != left)\n dom.scrollLeft = left;\n }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = { preventScroll: true };\n return true;\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\nfunction findOffsetInNode(node, coords) {\n let closest, dxClosest = 2e8, coordsClosest, offset = 0;\n let rowBot = coords.top, rowTop = coords.top;\n let firstBelow, coordsBelow;\n for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n let rects;\n if (child.nodeType == 1)\n rects = child.getClientRects();\n else if (child.nodeType == 3)\n rects = textRange(child).getClientRects();\n else\n continue;\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n let dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && closest.nodeType == 3 ? {\n left: rect.right < coords.left ? rect.right : rect.left,\n top: coords.top\n } : coords;\n if (child.nodeType == 1 && dx)\n offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n continue;\n }\n }\n else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n firstBelow = child;\n coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n offset = childIndex + 1;\n }\n }\n if (!closest && firstBelow) {\n closest = firstBelow;\n coordsClosest = coordsBelow;\n dxClosest = 0;\n }\n if (closest && closest.nodeType == 3)\n return findOffsetInText(closest, coordsClosest);\n if (!closest || (dxClosest && closest.nodeType == 1))\n return { node, offset };\n return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n let len = node.nodeValue.length;\n let range = document.createRange();\n for (let i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n let rect = singleRect(range, 1);\n if (rect.top == rect.bottom)\n continue;\n if (inRect(coords, rect))\n return { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n }\n return { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n let parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n return parent;\n return dom;\n}\nfunction posFromElement(view, elt, coords) {\n let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n if (node.nodeType == 1 && !node.firstChild) {\n let rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias);\n}\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n let outsideBlock = -1;\n for (let cur = node, sawBlock = false;;) {\n if (cur == view.dom)\n break;\n let desc = view.docView.nearestDesc(cur, true), rect;\n if (!desc)\n return null;\n if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n // Ignore elements with zero-size bounding rectangles\n ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n if (desc.node.isBlock && desc.parent) {\n // Only apply the horizontal test to the innermost block. Vertical for any parent.\n if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n outsideBlock = desc.posBefore;\n else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n outsideBlock = desc.posAfter;\n sawBlock = true;\n }\n if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n // If we are inside a leaf, return the side of the leaf closer to the coords\n let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n : coords.left < (rect.left + rect.right) / 2;\n return before ? desc.posBefore : desc.posAfter;\n }\n }\n cur = desc.dom.parentNode;\n }\n return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n let len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n let child = element.childNodes[i];\n if (child.nodeType == 1) {\n let rects = child.getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (inRect(coords, rect))\n return elementFromPoint(child, coords, rect);\n }\n }\n if ((i = (i + 1) % len) == startI)\n break;\n }\n }\n return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n let doc = view.dom.ownerDocument, node, offset = 0;\n let caret = caretFromPoint(doc, coords.left, coords.top);\n if (caret)\n ({ node, offset } = caret);\n let elt = (view.root.elementFromPoint ? view.root : doc)\n .elementFromPoint(coords.left, coords.top);\n let pos;\n if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {\n let box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box))\n return null;\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt)\n return null;\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (safari) {\n for (let p = elt; node && p; p = parentNode(p))\n if (p.draggable)\n node = undefined;\n }\n elt = targetKludge(elt, coords);\n if (node) {\n if (gecko && node.nodeType == 1) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n let next = node.childNodes[offset], box;\n if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n box.bottom > coords.top)\n offset++;\n }\n }\n let prev;\n // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 &&\n prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n offset--;\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n pos = view.state.doc.content.size;\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != \"BR\")\n pos = posFromCaret(view, node, offset, coords);\n }\n if (pos == null)\n pos = posFromElement(view, elt, coords);\n let desc = view.docView.nearestDesc(elt, true);\n return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n let rects = target.getClientRects();\n if (rects.length) {\n let first = rects[bias < 0 ? 0 : rects.length - 1];\n if (nonZero(first))\n return first;\n }\n return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n let supportEmptyRange = webkit || gecko;\n if (node.nodeType == 3) {\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context or when at the end of a node.\n if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n let rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n }\n }\n return rect;\n }\n else {\n let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n if (side < 0 && !offset) {\n to++;\n takeSide = -1;\n }\n else if (side >= 0 && offset == node.nodeValue.length) {\n from--;\n takeSide = 1;\n }\n else if (side < 0) {\n from--;\n }\n else {\n to++;\n }\n return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n }\n }\n let $dom = view.state.doc.resolve(pos - (atom || 0));\n // Return a horizontal line in block context\n if (!$dom.parent.inlineContent) {\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n if (before.nodeType == 1)\n return flattenH(before.getBoundingClientRect(), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n if (after.nodeType == 1)\n return flattenH(after.getBoundingClientRect(), true);\n }\n return flattenH(node.getBoundingClientRect(), side >= 0);\n }\n // Inline, not in text node (this is not Bidi-safe)\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them.\n // Only use them if they are the last element in their parent\n : before.nodeType == 1 && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n if (target)\n return flattenV(singleRect(target, 1), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n after = after.nextSibling;\n let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n : after.nodeType == 1 ? after : null;\n if (target)\n return flattenV(singleRect(target, -1), true);\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n if (rect.width == 0)\n return rect;\n let x = left ? rect.left : rect.right;\n return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n if (rect.height == 0)\n return rect;\n let y = top ? rect.top : rect.bottom;\n return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n let viewState = view.state, active = view.root.activeElement;\n if (viewState != state)\n view.updateState(state);\n if (active != view.dom)\n view.focus();\n try {\n return f();\n }\n finally {\n if (viewState != state)\n view.updateState(viewState);\n if (active != view.dom && active)\n active.focus();\n }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n let sel = state.selection;\n let $pos = dir == \"up\" ? sel.$from : sel.$to;\n return withFlushedState(view, state, () => {\n let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n for (;;) {\n let nearest = view.docView.nearestDesc(dom, true);\n if (!nearest)\n break;\n if (nearest.node.isBlock) {\n dom = nearest.contentDOM || nearest.dom;\n break;\n }\n dom = nearest.dom.parentNode;\n }\n let coords = coordsAtPos(view, $pos.pos, 1);\n for (let child = dom.firstChild; child; child = child.nextSibling) {\n let boxes;\n if (child.nodeType == 1)\n boxes = child.getClientRects();\n else if (child.nodeType == 3)\n boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n else\n continue;\n for (let i = 0; i < boxes.length; i++) {\n let box = boxes[i];\n if (box.bottom > box.top + 1 &&\n (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n return false;\n }\n }\n return true;\n });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n let { $head } = state.selection;\n if (!$head.parent.isTextblock)\n return false;\n let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n let sel = view.domSelection();\n if (!sel)\n return $head.pos == $head.start() || $head.pos == $head.end();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n return withFlushedState(view, state, () => {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n ;\n sel.modify(\"move\", dir, \"character\");\n let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) ||\n (oldNode == newNode && oldOff == newOff);\n // Restore the previous selection\n try {\n sel.collapse(anchorNode, anchorOffset);\n if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n sel.extend(oldNode, oldOff);\n }\n catch (_) { }\n if (oldBidiLevel != null)\n sel.caretBidiLevel = oldBidiLevel;\n return result;\n });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir)\n return cachedResult;\n cachedState = state;\n cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir);\n}\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n constructor(parent, children, dom, \n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n }\n // Used to check whether a given description corresponds to a\n // widget/mark/node.\n matchesWidget(widget) { return false; }\n matchesMark(mark) { return false; }\n matchesNode(node, outerDeco, innerDeco) { return false; }\n matchesHack(nodeName) { return false; }\n // When parsing in-editor content (in domchange.js), we allow\n // descriptions to determine the parse rules that should be used to\n // parse them.\n parseRule() { return null; }\n // Used by the editor's event handler to ignore events that come\n // from certain descs.\n stopEvent(event) { return false; }\n // The size of the content represented by this desc.\n get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }\n // For block nodes, this represents the space taken up by their\n // start/end tokens.\n get border() { return 0; }\n destroy() {\n this.parent = undefined;\n if (this.dom.pmViewDesc == this)\n this.dom.pmViewDesc = undefined;\n for (let i = 0; i < this.children.length; i++)\n this.children[i].destroy();\n }\n posBeforeChild(child) {\n for (let i = 0, pos = this.posAtStart;; i++) {\n let cur = this.children[i];\n if (cur == child)\n return pos;\n pos += cur.size;\n }\n }\n get posBefore() {\n return this.parent.posBeforeChild(this);\n }\n get posAtStart() {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n }\n get posAfter() {\n return this.posBefore + this.size;\n }\n get posAtEnd() {\n return this.posAtStart + this.size - 2 * this.border;\n }\n localPosFromDOM(dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {\n if (bias < 0) {\n let domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n domBefore = domBefore.previousSibling;\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n }\n else {\n let domAfter, desc;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n domAfter = domAfter.nextSibling;\n return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n let atEnd;\n if (dom == this.dom && this.contentDOM) {\n atEnd = offset > domIndex(this.contentDOM);\n }\n else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;\n }\n else if (this.dom.firstChild) {\n if (offset == 0)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = false;\n break;\n }\n if (search.previousSibling)\n break;\n }\n if (atEnd == null && offset == dom.childNodes.length)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = true;\n break;\n }\n if (search.nextSibling)\n break;\n }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n }\n nearestDesc(dom, onlyNodes = false) {\n for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n let desc = this.getDesc(cur), nodeDOM;\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && (nodeDOM = desc.nodeDOM) &&\n !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))\n first = false;\n else\n return desc;\n }\n }\n }\n getDesc(dom) {\n let desc = dom.pmViewDesc;\n for (let cur = desc; cur; cur = cur.parent)\n if (cur == this)\n return desc;\n }\n posFromDOM(dom, offset, bias) {\n for (let scan = dom; scan; scan = scan.parentNode) {\n let desc = this.getDesc(scan);\n if (desc)\n return desc.localPosFromDOM(dom, offset, bias);\n }\n return -1;\n }\n // Find the desc for the node after the given pos, if any. (When a\n // parent node overrode rendering, there might not be one.)\n descAt(pos) {\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length)\n child = child.children[0];\n return child;\n }\n if (pos < end)\n return child.descAt(pos - offset - child.border);\n offset = end;\n }\n }\n domFromPos(pos, side) {\n if (!this.contentDOM)\n return { node: this.dom, offset: 0, atom: pos + 1 };\n // First find the position in the child array\n let i = 0, offset = 0;\n for (let curPos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = curPos + child.size;\n if (end > pos || child instanceof TrailingHackViewDesc) {\n offset = pos - curPos;\n break;\n }\n curPos = end;\n }\n // If this points into the middle of a child, call through\n if (offset)\n return this.children[i].domFromPos(offset - this.children[i].border, side);\n // Go back if there were any zero-length widgets with side >= 0 before this point\n for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { }\n // Scan towards the first useable node\n if (side <= 0) {\n let prev, enter = true;\n for (;; i--, enter = false) {\n prev = i ? this.children[i - 1] : null;\n if (!prev || prev.dom.parentNode == this.contentDOM)\n break;\n }\n if (prev && side && enter && !prev.border && !prev.domAtom)\n return prev.domFromPos(prev.size, side);\n return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n }\n else {\n let next, enter = true;\n for (;; i++, enter = false) {\n next = i < this.children.length ? this.children[i] : null;\n if (!next || next.dom.parentNode == this.contentDOM)\n break;\n }\n if (next && enter && !next.border && !next.domAtom)\n return next.domFromPos(0, side);\n return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n }\n }\n // Used to find a DOM range in a single parent for a given changed\n // range.\n parseRange(from, to, base = 0) {\n if (this.children.length == 0)\n return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n let fromOffset = -1, toOffset = -1;\n for (let offset = base, i = 0;; i++) {\n let child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n let childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n return child.parseRange(from, to, childBase);\n from = offset;\n for (let j = i; j > 0; j--) {\n let prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break;\n }\n from -= prev.size;\n }\n if (fromOffset == -1)\n fromOffset = 0;\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (let j = i + 1; j < this.children.length; j++) {\n let next = this.children[j];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break;\n }\n to += next.size;\n }\n if (toOffset == -1)\n toOffset = this.contentDOM.childNodes.length;\n break;\n }\n offset = end;\n }\n return { node: this.contentDOM, from, to, fromOffset, toOffset };\n }\n emptyChildAt(side) {\n if (this.border || !this.contentDOM || !this.children.length)\n return false;\n let child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side);\n }\n domAfterPos(pos) {\n let { node, offset } = this.domFromPos(pos, 0);\n if (node.nodeType != 1 || offset == node.childNodes.length)\n throw new RangeError(\"No node after pos \" + pos);\n return node.childNodes[offset];\n }\n // View descs are responsible for setting any selection that falls\n // entirely inside of them, so that custom implementations can do\n // custom things with the selection. Note that this falls apart when\n // a selection starts in such a node and ends in another, in which\n // case we just use whatever domFromPos produces as a best effort.\n setSelection(anchor, head, view, force = false) {\n // If the selection falls entirely in a child, give it to that child\n let from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);\n offset = end;\n }\n let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n let domSel = view.root.getSelection();\n let selRange = view.domSelectionRange();\n let brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((gecko || safari) && anchor == head) {\n let { node, offset } = anchorDOM;\n if (node.nodeType == 3) {\n brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n // Issue #1128\n if (brKludge && offset == node.nodeValue.length) {\n for (let scan = node, after; scan; scan = scan.parentNode) {\n if (after = scan.nextSibling) {\n if (after.nodeName == \"BR\")\n anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n break;\n }\n let desc = scan.pmViewDesc;\n if (desc && desc.node && desc.node.isBlock)\n break;\n }\n }\n }\n else {\n let prev = node.childNodes[offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n }\n // Firefox can act strangely when the selection is in front of an\n // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {\n let after = selRange.focusNode.childNodes[selRange.focusOffset];\n if (after && after.contentEditable == \"false\")\n force = true;\n }\n if (!(force || brKludge && safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n return;\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n let domSelExtended = false;\n if ((domSel.extend || anchor == head) && !brKludge) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head)\n domSel.extend(headDOM.node, headDOM.offset);\n domSelExtended = true;\n }\n catch (_) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n // Similarly, this could crash on Safari if the editor is hidden, and\n // there was no selection.\n }\n }\n if (!domSelExtended) {\n if (anchor > head) {\n let tmp = anchorDOM;\n anchorDOM = headDOM;\n headDOM = tmp;\n }\n let range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n }\n ignoreMutation(mutation) {\n return !this.contentDOM && mutation.type != \"selection\";\n }\n get contentLost() {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n }\n // Remove a subtree of the element tree that has been touched\n // by a DOM change, so that the next update will redraw it.\n markDirty(from, to) {\n for (let offset = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n let startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM))\n child.dirty = NODE_DIRTY;\n else\n child.markDirty(from - startInside, to - startInside);\n return;\n }\n else {\n child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n ? CONTENT_DIRTY : NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n }\n markParentsDirty() {\n let level = 1;\n for (let node = this.parent; node; node = node.parent, level++) {\n let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty)\n node.dirty = dirty;\n }\n }\n get domAtom() { return false; }\n get ignoreForCoords() { return false; }\n isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n constructor(parent, widget, view, pos) {\n let self, dom = widget.type.toDOM;\n if (typeof dom == \"function\")\n dom = dom(view, () => {\n if (!self)\n return pos;\n if (self.parent)\n return self.parent.posBeforeChild(self);\n });\n if (!widget.type.spec.raw) {\n if (dom.nodeType != 1) {\n let wrap = document.createElement(\"span\");\n wrap.appendChild(dom);\n dom = wrap;\n }\n dom.contentEditable = \"false\";\n dom.classList.add(\"ProseMirror-widget\");\n }\n super(parent, [], dom, null);\n this.widget = widget;\n this.widget = widget;\n self = this;\n }\n matchesWidget(widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n }\n parseRule() { return { ignore: true }; }\n stopEvent(event) {\n let stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false;\n }\n ignoreMutation(mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n }\n destroy() {\n this.widget.type.destroy(this.dom);\n super.destroy();\n }\n get domAtom() { return true; }\n get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n constructor(parent, dom, textDOM, text) {\n super(parent, [], dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n get size() { return this.text.length; }\n localPosFromDOM(dom, offset) {\n if (dom != this.textDOM)\n return this.posAtStart + (offset ? this.size : 0);\n return this.posAtStart + offset;\n }\n domFromPos(pos) {\n return { node: this.textDOM, offset: pos };\n }\n ignoreMutation(mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n constructor(parent, mark, dom, contentDOM, spec) {\n super(parent, [], dom, contentDOM);\n this.mark = mark;\n this.spec = spec;\n }\n static create(parent, mark, inline, view) {\n let custom = view.nodeViews[mark.type.name];\n let spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n }\n parseRule() {\n if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n return null;\n return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n }\n matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n markDirty(from, to) {\n super.markDirty(from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n let parent = this.parent;\n while (!parent.node)\n parent = parent.parent;\n if (parent.dirty < this.dirty)\n parent.dirty = this.dirty;\n this.dirty = NOT_DIRTY;\n }\n }\n slice(from, to, view) {\n let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n let nodes = this.children, size = this.size;\n if (to < size)\n nodes = replaceNodes(nodes, to, size, view);\n if (from > 0)\n nodes = replaceNodes(nodes, 0, from, view);\n for (let i = 0; i < nodes.length; i++)\n nodes[i].parent = copy;\n copy.children = nodes;\n return copy;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {\n super(parent, [], dom, contentDOM);\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n this.nodeDOM = nodeDOM;\n }\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finicky\n // implementation details to the user code that they probably will\n // never need.)\n static create(parent, node, outerDeco, innerDeco, view, pos) {\n let custom = view.nodeViews[node.type.name], descObj;\n let spec = custom && custom(node, view, () => {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj)\n return pos;\n if (descObj.parent)\n return descObj.parent.posBeforeChild(descObj);\n }, outerDeco, innerDeco);\n let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom)\n dom = document.createTextNode(node.text);\n else if (dom.nodeType != 3)\n throw new RangeError(\"Text must be rendered as a DOM text node\");\n }\n else if (!dom) {\n let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n ({ dom, contentDOM } = spec);\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
    \n if (!dom.hasAttribute(\"contenteditable\"))\n dom.contentEditable = \"false\";\n if (node.type.spec.draggable)\n dom.draggable = true;\n }\n let nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n if (spec)\n return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);\n else if (node.isText)\n return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);\n else\n return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);\n }\n parseRule() {\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView)\n return null;\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n let rule = { node: this.node.type.name, attrs: this.node.attrs };\n if (this.node.type.whitespace == \"pre\")\n rule.preserveWhitespace = \"full\";\n if (!this.contentDOM) {\n rule.getContent = () => this.node.content;\n }\n else if (!this.contentLost) {\n rule.contentElement = this.contentDOM;\n }\n else {\n // Chrome likes to randomly recreate parent nodes when\n // backspacing things. When that happens, this tries to find the\n // new parent.\n for (let i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i];\n if (this.dom.contains(child.dom.parentNode)) {\n rule.contentElement = child.dom.parentNode;\n break;\n }\n }\n if (!rule.contentElement)\n rule.getContent = () => Fragment.empty;\n }\n return rule;\n }\n matchesNode(node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n }\n get size() { return this.node.nodeSize; }\n get border() { return this.node.isLeaf ? 0 : 1; }\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n updateChildren(view, pos) {\n let inline = this.node.inlineContent, off = pos;\n let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n let localComposition = composition && composition.pos > -1 ? composition : null;\n let compositionInChild = composition && composition.pos < 0;\n let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n if (widget.spec.marks)\n updater.syncToMarks(widget.spec.marks, inline, view);\n else if (widget.type.side >= 0 && !insideNode)\n updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view);\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, (child, outerDeco, innerDeco, i) => {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view);\n // Try several strategies for drawing this node\n let compIndex;\n if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n else if (compositionInChild && view.state.selection.from > off &&\n view.state.selection.to < off + child.nodeSize &&\n (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n else {\n // Add it as a new view\n updater.addNode(child, outerDeco, innerDeco, view, off);\n }\n off += child.nodeSize;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks([], inline, view);\n if (this.node.isTextblock)\n updater.addTextblockHacks();\n updater.destroyRest();\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (localComposition)\n this.protectLocalComposition(view, localComposition);\n renderDescs(this.contentDOM, this.children, view);\n if (ios)\n iosHacks(this.dom);\n }\n }\n localCompositionInfo(view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node\n let { from, to } = view.state.selection;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n return null;\n let textNode = view.input.compositionNode;\n if (!textNode || !this.dom.contains(textNode.parentNode))\n return null;\n if (this.node.inlineContent) {\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n let text = textNode.nodeValue;\n let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n }\n else {\n return { node: textNode, pos: -1, text: \"\" };\n }\n }\n protectLocalComposition(view, { node, pos, text }) {\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node))\n return;\n // Create a composition view for the orphaned nodes\n let topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM)\n break;\n while (topNode.previousSibling)\n topNode.parentNode.removeChild(topNode.previousSibling);\n while (topNode.nextSibling)\n topNode.parentNode.removeChild(topNode.nextSibling);\n if (topNode.pmViewDesc)\n topNode.pmViewDesc = undefined;\n }\n let desc = new CompositionViewDesc(this, topNode, node, text);\n view.input.compositionNodes.push(desc);\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n }\n // If this desc must be updated to match the given node decoration,\n // do so and return true.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node))\n return false;\n this.updateInner(node, outerDeco, innerDeco, view);\n return true;\n }\n updateInner(node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM)\n this.updateChildren(view, this.posAtStart);\n this.dirty = NOT_DIRTY;\n }\n updateOuterDeco(outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco))\n return;\n let needsWrap = this.nodeDOM.nodeType != 1;\n let oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = undefined;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n }\n // Mark this node as being the selected node.\n selectNode() {\n if (this.nodeDOM.nodeType == 1)\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.dom.draggable = true;\n }\n // Remove selected node marking from this node.\n deselectNode() {\n if (this.nodeDOM.nodeType == 1) {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.dom.removeAttribute(\"draggable\");\n }\n }\n get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom, view, 0);\n if (docView.contentDOM)\n docView.updateChildren(view, 0);\n return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {\n super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);\n }\n parseRule() {\n let skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco)\n skip = skip.parentNode;\n return { skip: (skip || true) };\n }\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node))\n return false;\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM)\n view.trackWrites = null;\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true;\n }\n inParent() {\n let parentDOM = this.parent.contentDOM;\n for (let n = this.nodeDOM; n; n = n.parentNode)\n if (n == parentDOM)\n return true;\n return false;\n }\n domFromPos(pos) {\n return { node: this.nodeDOM, offset: pos };\n }\n localPosFromDOM(dom, offset, bias) {\n if (dom == this.nodeDOM)\n return this.posAtStart + Math.min(offset, this.node.text.length);\n return super.localPosFromDOM(dom, offset, bias);\n }\n ignoreMutation(mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\";\n }\n slice(from, to, view) {\n let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);\n }\n markDirty(from, to) {\n super.markDirty(from, to);\n if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n this.dirty = NODE_DIRTY;\n }\n get domAtom() { return false; }\n isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag trailing BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass TrailingHackViewDesc extends ViewDesc {\n parseRule() { return { ignore: true }; }\n matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n get domAtom() { return true; }\n get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {\n super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);\n this.spec = spec;\n }\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY)\n return false;\n if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n let result = this.spec.update(node, outerDeco, innerDeco);\n if (result)\n this.updateInner(node, outerDeco, innerDeco, view);\n return result;\n }\n else if (!this.contentDOM && !node.isLeaf) {\n return false;\n }\n else {\n return super.update(node, outerDeco, innerDeco, view);\n }\n }\n selectNode() {\n this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n }\n deselectNode() {\n this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n }\n setSelection(anchor, head, view, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n : super.setSelection(anchor, head, view, force);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n stopEvent(event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n let dom = parentDOM.firstChild, written = false;\n for (let i = 0; i < descs.length; i++) {\n let desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) {\n dom = rm(dom);\n written = true;\n }\n dom = dom.nextSibling;\n }\n else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) {\n dom = rm(dom);\n written = true;\n }\n if (written && view.trackWrites == parentDOM)\n view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n if (nodeName)\n this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0)\n return noDeco;\n let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n for (let i = 0; i < outerDeco.length; i++) {\n let attrs = outerDeco[i].type.attrs;\n if (!attrs)\n continue;\n if (attrs.nodeName)\n result.push(top = new OuterDecoLevel(attrs.nodeName));\n for (let name in attrs) {\n let val = attrs[name];\n if (val == null)\n continue;\n if (needsWrap && result.length == 1)\n result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n if (name == \"class\")\n top.class = (top.class ? top.class + \" \" : \"\") + val;\n else if (name == \"style\")\n top.style = (top.style ? top.style + \";\" : \"\") + val;\n else if (name != \"nodeName\")\n top[name] = val;\n }\n }\n return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco)\n return nodeDOM;\n let curDOM = nodeDOM;\n for (let i = 0; i < curComputed.length; i++) {\n let deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n let parent;\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n }\n else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n for (let name in prev)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n dom.removeAttribute(name);\n for (let name in cur)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n dom.setAttribute(name, cur[name]);\n if (prev.class != cur.class) {\n let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n for (let i = 0; i < prevList.length; i++)\n if (curList.indexOf(prevList[i]) == -1)\n dom.classList.remove(prevList[i]);\n for (let i = 0; i < curList.length; i++)\n if (prevList.indexOf(curList[i]) == -1)\n dom.classList.add(curList[i]);\n if (dom.classList.length == 0)\n dom.removeAttribute(\"class\");\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n dom.style.removeProperty(m[1]);\n }\n if (cur.style)\n dom.style.cssText += cur.style;\n }\n}\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));\n}\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].type.eq(b[i].type))\n return false;\n return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n constructor(top, lock, view) {\n this.lock = lock;\n this.view = view;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n this.top = top;\n this.preMatch = preMatch(top.node.content, top);\n }\n // Destroy and remove the children between the given indices in\n // `this.top`.\n destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }\n // Destroy all remaining children in `this.top`.\n destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }\n // Sync the current stack of mark descs with the given array of\n // marks, reusing existing mark descs when possible.\n syncToMarks(marks, inline, view) {\n let keep = 0, depth = this.stack.length >> 1;\n let maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n keep++;\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n let found = -1;\n for (let i = this.index; i < Math.min(this.index + 3, this.top.children.length); i++) {\n let next = this.top.children[i];\n if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n found = i;\n break;\n }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n }\n else {\n let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n }\n // Try to find a node desc matching the given data. Skip over it and\n // return true when successful.\n findNodeMatch(node, outerDeco, innerDeco, index) {\n let found = -1, targetDesc;\n if (index >= this.preMatch.index &&\n (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n found = this.top.children.indexOf(targetDesc, this.index);\n }\n else {\n for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n let child = this.top.children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n found = i;\n break;\n }\n }\n }\n if (found < 0)\n return false;\n this.destroyBetween(this.index, found);\n this.index++;\n return true;\n }\n updateNodeAt(node, outerDeco, innerDeco, index, view) {\n let child = this.top.children[index];\n if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n child.dirty = CONTENT_DIRTY;\n if (!child.update(node, outerDeco, innerDeco, view))\n return false;\n this.destroyBetween(this.index, index);\n this.index++;\n return true;\n }\n findIndexWithChild(domNode) {\n for (;;) {\n let parent = domNode.parentNode;\n if (!parent)\n return -1;\n if (parent == this.top.contentDOM) {\n let desc = domNode.pmViewDesc;\n if (desc)\n for (let i = this.index; i < this.top.children.length; i++) {\n if (this.top.children[i] == desc)\n return i;\n }\n return -1;\n }\n domNode = parent;\n }\n }\n // Try to update the next node, if any, to the given data. Checks\n // pre-matches to avoid overwriting nodes that could still be used.\n updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n for (let i = this.index; i < this.top.children.length; i++) {\n let next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n let preMatch = this.preMatch.matched.get(next);\n if (preMatch != null && preMatch != index)\n return false;\n let nextDOM = next.dom, updated;\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n let locked = this.isLocked(nextDOM) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM)\n this.changed = true;\n this.index++;\n return true;\n }\n else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n this.destroyBetween(this.index, i);\n this.top.children[this.index] = updated;\n if (updated.contentDOM) {\n updated.dirty = CONTENT_DIRTY;\n updated.updateChildren(view, pos + 1);\n updated.dirty = NOT_DIRTY;\n }\n this.changed = true;\n this.index++;\n return true;\n }\n break;\n }\n }\n return false;\n }\n // When a node with content is replaced by a different node with\n // identical content, move over its children.\n recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n if (next.dirty || node.isAtom || !next.children.length ||\n !next.node.content.eq(node.content) ||\n !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n return null;\n let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (wrapper.contentDOM) {\n wrapper.children = next.children;\n next.children = [];\n for (let ch of wrapper.children)\n ch.parent = wrapper;\n }\n next.destroy();\n return wrapper;\n }\n // Insert the node as a newly created node desc.\n addNode(node, outerDeco, innerDeco, view, pos) {\n let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (desc.contentDOM)\n desc.updateChildren(view, pos + 1);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n placeWidget(widget, view, pos) {\n let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) &&\n (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n }\n else {\n let desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n }\n // Make sure a textblock looks and behaves correctly in\n // contentEditable.\n addTextblockHacks() {\n let lastChild = this.top.children[this.index - 1], parent = this.top;\n while (lastChild instanceof MarkViewDesc) {\n parent = lastChild;\n lastChild = parent.children[parent.children.length - 1];\n }\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text) ||\n (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n this.addHackNode(\"IMG\", parent);\n this.addHackNode(\"BR\", this.top);\n }\n }\n addHackNode(nodeName, parent) {\n if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n this.index++;\n }\n else {\n let dom = document.createElement(nodeName);\n if (nodeName == \"IMG\") {\n dom.className = \"ProseMirror-separator\";\n dom.alt = \"\";\n }\n if (nodeName == \"BR\")\n dom.className = \"ProseMirror-trailingBreak\";\n let hack = new TrailingHackViewDesc(this.top, [], dom, null);\n if (parent != this.top)\n parent.children.push(hack);\n else\n parent.children.splice(this.index++, 0, hack);\n this.changed = true;\n }\n }\n isLocked(node) {\n return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));\n }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes. Returns the fragment index of the first node that\n// is part of the sequence of matched nodes at the end of the\n// fragment.\nfunction preMatch(frag, parentDesc) {\n let curDesc = parentDesc, descI = curDesc.children.length;\n let fI = frag.childCount, matched = new Map, matches = [];\n outer: while (fI > 0) {\n let desc;\n for (;;) {\n if (descI) {\n let next = curDesc.children[descI - 1];\n if (next instanceof MarkViewDesc) {\n curDesc = next;\n descI = next.children.length;\n }\n else {\n desc = next;\n descI--;\n break;\n }\n }\n else if (curDesc == parentDesc) {\n break outer;\n }\n else {\n // FIXME\n descI = curDesc.parent.children.indexOf(curDesc);\n curDesc = curDesc.parent;\n }\n }\n let node = desc.node;\n if (!node)\n continue;\n if (node != frag.child(fI - 1))\n break;\n --fI;\n matched.set(desc, fI);\n matches.push(desc);\n }\n return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n let locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (let i = 0; i < parent.childCount; i++) {\n let child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return;\n }\n let decoIndex = 0, active = [], restNode = null;\n for (let parentIndex = 0;;) {\n let widget, widgets;\n while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n let next = locals[decoIndex++];\n if (next.widget) {\n if (!widget)\n widget = next;\n else\n (widgets || (widgets = [widget])).push(next);\n }\n }\n if (widget) {\n if (widgets) {\n widgets.sort(compareSide);\n for (let i = 0; i < widgets.length; i++)\n onWidget(widgets[i], parentIndex, !!restNode);\n }\n else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n let child, index;\n if (restNode) {\n index = -1;\n child = restNode;\n restNode = null;\n }\n else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child = parent.child(parentIndex++);\n }\n else {\n break;\n }\n for (let i = 0; i < active.length; i++)\n if (active[i].to <= offset)\n active.splice(i--, 1);\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n active.push(locals[decoIndex++]);\n let end = offset + child.nodeSize;\n if (child.isText) {\n let cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n cutAt = locals[decoIndex].from;\n for (let i = 0; i < active.length; i++)\n if (active[i].to < cutAt)\n cutAt = active[i].to;\n if (cutAt < end) {\n restNode = child.cut(cutAt - offset);\n child = child.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n else {\n while (decoIndex < locals.length && locals[decoIndex].to < end)\n decoIndex++;\n }\n let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n onNode(child, outerDeco, deco.forChild(offset, child), index);\n offset = end;\n }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n let oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n let child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText)\n continue;\n let str = child.text;\n while (i < frag.childCount) {\n let next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText)\n break;\n str += next.text;\n }\n if (pos >= from) {\n if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n return to - text.length;\n let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n if (found >= 0 && found + text.length + childStart >= from)\n return childStart + found;\n if (from == to && str.length >= (to + text.length) - childStart &&\n str.slice(to - childStart, to - childStart + text.length) == text)\n return to;\n }\n }\n return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n let result = [];\n for (let i = 0, off = 0; i < nodes.length; i++) {\n let child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n }\n else {\n if (start < from)\n result.push(child.slice(0, from - start, view));\n if (replacement) {\n result.push(replacement);\n replacement = undefined;\n }\n if (end > to)\n result.push(child.slice(to - start, child.size, view));\n }\n }\n return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n let domSel = view.domSelectionRange(), doc = view.state.doc;\n if (!domSel.focusNode)\n return null;\n let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n if (head < 0)\n return null;\n let $head = doc.resolve(head), anchor, selection;\n if (selectionCollapsed(domSel)) {\n anchor = head;\n while (nearestDesc && !nearestDesc.node)\n nearestDesc = nearestDesc.parent;\n let nearestDescNode = nearestDesc.node;\n if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent\n && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n let pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n }\n else {\n if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n let min = head, max = head;\n for (let i = 0; i < domSel.rangeCount; i++) {\n let range = domSel.getRangeAt(i);\n min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n }\n if (min < 0)\n return null;\n [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n $head = doc.resolve(head);\n }\n else {\n anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n }\n if (anchor < 0)\n return null;\n }\n let $anchor = doc.resolve(anchor);\n if (!selection) {\n let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection;\n}\nfunction editorOwnsSelection(view) {\n return view.editable ? view.hasFocus() :\n hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n let sel = view.state.selection;\n syncNodeSelection(view, sel);\n if (!editorOwnsSelection(view))\n return;\n // The delayed drag selection causes issues with Cell Selections\n // in Safari. And the drag selection delay is to workarond issues\n // which only present in Chrome.\n if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {\n let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n if (domSel.anchorNode && curSel.anchorNode &&\n isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {\n view.input.mouseDown.delayedSelectionSync = true;\n view.domObserver.setCurSelection();\n return;\n }\n }\n view.domObserver.disconnectSelection();\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n }\n else {\n let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n resetEditableFrom = temporarilyEditableNear(view, sel.from);\n if (!sel.empty && !sel.$from.parent.inlineContent)\n resetEditableTo = temporarilyEditableNear(view, sel.to);\n }\n view.docView.setSelection(anchor, head, view, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom)\n resetEditable(resetEditableFrom);\n if (resetEditableTo)\n resetEditable(resetEditableTo);\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document)\n removeClassOnSelectionChange(view);\n }\n }\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n let { node, offset } = view.docView.domFromPos(pos, 0);\n let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n let before = offset ? node.childNodes[offset - 1] : null;\n if (safari && after && after.contentEditable == \"false\")\n return setEditable(after);\n if ((!after || after.contentEditable == \"false\") &&\n (!before || before.contentEditable == \"false\")) {\n if (after)\n return setEditable(after);\n else if (before)\n return setEditable(before);\n }\n}\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (safari && element.draggable) {\n element.draggable = false;\n element.wasDraggable = true;\n }\n return element;\n}\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) {\n element.draggable = true;\n element.wasDraggable = null;\n }\n}\nfunction removeClassOnSelectionChange(view) {\n let doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n let domSel = view.domSelectionRange();\n let node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n setTimeout(() => {\n if (!editorOwnsSelection(view) || view.state.selection.visible)\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }, 20);\n }\n });\n}\nfunction selectCursorWrapper(view) {\n let domSel = view.domSelection(), range = document.createRange();\n if (!domSel)\n return;\n let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img)\n range.setStart(node.parentNode, domIndex(node) + 1);\n else\n range.setStart(node, 0);\n range.collapse(true);\n domSel.removeAllRanges();\n domSel.addRange(range);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && ie && ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n let desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc)\n desc.selectNode();\n view.lastSelectedViewDesc = desc;\n }\n }\n else {\n clearNodeSelection(view);\n }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n view.lastSelectedViewDesc.deselectNode();\n view.lastSelectedViewDesc = undefined;\n }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n if (view.editable && !view.hasFocus())\n return false;\n return hasSelection(view);\n}\nfunction hasSelection(view) {\n let sel = view.domSelectionRange();\n if (!sel.anchorNode)\n return false;\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) &&\n (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));\n }\n catch (_) {\n return false;\n }\n}\nfunction anchorInRightPlace(view) {\n let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n let domSel = view.domSelectionRange();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n let { $anchor, $head } = state.selection;\n let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (mods.indexOf(\"s\") > -1) {\n let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n if (!node || node.isText || !node.isLeaf)\n return false;\n let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n return apply(view, new TextSelection(sel.$anchor, $newHead));\n }\n else if (!sel.empty) {\n return false;\n }\n else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n return false;\n }\n else if (!(mac && mods.indexOf(\"m\") > -1)) {\n let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText)\n return false;\n let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n return false;\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n }\n else if (webkit) {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes, so we have to\n // take over and move the cursor past them (#937)\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n }\n else {\n return false;\n }\n }\n }\n else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n }\n else {\n let next = moveSelectionBlock(view.state, dir);\n if (next)\n return apply(view, next);\n return false;\n }\n}\nfunction nodeLen(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isIgnorable(dom, dir) {\n let desc = dom.pmViewDesc;\n return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\");\n}\nfunction skipIgnoredNodes(view, dir) {\n return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))\n force = true;\n for (;;) {\n if (offset > 0) {\n if (node.nodeType != 1) {\n break;\n }\n else {\n let before = node.childNodes[offset - 1];\n if (isIgnorable(before, -1)) {\n moveNode = node;\n moveOffset = --offset;\n }\n else if (before.nodeType == 3) {\n node = before;\n offset = node.nodeValue.length;\n }\n else\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let prev = node.previousSibling;\n while (prev && isIgnorable(prev, -1)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = 0;\n }\n else {\n node = prev;\n offset = nodeLen(node);\n }\n }\n }\n if (force)\n setSelFocus(view, node, offset);\n else if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let len = nodeLen(node);\n let moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (node.nodeType != 1)\n break;\n let after = node.childNodes[offset];\n if (isIgnorable(after, 1)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else\n break;\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let next = node.nextSibling;\n while (next && isIgnorable(next, 1)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = len = 0;\n }\n else {\n node = next;\n offset = 0;\n len = nodeLen(node);\n }\n }\n }\n if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n let desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n while (node && offset < node.childNodes.length) {\n let next = node.childNodes[offset];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = 0;\n }\n}\nfunction textNodeBefore(node, offset) {\n while (node && !offset && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (node && offset) {\n let next = node.childNodes[offset - 1];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = node.childNodes.length;\n }\n}\nfunction setSelFocus(view, node, offset) {\n if (node.nodeType != 3) {\n let before, after;\n if (after = textNodeAfter(node, offset)) {\n node = after;\n offset = 0;\n }\n else if (before = textNodeBefore(node, offset)) {\n node = before;\n offset = before.nodeValue.length;\n }\n }\n let sel = view.domSelection();\n if (!sel)\n return;\n if (selectionCollapsed(sel)) {\n let range = document.createRange();\n range.setEnd(node, offset);\n range.setStart(node, offset);\n sel.removeAllRanges();\n sel.addRange(range);\n }\n else if (sel.extend) {\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n let { state } = view;\n // If no state update ends up happening, reset the selection.\n setTimeout(() => {\n if (view.state == state)\n selectionToDOM(view);\n }, 50);\n}\nfunction findDirection(view, pos) {\n let $pos = view.state.doc.resolve(pos);\n if (!(chrome || windows) && $pos.parent.inlineContent) {\n let coords = view.coordsAtPos(pos);\n if (pos > $pos.start()) {\n let before = view.coordsAtPos(pos - 1);\n let mid = (before.top + before.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n return before.left < coords.left ? \"ltr\" : \"rtl\";\n }\n if (pos < $pos.end()) {\n let after = view.coordsAtPos(pos + 1);\n let mid = (after.top + after.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n return after.left > coords.left ? \"ltr\" : \"rtl\";\n }\n }\n let computed = getComputedStyle(view.dom).direction;\n return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n return false;\n if (mac && mods.indexOf(\"m\") > -1)\n return false;\n let { $from, $to } = sel;\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n }\n if (!$from.parent.inlineContent) {\n let side = dir < 0 ? $from : $to;\n let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n return beyond ? apply(view, beyond) : false;\n }\n return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection))\n return true;\n let { $head, $anchor, empty } = view.state.selection;\n if (!$head.sameParent($anchor))\n return true;\n if (!empty)\n return false;\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n return true;\n let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n let tr = view.state.tr;\n if (dir < 0)\n tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n else\n tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n view.dispatch(tr);\n return true;\n }\n return false;\n}\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!safari || view.state.selection.$head.parentOffset > 0)\n return false;\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 &&\n focusNode.firstChild && focusNode.firstChild.contentEditable == \"false\") {\n let child = focusNode.firstChild;\n switchEditable(view, child, \"true\");\n setTimeout(() => switchEditable(view, child, \"false\"), 20);\n }\n return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n let result = \"\";\n if (event.ctrlKey)\n result += \"c\";\n if (event.metaKey)\n result += \"m\";\n if (event.altKey)\n result += \"a\";\n if (event.shiftKey)\n result += \"s\";\n return result;\n}\nfunction captureKeyDown(view, event) {\n let code = event.keyCode, mods = getMods(event);\n if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n }\n else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n }\n else if (code == 13 || code == 27) { // Enter, Esc\n return true;\n }\n else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n }\n else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n }\n else if (mods == (mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true;\n }\n return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n let context = [], { content, openStart, openEnd } = slice;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n let node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (let i = needsWrap.length - 1; i >= 0; i--) {\n let wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild)\n wrapper.appendChild(wrap.firstChild);\n wrap.appendChild(wrapper);\n wrappers++;\n }\n firstChild = wrap.firstChild;\n }\n if (firstChild && firstChild.nodeType == 1)\n firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n let inCode = $context.parent.type.spec.code;\n let dom, slice;\n if (!html && !text)\n return null;\n let asText = text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n if (inCode)\n return text ? new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0) : Slice.empty;\n let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n if (parsed) {\n slice = parsed;\n }\n else {\n let marks = $context.marks();\n let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n dom = document.createElement(\"div\");\n text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n let p = dom.appendChild(document.createElement(\"p\"));\n if (block)\n p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n });\n }\n }\n else {\n view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n dom = readHTML(html);\n if (webkit)\n restoreReplacedSpaces(dom);\n }\n let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n if (sliceData && sliceData[3])\n for (let i = +sliceData[3]; i > 0; i--) {\n let child = dom.firstChild;\n while (child && child.nodeType != 1)\n child = child.nextSibling;\n if (!child)\n break;\n dom = child;\n }\n if (!slice) {\n let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {\n preserveWhitespace: !!(asText || sliceData),\n context: $context,\n ruleFromNode(dom) {\n if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n return { ignore: true };\n return null;\n }\n });\n }\n if (sliceData) {\n slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n }\n else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n if (slice.openStart || slice.openEnd) {\n let openStart = 0, openEnd = 0;\n for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n slice = closeSlice(slice, openStart, openEnd);\n }\n }\n view.someProp(\"transformPasted\", f => { slice = f(slice, view); });\n return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2)\n return fragment;\n for (let d = $context.depth; d >= 0; d--) {\n let parent = $context.node(d);\n let match = parent.contentMatchAt($context.index(d));\n let lastWrap, result = [];\n fragment.forEach(node => {\n if (!result)\n return;\n let wrap = match.findWrapping(node.type), inLast;\n if (!wrap)\n return result = null;\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n }\n else {\n if (result.length)\n result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n let wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type);\n lastWrap = wrap;\n }\n });\n if (result)\n return Fragment.from(result);\n }\n return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n for (let i = wrap.length - 1; i >= from; i--)\n node = wrap[i].create(null, Fragment.from(node));\n return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner)\n return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n let match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n }\n}\nfunction closeRight(node, depth) {\n if (depth == 0)\n return node;\n let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (fragment.childCount > 1)\n openEnd = 0;\n if (depth < to - 1)\n inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n if (depth >= from)\n inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n if (openEnd < slice.openEnd)\n slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"..\"` the table cells are ignored.\nconst wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\nlet _detachedDoc = null;\nfunction detachedDoc() {\n return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument(\"title\"));\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n let trustedTypes = window.trustedTypes;\n if (!trustedTypes)\n return html;\n // With the require-trusted-types-for CSP, Chrome will block\n // innerHTML, even on a detached document. This wraps the string in\n // a way that makes the browser allow us to use its parser again.\n if (!_policy)\n _policy = trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n let metas = /^(\\s*]*>)*/.exec(html);\n if (metas)\n html = html.slice(metas[0].length);\n let elt = detachedDoc().createElement(\"div\");\n let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"\").reverse().join(\"\");\n elt.innerHTML = maybeWrapTrusted(html);\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n elt = elt.querySelector(wrap[i]) || elt;\n return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n for (let i = 0; i < nodes.length; i++) {\n let node = nodes[i];\n if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n }\n}\nfunction addContext(slice, context) {\n if (!slice.size)\n return slice;\n let schema = slice.content.firstChild.type.schema, array;\n try {\n array = JSON.parse(context);\n }\n catch (e) {\n return slice;\n }\n let { content, openStart, openEnd } = slice;\n for (let i = array.length - 2; i >= 0; i -= 2) {\n let type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs())\n break;\n content = Fragment.from(type.create(array[i + 1], content));\n openStart++;\n openEnd++;\n }\n return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n constructor() {\n this.shiftKey = false;\n this.mouseDown = null;\n this.lastKeyCode = null;\n this.lastKeyCodeTime = 0;\n this.lastClick = { time: 0, x: 0, y: 0, type: \"\" };\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastIOSEnter = 0;\n this.lastIOSEnterFallbackTimeout = -1;\n this.lastFocus = 0;\n this.lastTouch = 0;\n this.lastChromeDelete = 0;\n this.composing = false;\n this.compositionNode = null;\n this.composingTimeout = -1;\n this.compositionNodes = [];\n this.compositionEndedAt = -2e8;\n this.compositionID = 1;\n // Set to a composition ID when there are pending changes at compositionend\n this.compositionPendingChanges = 0;\n this.domChangeCount = 0;\n this.eventHandlers = Object.create(null);\n this.hideSelectionGuard = null;\n }\n}\nfunction initInput(view) {\n for (let event in handlers) {\n let handler = handlers[event];\n view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n handler(view, event);\n }, passiveHandlers[event] ? { passive: true } : undefined);\n }\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (safari)\n view.dom.addEventListener(\"input\", () => null);\n ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n view.input.lastSelectionOrigin = origin;\n view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n view.domObserver.stop();\n for (let type in view.input.eventHandlers)\n view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n clearTimeout(view.input.composingTimeout);\n clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", currentHandlers => {\n for (let type in currentHandlers)\n if (!view.input.eventHandlers[type])\n view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n });\n}\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", handlers => {\n let handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false;\n });\n}\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let node = event.target; node != view.dom; node = node.parentNode)\n if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n return false;\n return true;\n}\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n handlers[event.type](view, event);\n}\neditHandlers.keydown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view, event))\n return;\n view.input.lastKeyCode = event.keyCode;\n view.input.lastKeyCodeTime = Date.now();\n // Suppress enter key events on Chrome Android, because those tend\n // to be part of a confused sequence of composition events fired,\n // and handling them eagerly tends to corrupt the input.\n if (android && chrome && event.keyCode == 13)\n return;\n if (event.keyCode != 229)\n view.domObserver.forceFlush();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n let now = Date.now();\n view.input.lastIOSEnter = now;\n view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n if (view.input.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")));\n view.input.lastIOSEnter = 0;\n }\n }, 200);\n }\n else if (view.someProp(\"handleKeyDown\", f => f(view, event)) || captureKeyDown(view, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"key\");\n }\n};\neditHandlers.keyup = (view, event) => {\n if (event.keyCode == 16)\n view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n let event = _event;\n if (inOrNearComposition(view, event) || !event.charCode ||\n event.ctrlKey && !event.altKey || mac && event.metaKey)\n return;\n if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n event.preventDefault();\n return;\n }\n let sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n let text = String.fromCharCode(event.charCode);\n if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text)))\n view.dispatch(view.state.tr.insertText(text).scrollIntoView());\n event.preventDefault();\n }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n let dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n return true;\n }\n return false;\n}\nfunction updateSelection(view, selection, origin) {\n if (!view.focused)\n view.focus();\n if (view.state.selection.eq(selection))\n return;\n let tr = view.state.tr.setSelection(selection);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos), \"pointer\");\n return true;\n }\n return false;\n}\nfunction selectClickedNode(view, inside) {\n if (inside == -1)\n return false;\n let sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection)\n selectedNode = sel.node;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n selectAt = $pos.before(sel.$from.depth);\n else\n selectAt = $pos.before(i);\n break;\n }\n }\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt), \"pointer\");\n return true;\n }\n else {\n return false;\n }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n if (event.button != 0)\n return false;\n let doc = view.state.doc;\n if (inside == -1) {\n if (doc.inlineContent) {\n updateSelection(view, TextSelection.create(doc, 0, doc.content.size), \"pointer\");\n return true;\n }\n return false;\n }\n let $pos = doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n let nodePos = $pos.before(i);\n if (node.inlineContent)\n updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), \"pointer\");\n else if (NodeSelection.isSelectable(node))\n updateSelection(view, NodeSelection.create(doc, nodePos), \"pointer\");\n else\n continue;\n return true;\n }\n}\nfunction forceDOMFlush(view) {\n return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.shiftKey;\n let flushed = forceDOMFlush(view);\n let now = Date.now(), type = \"singleClick\";\n if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier]) {\n if (view.input.lastClick.type == \"singleClick\")\n type = \"doubleClick\";\n else if (view.input.lastClick.type == \"doubleClick\")\n type = \"tripleClick\";\n }\n view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type };\n let pos = view.posAtCoords(eventCoords(event));\n if (!pos)\n return;\n if (type == \"singleClick\") {\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);\n }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"pointer\");\n }\n};\nclass MouseDown {\n constructor(view, pos, event, flushed) {\n this.view = view;\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.delayedSelectionSync = false;\n this.mightDrag = null;\n this.startDoc = view.state.doc;\n this.selectNode = !!event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n let targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n }\n else {\n let $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n const target = flushed ? null : event.target;\n const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc && targetDesc.dom.nodeType == 1 ? targetDesc.dom : null;\n let { selection } = view.state;\n if (event.button == 0 &&\n targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)\n this.mightDrag = {\n node: targetNode,\n pos: targetPos,\n addAttr: !!(this.target && !this.target.draggable),\n setUneditable: !!(this.target && gecko && !this.target.hasAttribute(\"contentEditable\"))\n };\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.draggable = true;\n if (this.mightDrag.setUneditable)\n setTimeout(() => {\n if (this.view.input.mouseDown == this)\n this.target.setAttribute(\"contentEditable\", \"false\");\n }, 20);\n this.view.domObserver.start();\n }\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n setSelectionOrigin(view, \"pointer\");\n }\n done() {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.removeAttribute(\"draggable\");\n if (this.mightDrag.setUneditable)\n this.target.removeAttribute(\"contentEditable\");\n this.view.domObserver.start();\n }\n if (this.delayedSelectionSync)\n setTimeout(() => selectionToDOM(this.view));\n this.view.input.mouseDown = null;\n }\n up(event) {\n this.done();\n if (!this.view.dom.contains(event.target))\n return;\n let pos = this.pos;\n if (this.view.state.doc != this.startDoc)\n pos = this.view.posAtCoords(eventCoords(event));\n this.updateAllowDefault(event);\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n }\n else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n }\n else if (event.button == 0 &&\n (this.flushed ||\n // Safari ignores clicks on draggable elements\n (safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (chrome && !this.view.state.selection.visible &&\n Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), \"pointer\");\n event.preventDefault();\n }\n else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n }\n move(event) {\n this.updateAllowDefault(event);\n setSelectionOrigin(this.view, \"pointer\");\n if (event.buttons == 0)\n this.done();\n }\n updateAllowDefault(event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n this.allowDefault = true;\n }\n}\nhandlers.touchstart = view => {\n view.input.lastTouch = Date.now();\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n view.input.lastTouch = Date.now();\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n if (view.composing)\n return true;\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {\n view.input.compositionEndedAt = -2e8;\n return true;\n }\n return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n if (!view.composing) {\n view.domObserver.flush();\n let { state } = view, $pos = state.selection.$to;\n if (state.selection instanceof TextSelection &&\n (state.storedMarks ||\n (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)))) {\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n }\n else {\n endComposition(view, !state.selection.empty);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n let sel = view.domSelectionRange();\n for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {\n let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before)\n break;\n if (before.nodeType == 3) {\n let sel = view.domSelection();\n if (sel)\n sel.collapse(before, before.nodeValue.length);\n break;\n }\n else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.input.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\neditHandlers.compositionend = (view, event) => {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = event.timeStamp;\n view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n view.input.compositionNode = null;\n if (view.input.compositionPendingChanges)\n Promise.resolve().then(() => view.domObserver.flush());\n view.input.compositionID++;\n scheduleComposeEnd(view, 20);\n }\n};\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.input.composingTimeout);\n if (delay > -1)\n view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = timestampFromCustomEvent();\n }\n while (view.input.compositionNodes.length > 0)\n view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n let sel = view.domSelectionRange();\n if (!sel.focusNode)\n return null;\n let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n if (textBefore && textAfter && textBefore != textAfter) {\n let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n if (textBefore == lastChanged || textAfter == lastChanged)\n return lastChanged;\n if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n return textAfter;\n }\n else if (view.input.compositionNode == textAfter) {\n let descBefore = textBefore.pmViewDesc;\n if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n return textAfter;\n }\n }\n return textBefore || textAfter;\n}\nfunction timestampFromCustomEvent() {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"event\", true, true);\n return event.timeStamp;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n if (android && view.domObserver.flushingSoon >= 0)\n return;\n view.domObserver.forceFlush();\n clearComposition(view);\n if (restarting || view.docView && view.docView.dirty) {\n let sel = selectionFromDOM(view);\n if (sel && !sel.eq(view.state.selection))\n view.dispatch(view.state.tr.setSelection(sel));\n else if ((view.markCursor || restarting) && !view.state.selection.empty)\n view.dispatch(view.state.tr.deleteSelection());\n else\n view.updateState(view.state);\n return true;\n }\n return false;\n}\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode)\n return;\n let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n let sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(() => {\n if (wrap.parentNode)\n wrap.parentNode.removeChild(wrap);\n view.focus();\n }, 50);\n}\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n let event = _event;\n let sel = view.state.selection, cut = event.type == \"cut\";\n if (sel.empty)\n return;\n // IE and Edge's clipboard interface is completely broken\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n if (data) {\n event.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n }\n else {\n captureCopy(view, dom);\n }\n if (cut)\n view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n if (!view.dom.parentNode)\n return;\n let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText)\n target.contentEditable = \"true\";\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n setTimeout(() => {\n view.focus();\n if (target.parentNode)\n target.parentNode.removeChild(target);\n if (plainText)\n doPaste(view, target.value, null, plain, event);\n else\n doPaste(view, target.textContent, target.innerHTML, plain, event);\n }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n return true;\n if (!slice)\n return false;\n let singleNode = sliceSingleNode(slice);\n let tr = singleNode\n ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\nfunction getText(clipboardData) {\n let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n if (text)\n return text;\n let uris = clipboardData.getData(\"text/uri-list\");\n return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n let event = _event;\n // Handling paste from JavaScript during composition is very poorly\n // handled by browsers, so as a dodgy but preferable kludge, we just\n // let the browser do its native thing there, except on Android,\n // where the editor is almost always composing.\n if (view.composing && !android)\n return;\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n event.preventDefault();\n else\n capturePaste(view, event);\n};\nclass Dragging {\n constructor(slice, move, node) {\n this.slice = slice;\n this.move = move;\n this.node = node;\n }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nhandlers.dragstart = (view, _event) => {\n let event = _event;\n let mouseDown = view.input.mouseDown;\n if (mouseDown)\n mouseDown.done();\n if (!event.dataTransfer)\n return;\n let sel = view.state.selection;\n let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n let node;\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n else if (mouseDown && mouseDown.mightDrag) {\n node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n }\n else if (event.target && event.target.nodeType == 1) {\n let desc = view.docView.nearestDesc(event.target, true);\n if (desc && desc.node.type.spec.draggable && desc != view.docView)\n node = NodeSelection.create(view.state.doc, desc.posBefore);\n }\n let draggedSlice = (node || view.state.selection).content();\n let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n event.dataTransfer.clearData();\n event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n // See https://github.com/ProseMirror/prosemirror/issues/1156\n event.dataTransfer.effectAllowed = \"copyMove\";\n if (!brokenClipboardAPI)\n event.dataTransfer.setData(\"text/plain\", text);\n view.dragging = new Dragging(slice, !event[dragCopyModifier], node);\n};\nhandlers.dragend = view => {\n let dragging = view.dragging;\n window.setTimeout(() => {\n if (view.dragging == dragging)\n view.dragging = null;\n }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, _event) => {\n let event = _event;\n let dragging = view.dragging;\n view.dragging = null;\n if (!event.dataTransfer)\n return;\n let eventPos = view.posAtCoords(eventCoords(event));\n if (!eventPos)\n return;\n let $mouse = view.state.doc.resolve(eventPos.pos);\n let slice = dragging && dragging.slice;\n if (slice) {\n view.someProp(\"transformPasted\", f => { slice = f(slice, view); });\n }\n else {\n slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n }\n let move = !!(dragging && !event[dragCopyModifier]);\n if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n event.preventDefault();\n return;\n }\n if (!slice)\n return;\n event.preventDefault();\n let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null)\n insertPos = $mouse.pos;\n let tr = view.state.tr;\n if (move) {\n let { node } = dragging;\n if (node)\n node.replace(tr);\n else\n tr.deleteSelection();\n }\n let pos = tr.mapping.map(insertPos);\n let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n let beforeInsert = tr.doc;\n if (isNode)\n tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n else\n tr.replaceRange(pos, pos, slice);\n if (tr.doc.eq(beforeInsert))\n return;\n let $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n }\n else {\n let end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n};\nhandlers.focus = view => {\n view.input.lastFocus = Date.now();\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(() => {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))\n selectionToDOM(view);\n }, 20);\n }\n};\nhandlers.blur = (view, _event) => {\n let event = _event;\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n view.domObserver.currentSelection.clear();\n view.focused = false;\n }\n};\nhandlers.beforeinput = (view, _event) => {\n let event = _event;\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome Android when after an uneditable node.\n if (chrome && android && event.inputType == \"deleteContentBackward\") {\n view.domObserver.flushSoon();\n let { domChangeCount } = view.input;\n setTimeout(() => {\n if (view.input.domChangeCount != domChangeCount)\n return; // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\"))))\n return;\n let { $cursor } = view.state.selection;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0)\n view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n }, 50);\n }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n if (a == b)\n return true;\n for (let p in a)\n if (a[p] !== b[p])\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n return true;\n}\nclass WidgetType {\n constructor(toDOM, spec) {\n this.toDOM = toDOM;\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n }\n map(mapping, span, offset, oldOffset) {\n let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n }\n valid() { return true; }\n eq(other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n }\n destroy(node) {\n if (this.spec.destroy)\n this.spec.destroy(node);\n }\n}\nclass InlineType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this);\n }\n valid(_, span) { return span.from < span.to; }\n eq(other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n static is(span) { return span.type instanceof InlineType; }\n destroy() { }\n}\nclass NodeType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted)\n return null;\n let to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos)\n return null;\n return new Decoration(from.pos - offset, to.pos - offset, this);\n }\n valid(node, span) {\n let { index, offset } = node.content.findIndex(span.from), child;\n return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to;\n }\n eq(other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants—see the static members of this class for details.\n*/\nclass Decoration {\n /**\n @internal\n */\n constructor(\n /**\n The start position of the decoration.\n */\n from, \n /**\n The end position. Will be the same as `from` for [widget\n decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n */\n to, \n /**\n @internal\n */\n type) {\n this.from = from;\n this.to = to;\n this.type = type;\n }\n /**\n @internal\n */\n copy(from, to) {\n return new Decoration(from, to, this.type);\n }\n /**\n @internal\n */\n eq(other, offset = 0) {\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n }\n /**\n @internal\n */\n map(mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset);\n }\n /**\n Creates a widget decoration, which is a DOM node that's shown in\n the document at the given position. It is recommended that you\n delay rendering the widget by passing a function that will be\n called when the widget is actually drawn in a view, but you can\n also directly pass a DOM node. `getPos` can be used to find the\n widget's current document position.\n */\n static widget(pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n }\n /**\n Creates an inline decoration, which adds the given attributes to\n each inline node between `from` and `to`.\n */\n static inline(from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec));\n }\n /**\n Creates a node decoration. `from` and `to` should point precisely\n before and after a node in the document. That node, and only that\n node, will receive the given attributes.\n */\n static node(from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec));\n }\n /**\n The spec provided when creating this decoration. Can be useful\n if you've stored extra information in that object.\n */\n get spec() { return this.type.spec; }\n /**\n @internal\n */\n get inline() { return this.type instanceof InlineType; }\n /**\n @internal\n */\n get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure—it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n /**\n @internal\n */\n constructor(local, children) {\n this.local = local.length ? local : none;\n this.children = children.length ? children : none;\n }\n /**\n Create a set of decorations, using the structure of the given\n document. This will consume (modify) the `decorations` array, so\n you must make a copy if you want need to preserve that.\n */\n static create(doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n }\n /**\n Find all decorations in this set which touch the given range\n (including decorations that start or end directly at the\n boundaries) and match the given predicate on their spec. When\n `start` and `end` are omitted, all decorations in the set are\n considered. When `predicate` isn't given, all decorations are\n assumed to match.\n */\n find(start, end, predicate) {\n let result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result;\n }\n findInner(start, end, result, offset, predicate) {\n for (let i = 0; i < this.local.length; i++) {\n let span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n result.push(span.copy(span.from + offset, span.to + offset));\n }\n for (let i = 0; i < this.children.length; i += 3) {\n if (this.children[i] < end && this.children[i + 1] > start) {\n let childOff = this.children[i] + 1;\n this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n }\n /**\n Map the set of decorations in response to a change in the\n document.\n */\n map(mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0)\n return this;\n return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n }\n /**\n @internal\n */\n mapInner(mapping, node, offset, oldOffset, options) {\n let newLocal;\n for (let i = 0; i < this.local.length; i++) {\n let mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped))\n (newLocal || (newLocal = [])).push(mapped);\n else if (options.onRemove)\n options.onRemove(this.local[i].spec);\n }\n if (this.children.length)\n return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n else\n return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n }\n /**\n Add the given array of decorations to the ones in the set,\n producing a new set. Consumes the `decorations` array. Needs\n access to the current document to create the appropriate tree\n structure.\n */\n add(doc, decorations) {\n if (!decorations.length)\n return this;\n if (this == empty)\n return DecorationSet.create(doc, decorations);\n return this.addInner(doc, decorations, 0);\n }\n addInner(doc, decorations, offset) {\n let children, childIndex = 0;\n doc.forEach((childNode, childOffset) => {\n let baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n return;\n if (!children)\n children = this.children.slice();\n while (childIndex < children.length && children[childIndex] < childOffset)\n childIndex += 3;\n if (children[childIndex] == childOffset)\n children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n else\n children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n childIndex += 3;\n });\n let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n for (let i = 0; i < local.length; i++)\n if (!local[i].type.valid(doc, local[i]))\n local.splice(i--, 1);\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n }\n /**\n Create a new set that contains the decorations in this set, minus\n the ones in the given array.\n */\n remove(decorations) {\n if (decorations.length == 0 || this == empty)\n return this;\n return this.removeInner(decorations, 0);\n }\n removeInner(decorations, offset) {\n let children = this.children, local = this.local;\n for (let i = 0; i < children.length; i += 3) {\n let found;\n let from = children[i] + offset, to = children[i + 1] + offset;\n for (let j = 0, span; j < decorations.length; j++)\n if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null;\n (found || (found = [])).push(span);\n }\n }\n if (!found)\n continue;\n if (children == this.children)\n children = this.children.slice();\n let removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n }\n else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length)\n for (let i = 0, span; i < decorations.length; i++)\n if (span = decorations[i]) {\n for (let j = 0; j < local.length; j++)\n if (local[j].eq(span, offset)) {\n if (local == this.local)\n local = this.local.slice();\n local.splice(j--, 1);\n }\n }\n if (children == this.children && local == this.local)\n return this;\n return local.length || children.length ? new DecorationSet(local, children) : empty;\n }\n forChild(offset, node) {\n if (this == empty)\n return this;\n if (node.isLeaf)\n return DecorationSet.empty;\n let child, local;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] >= offset) {\n if (this.children[i] == offset)\n child = this.children[i + 2];\n break;\n }\n let start = offset + 1, end = start + node.content.size;\n for (let i = 0; i < this.local.length; i++) {\n let dec = this.local[i];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to)\n (local || (local = [])).push(dec.copy(from, to));\n }\n }\n if (local) {\n let localSet = new DecorationSet(local.sort(byPos), none);\n return child ? new DecorationGroup([localSet, child]) : localSet;\n }\n return child || empty;\n }\n /**\n @internal\n */\n eq(other) {\n if (this == other)\n return true;\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length)\n return false;\n for (let i = 0; i < this.local.length; i++)\n if (!this.local[i].eq(other.local[i]))\n return false;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] != other.children[i] ||\n this.children[i + 1] != other.children[i + 1] ||\n !this.children[i + 2].eq(other.children[i + 2]))\n return false;\n return true;\n }\n /**\n @internal\n */\n locals(node) {\n return removeOverlap(this.localsInner(node));\n }\n /**\n @internal\n */\n localsInner(node) {\n if (this == empty)\n return none;\n if (node.inlineContent || !this.local.some(InlineType.is))\n return this.local;\n let result = [];\n for (let i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n result.push(this.local[i]);\n }\n return result;\n }\n forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n constructor(members) {\n this.members = members;\n }\n map(mapping, doc) {\n const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n return DecorationGroup.from(mappedDecos);\n }\n forChild(offset, child) {\n if (child.isLeaf)\n return DecorationSet.empty;\n let found = [];\n for (let i = 0; i < this.members.length; i++) {\n let result = this.members[i].forChild(offset, child);\n if (result == empty)\n continue;\n if (result instanceof DecorationGroup)\n found = found.concat(result.members);\n else\n found.push(result);\n }\n return DecorationGroup.from(found);\n }\n eq(other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length)\n return false;\n for (let i = 0; i < this.members.length; i++)\n if (!this.members[i].eq(other.members[i]))\n return false;\n return true;\n }\n locals(node) {\n let result, sorted = true;\n for (let i = 0; i < this.members.length; i++) {\n let locals = this.members[i].localsInner(node);\n if (!locals.length)\n continue;\n if (!result) {\n result = locals;\n }\n else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (let j = 0; j < locals.length; j++)\n result.push(locals[j]);\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n }\n // Create a group for the given array of decoration sets, or return\n // a single set when possible.\n static from(members) {\n switch (members.length) {\n case 0: return empty;\n case 1: return members[0];\n default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n }\n }\n forEachSet(f) {\n for (let i = 0; i < this.members.length; i++)\n this.members[i].forEachSet(f);\n }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n let children = oldChildren.slice();\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n let moved = 0;\n mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n for (let i = 0; i < children.length; i += 3) {\n let end = children[i + 1];\n if (end < 0 || oldStart > end + baseOffset - moved)\n continue;\n let start = children[i] + baseOffset - moved;\n if (oldEnd >= start) {\n children[i + 1] = oldStart <= start ? -2 : -1;\n }\n else if (oldStart >= baseOffset && dSize) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n moved += dSize;\n });\n baseOffset = mapping.maps[i].map(baseOffset, -1);\n }\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n let mustRebuild = false;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) { // Touched nodes\n if (children[i + 1] == -2) {\n mustRebuild = true;\n children[i + 1] = -1;\n continue;\n }\n let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue;\n }\n // Must read oldChildren because children was tagged with -1\n let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n let childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n let mapped = children[i + 2]\n .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i] = fromLocal;\n children[i + 1] = toLocal;\n children[i + 2] = mapped;\n }\n else {\n children[i + 1] = -2;\n mustRebuild = true;\n }\n }\n else {\n mustRebuild = true;\n }\n }\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n let built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) {\n children.splice(i, 3);\n i -= 3;\n }\n for (let i = 0, j = 0; i < built.children.length; i += 3) {\n let from = built.children[i];\n while (j < children.length && children[j] < from)\n j += 3;\n children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n }\n }\n return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length)\n return spans;\n let result = [];\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (let i = 0; i < set.local.length; i++) {\n let mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped)\n decorations.push(mapped);\n else if (options.onRemove)\n options.onRemove(set.local[i].spec);\n }\n for (let i = 0; i < set.children.length; i += 3)\n gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n }\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] == -1)\n gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf)\n return null;\n let end = offset + node.nodeSize, found = null;\n for (let i = 0, span; i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n (found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found;\n}\nfunction withoutNulls(array) {\n let result = [];\n for (let i = 0; i < array.length; i++)\n if (array[i] != null)\n result.push(array[i]);\n return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n let children = [], hasNulls = false;\n node.forEach((childNode, localStart) => {\n let found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n children.push(localStart, localStart + childNode.nodeSize, subtree);\n }\n });\n let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n for (let i = 0; i < locals.length; i++)\n if (!locals[i].type.valid(node, locals[i])) {\n if (options.onRemove)\n options.onRemove(locals[i].spec);\n locals.splice(i--, 1);\n }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n let working = spans;\n for (let i = 0; i < working.length - 1; i++) {\n let span = working[i];\n if (span.from != span.to)\n for (let j = i + 1; j < working.length; j++) {\n let next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans)\n working = spans.slice();\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue;\n }\n else {\n if (next.from < span.to) {\n if (working == spans)\n working = spans.slice();\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break;\n }\n }\n }\n return working;\n}\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0)\n i++;\n array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n let found = [];\n view.someProp(\"decorations\", f => {\n let result = f(view.state);\n if (result && result != empty)\n found.push(result);\n });\n if (view.cursorWrapper)\n found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n return DecorationGroup.from(found);\n}\n\nconst observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n set(sel) {\n this.anchorNode = sel.anchorNode;\n this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode;\n this.focusOffset = sel.focusOffset;\n }\n clear() {\n this.anchorNode = this.focusNode = null;\n }\n eq(sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n }\n}\nclass DOMObserver {\n constructor(view, handleDOMChange) {\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = null;\n this.currentSelection = new SelectionState;\n this.onCharData = null;\n this.suppressingSelectionUpdates = false;\n this.lastChangedTextNode = null;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(mutations => {\n for (let i = 0; i < mutations.length; i++)\n this.queue.push(mutations[i]);\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length))\n this.flushSoon();\n else\n this.flush();\n });\n if (useCharData) {\n this.onCharData = e => {\n this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n this.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n }\n flushSoon() {\n if (this.flushingSoon < 0)\n this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n }\n forceFlush() {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n }\n start() {\n if (this.observer) {\n this.observer.takeRecords();\n this.observer.observe(this.view.dom, observeOptions);\n }\n if (this.onCharData)\n this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.connectSelection();\n }\n stop() {\n if (this.observer) {\n let take = this.observer.takeRecords();\n if (take.length) {\n for (let i = 0; i < take.length; i++)\n this.queue.push(take[i]);\n window.setTimeout(() => this.flush(), 20);\n }\n this.observer.disconnect();\n }\n if (this.onCharData)\n this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.disconnectSelection();\n }\n connectSelection() {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n disconnectSelection() {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n suppressSelectionUpdates() {\n this.suppressingSelectionUpdates = true;\n setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n }\n onSelectionChange() {\n if (!hasFocusAndSelection(this.view))\n return;\n if (this.suppressingSelectionUpdates)\n return selectionToDOM(this.view);\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n let sel = this.view.domSelectionRange();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n return this.flushSoon();\n }\n this.flush();\n }\n setCurSelection() {\n this.currentSelection.set(this.view.domSelectionRange());\n }\n ignoreSelectionChange(sel) {\n if (!sel.focusNode)\n return true;\n let ancestors = new Set, container;\n for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n ancestors.add(scan);\n for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n if (ancestors.has(scan)) {\n container = scan;\n break;\n }\n let desc = container && this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({\n type: \"selection\",\n target: container.nodeType == 3 ? container.parentNode : container\n })) {\n this.setCurSelection();\n return true;\n }\n }\n pendingRecords() {\n if (this.observer)\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n flush() {\n let { view } = this;\n if (!view.docView || this.flushingSoon > -1)\n return;\n let mutations = this.pendingRecords();\n if (mutations.length)\n this.queue = [];\n let sel = view.domSelectionRange();\n let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);\n let from = -1, to = -1, typeOver = false, added = [];\n if (view.editable) {\n for (let i = 0; i < mutations.length; i++) {\n let result = this.registerMutation(mutations[i], added);\n if (result) {\n from = from < 0 ? result.from : Math.min(result.from, from);\n to = to < 0 ? result.to : Math.max(result.to, to);\n if (result.typeOver)\n typeOver = true;\n }\n }\n }\n if (gecko && added.length) {\n let brs = added.filter(n => n.nodeName == \"BR\");\n if (brs.length == 2) {\n let [a, b] = brs;\n if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n b.remove();\n else\n a.remove();\n }\n else {\n let { focusNode } = this.currentSelection;\n for (let br of brs) {\n let parent = br.parentNode;\n if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n br.remove();\n }\n }\n }\n let readSel = null;\n // If it looks like the browser has reset the selection to the\n // start of the document after focus, restore the selection from\n // the state\n if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) &&\n readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n view.input.lastFocus = 0;\n selectionToDOM(view);\n this.currentSelection.set(sel);\n view.scrollToSelection();\n }\n else if (from > -1 || newSel) {\n if (from > -1) {\n view.docView.markDirty(from, to);\n checkCSS(view);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (view.docView && view.docView.dirty)\n view.updateState(view.state);\n else if (!this.currentSelection.eq(sel))\n selectionToDOM(view);\n this.currentSelection.set(sel);\n }\n }\n registerMutation(mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1)\n return null;\n let desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n return null;\n if (!desc || desc.ignoreMutation(mut))\n return null;\n if (mut.type == \"childList\") {\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let node = mut.addedNodes[i];\n added.push(node);\n if (node.nodeType == 3)\n this.lastChangedTextNode = node;\n }\n if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n return { from: desc.posBefore, to: desc.posAfter };\n let prev = mut.previousSibling, next = mut.nextSibling;\n if (ie && ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let { previousSibling, nextSibling } = mut.addedNodes[i];\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n prev = previousSibling;\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n next = nextSibling;\n }\n }\n let fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n let toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return { from, to };\n }\n else if (mut.type == \"attributes\") {\n return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n }\n else { // \"characterData\"\n this.lastChangedTextNode = mut.target;\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n };\n }\n }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n if (cssChecked.has(view))\n return;\n cssChecked.set(view, null);\n if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n view.requiresGeckoHackNode = gecko;\n if (cssCheckWarned)\n return;\n console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n cssCheckWarned = true;\n }\n}\nfunction rangeToSelectionRange(view, range) {\n let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n let focusNode = range.endContainer, focusOffset = range.endOffset;\n let currentAnchor = view.domAtPos(view.state.selection.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n if (selection.getComposedRanges) {\n let range = selection.getComposedRanges(view.root)[0];\n if (range)\n return rangeToSelectionRange(view, range);\n }\n let found;\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n // Because Safari (at least in 2018-2022) doesn't provide regular\n // access to the selection inside a shadowRoot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n view.dom.addEventListener(\"beforeinput\", read, true);\n document.execCommand(\"indent\");\n view.dom.removeEventListener(\"beforeinput\", read, true);\n return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n let desc = view.docView.nearestDesc(p, true);\n if (desc && desc.node.isBlock)\n return p;\n }\n return null;\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_) {\n let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n let domSel = view.domSelectionRange();\n let find;\n let anchor = domSel.anchorNode;\n if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {\n find = [{ node: anchor, offset: domSel.anchorOffset }];\n if (!selectionCollapsed(domSel))\n find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (chrome && view.input.lastKeyCode === 8) {\n for (let off = toOffset; off > fromOffset; off--) {\n let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeName == \"BR\" && !desc) {\n toOffset = off;\n break;\n }\n if (!desc || desc.size)\n break;\n }\n }\n let startDoc = view.state.doc;\n let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n let $from = startDoc.resolve(from);\n let sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n findPositions: find,\n ruleFromNode,\n context: $from\n });\n if (find && find[0].pos != null) {\n let anchor = find[0].pos, head = find[1] && find[1].pos;\n if (head == null)\n head = anchor;\n sel = { anchor: anchor + from, head: head + from };\n }\n return { doc, sel, from, to };\n}\nfunction ruleFromNode(dom) {\n let desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule();\n }\n else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n let skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return { skip };\n }\n else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return { ignore: true };\n }\n }\n else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return { ignore: true };\n }\n return null;\n}\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n view.input.compositionPendingChanges = 0;\n if (from < 0) {\n let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n let newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n if (chrome && android &&\n view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\"))))\n return;\n let tr = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n else if (origin == \"key\")\n tr.scrollIntoView();\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n return;\n }\n let $before = view.state.doc.resolve(from);\n let shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n let sel = view.state.selection;\n let parse = parseBetween(view, from, to);\n let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n let preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n }\n else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.input.lastKeyCode = null;\n let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (change)\n view.input.domChangeCount++;\n if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n addedNodes.some(n => n.nodeType == 1 && !isInline.test(n.nodeName)) &&\n (!change || change.endA >= change.endB) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = { start: sel.from, endA: sel.to, endB: sel.to };\n }\n else {\n if (parse.sel) {\n let sel = resolveSelection(view, view.state.doc, parse.sel);\n if (sel && !sel.eq(view.state.selection)) {\n let tr = view.state.tr.setSelection(sel);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n }\n return;\n }\n }\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n view.state.selection.from >= parse.from) {\n change.start = view.state.selection.from;\n }\n else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n view.state.selection.to <= parse.to) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (ie && ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n let $from = parse.doc.resolveNoCache(change.start - parse.from);\n let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n let $fromA = doc.resolve(change.start);\n let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n let nextSel;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n (!inlineChange && $from.pos < parse.doc.content.size && !$from.sameParent($to) &&\n (nextSel = Selection.findFrom(parse.doc.resolve($from.pos + 1), 1, true)) &&\n nextSel.head == $to.pos)) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n looksLikeBackspace(doc, change.start, change.endA, $from, $to) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\")))) {\n if (android && chrome)\n view.domObserver.suppressSelectionUpdates(); // #820\n return;\n }\n // Chrome will occasionally, during composition, delete the\n // entire composition and then immediately insert it again. This is\n // used to detect that situation.\n if (chrome && change.endB == change.start)\n view.input.lastChromeDelete = Date.now();\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(() => {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n let chFrom = change.start, chTo = change.endA;\n let tr, storedMarks, markChange;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (ie && ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(() => selectionToDOM(view), 20);\n }\n tr = view.state.tr.delete(chFrom, chTo);\n storedMarks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n }\n else if ( // Adding or removing a mark\n change.endA == change.endB &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n tr = view.state.tr;\n if (markChange.type == \"add\")\n tr.addMark(chFrom, chTo, markChange.mark);\n else\n tr.removeMark(chFrom, chTo, markChange.mark);\n }\n else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n if (view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text)))\n return;\n tr = view.state.tr.insertText(text, chFrom, chTo);\n }\n }\n if (!tr)\n tr = view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n if (parse.sel) {\n let sel = resolveSelection(view, tr.doc, parse.sel);\n // Chrome will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel && !(chrome && view.composing && sel.empty &&\n (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n ie && sel.empty && sel.head == chFrom))\n tr.setSelection(sel);\n }\n if (storedMarks)\n tr.ensureMarks(storedMarks);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr.scrollIntoView());\n}\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n return null;\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n let added = curMarks, removed = prevMarks, type, mark, update;\n for (let i = 0; i < prevMarks.length; i++)\n added = prevMarks[i].removeFromSet(added);\n for (let i = 0; i < curMarks.length; i++)\n removed = curMarks[i].removeFromSet(removed);\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = (node) => node.mark(mark.addToSet(node.marks));\n }\n else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = (node) => node.mark(mark.removeFromSet(node.marks));\n }\n else {\n return null;\n }\n let updated = [];\n for (let i = 0; i < prev.childCount; i++)\n updated.push(update(prev.child(i)));\n if (Fragment.from(updated).eq(cur))\n return { mark, type };\n}\nfunction looksLikeBackspace(old, start, end, $newStart, $newEnd) {\n if ( // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n return false;\n let $start = old.resolve(start);\n // Handle the case where, rather than joining blocks, the change just removed an entire block\n if (!$newStart.parent.isTextblock) {\n let after = $start.nodeAfter;\n return after != null && end == start + after.nodeSize;\n }\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n return false;\n let $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n return false;\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n let start = a.findDiffStart(b, pos);\n if (start == null)\n return null;\n let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size);\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && a.size < b.size) {\n let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endB = start + (endB - endA);\n endA = start;\n }\n else if (endB < start) {\n let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move;\n if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endA = start + (endA - endB);\n endB = start;\n }\n return { start, endA, endB };\n}\nfunction isSurrogatePair(str) {\n if (str.length != 2)\n return false;\n let a = str.charCodeAt(0), b = str.charCodeAt(1);\n return a >= 0xDC00 && a <= 0xDFFF && b >= 0xD800 && b <= 0xDBFF;\n}\n\n/**\n@internal\n*/\nconst __serializeForClipboard = serializeForClipboard;\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n /**\n Create a view. `place` may be a DOM node that the editor should\n be appended to, a function that will place it into the document,\n or an object whose `mount` property holds the node to use as the\n document container. If it is `null`, the editor will not be\n added to the document.\n */\n constructor(place, props) {\n this._root = null;\n /**\n @internal\n */\n this.focused = false;\n /**\n Kludge used to work around a Chrome bug @internal\n */\n this.trackWrites = null;\n this.mounted = false;\n /**\n @internal\n */\n this.markCursor = null;\n /**\n @internal\n */\n this.cursorWrapper = null;\n /**\n @internal\n */\n this.lastSelectedViewDesc = undefined;\n /**\n @internal\n */\n this.input = new InputState;\n this.prevDirectPlugins = [];\n this.pluginViews = [];\n /**\n Holds `true` when a hack node is needed in Firefox to prevent the\n [space is eaten issue](https://github.com/ProseMirror/prosemirror/issues/651)\n @internal\n */\n this.requiresGeckoHackNode = false;\n /**\n When editor content is being dragged, this object contains\n information about the dragged slice and whether it is being\n copied or moved. At any other time, it is null.\n */\n this.dragging = null;\n this._props = props;\n this.state = props.state;\n this.directPlugins = props.plugins || [];\n this.directPlugins.forEach(checkStateComponent);\n this.dispatch = this.dispatch.bind(this);\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild)\n place.appendChild(this.dom);\n else if (typeof place == \"function\")\n place(this.dom);\n else if (place.mount)\n this.mounted = true;\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n this.domObserver.start();\n initInput(this);\n this.updatePluginViews();\n }\n /**\n Holds `true` when a\n [composition](https://w3c.github.io/uievents/#events-compositionevents)\n is active.\n */\n get composing() { return this.input.composing; }\n /**\n The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n */\n get props() {\n if (this._props.state != this.state) {\n let prev = this._props;\n this._props = {};\n for (let name in prev)\n this._props[name] = prev[name];\n this._props.state = this.state;\n }\n return this._props;\n }\n /**\n Update the view's props. Will immediately cause an update to\n the DOM.\n */\n update(props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents)\n ensureListeners(this);\n let prevProps = this._props;\n this._props = props;\n if (props.plugins) {\n props.plugins.forEach(checkStateComponent);\n this.directPlugins = props.plugins;\n }\n this.updateStateInner(props.state, prevProps);\n }\n /**\n Update the view by updating existing props object with the object\n given as argument. Equivalent to `view.update(Object.assign({},\n view.props, props))`.\n */\n setProps(props) {\n let updated = {};\n for (let name in this._props)\n updated[name] = this._props[name];\n updated.state = this.state;\n for (let name in props)\n updated[name] = props[name];\n this.update(updated);\n }\n /**\n Update the editor's `state` prop, without touching any of the\n other props.\n */\n updateState(state) {\n this.updateStateInner(state, this._props);\n }\n updateStateInner(state, prevProps) {\n var _a;\n let prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n let nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n }\n if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n ensureListeners(this);\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection))\n updateSel = true;\n let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n if (this.composing)\n this.input.compositionNode = findCompositionNode(this);\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco(outerDeco);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && !this.trackWrites)\n forceSelUpdate = true;\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n if (forceSelUpdate ||\n !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n anchorInRightPlace(this))) {\n selectionToDOM(this, forceSelUpdate);\n }\n else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n this.updatePluginViews(prev);\n if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n this.updateDraggedNode(this.dragging, prev);\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n }\n else if (scroll == \"to selection\") {\n this.scrollToSelection();\n }\n else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n }\n /**\n @internal\n */\n scrollToSelection() {\n let startDOM = this.domSelectionRange().focusNode;\n if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n else if (this.state.selection instanceof NodeSelection) {\n let target = this.docView.domAfterPos(this.state.selection.from);\n if (target.nodeType == 1)\n scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n }\n else {\n scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n }\n }\n destroyPluginViews() {\n let view;\n while (view = this.pluginViews.pop())\n if (view.destroy)\n view.destroy();\n }\n updatePluginViews(prevState) {\n if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n this.prevDirectPlugins = this.directPlugins;\n this.destroyPluginViews();\n for (let i = 0; i < this.directPlugins.length; i++) {\n let plugin = this.directPlugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n for (let i = 0; i < this.state.plugins.length; i++) {\n let plugin = this.state.plugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n }\n else {\n for (let i = 0; i < this.pluginViews.length; i++) {\n let pluginView = this.pluginViews[i];\n if (pluginView.update)\n pluginView.update(this, prevState);\n }\n }\n }\n updateDraggedNode(dragging, prev) {\n let sel = dragging.node, found = -1;\n if (this.state.doc.nodeAt(sel.from) == sel.node) {\n found = sel.from;\n }\n else {\n let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);\n if (moved == sel.node)\n found = movedPos;\n }\n this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n }\n someProp(propName, f) {\n let prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n for (let i = 0; i < this.directPlugins.length; i++) {\n let prop = this.directPlugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n let plugins = this.state.plugins;\n if (plugins)\n for (let i = 0; i < plugins.length; i++) {\n let prop = plugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n }\n /**\n Query whether the view has focus.\n */\n hasFocus() {\n // Work around IE not handling focus correctly if resize handles are shown.\n // If the cursor is inside an element with resize handles, activeElement\n // will be that element instead of this.dom.\n if (ie) {\n // If activeElement is within this.dom, and there are no other elements\n // setting `contenteditable` to false in between, treat it as focused.\n let node = this.root.activeElement;\n if (node == this.dom)\n return true;\n if (!node || !this.dom.contains(node))\n return false;\n while (node && this.dom != node && this.dom.contains(node)) {\n if (node.contentEditable == 'false')\n return false;\n node = node.parentElement;\n }\n return true;\n }\n return this.root.activeElement == this.dom;\n }\n /**\n Focus the editor.\n */\n focus() {\n this.domObserver.stop();\n if (this.editable)\n focusPreventScroll(this.dom);\n selectionToDOM(this);\n this.domObserver.start();\n }\n /**\n Get the document root in which the editor exists. This will\n usually be the top-level `document`, but might be a [shadow\n DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n root if the editor is inside one.\n */\n get root() {\n let cached = this._root;\n if (cached == null)\n for (let search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection)\n Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n return this._root = search;\n }\n }\n return cached || document;\n }\n /**\n When an existing editor view is moved to a new document or\n shadow tree, call this to make it recompute its root.\n */\n updateRoot() {\n this._root = null;\n }\n /**\n Given a pair of viewport coordinates, return the document\n position that corresponds to them. May return null if the given\n coordinates aren't inside of the editor. When an object is\n returned, its `pos` property is the position nearest to the\n coordinates, and its `inside` property holds the position of the\n inner node that the position falls inside of, or -1 if it is at\n the top level, not in any node.\n */\n posAtCoords(coords) {\n return posAtCoords(this, coords);\n }\n /**\n Returns the viewport rectangle at a given document position.\n `left` and `right` will be the same number, as this returns a\n flat cursor-ish rectangle. If the position is between two things\n that aren't directly adjacent, `side` determines which element\n is used. When < 0, the element before the position is used,\n otherwise the element after.\n */\n coordsAtPos(pos, side = 1) {\n return coordsAtPos(this, pos, side);\n }\n /**\n Find the DOM position that corresponds to the given document\n position. When `side` is negative, find the position as close as\n possible to the content before the position. When positive,\n prefer positions close to the content after the position. When\n zero, prefer as shallow a position as possible.\n \n Note that you should **not** mutate the editor's internal DOM,\n only inspect it (and even that is usually not necessary).\n */\n domAtPos(pos, side = 0) {\n return this.docView.domFromPos(pos, side);\n }\n /**\n Find the DOM node that represents the document node after the\n given position. May return `null` when the position doesn't point\n in front of a node or if the node is inside an opaque node view.\n \n This is intended to be able to call things like\n `getBoundingClientRect` on that DOM node. Do **not** mutate the\n editor DOM directly, or add styling this way, since that will be\n immediately overriden by the editor as it redraws the node.\n */\n nodeDOM(pos) {\n let desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null;\n }\n /**\n Find the document position that corresponds to a given DOM\n position. (Whenever possible, it is preferable to inspect the\n document structure directly, rather than poking around in the\n DOM, but sometimes—for example when interpreting an event\n target—you don't have a choice.)\n \n The `bias` parameter can be used to influence which side of a DOM\n node to use when the position is inside a leaf node.\n */\n posAtDOM(node, offset, bias = -1) {\n let pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null)\n throw new RangeError(\"DOM position not inside the editor\");\n return pos;\n }\n /**\n Find out whether the selection is at the end of a textblock when\n moving in a given direction. When, for example, given `\"left\"`,\n it will return true if moving left from the current cursor\n position would leave that position's parent textblock. Will apply\n to the view's current state by default, but it is possible to\n pass a different state.\n */\n endOfTextblock(dir, state) {\n return endOfTextblock(this, state || this.state, dir);\n }\n /**\n Run the editor's paste logic with the given HTML string. The\n `event`, if given, will be passed to the\n [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n */\n pasteHTML(html, event) {\n return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Run the editor's paste logic with the given plain-text input.\n */\n pasteText(text, event) {\n return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Removes the editor from the DOM and destroys all [node\n views](https://prosemirror.net/docs/ref/#view.NodeView).\n */\n destroy() {\n if (!this.docView)\n return;\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n }\n else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n clearReusedRange();\n }\n /**\n This is true when the view has been\n [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n used anymore).\n */\n get isDestroyed() {\n return this.docView == null;\n }\n /**\n Used for testing.\n */\n dispatchEvent(event) {\n return dispatchEvent(this, event);\n }\n /**\n Dispatch a transaction. Will call\n [`dispatchTransaction`](https://prosemirror.net/docs/ref/#view.DirectEditorProps.dispatchTransaction)\n when given, and otherwise defaults to applying the transaction to\n the current state and calling\n [`updateState`](https://prosemirror.net/docs/ref/#view.EditorView.updateState) with the result.\n This method is bound to the view instance, so that it can be\n easily passed around.\n */\n dispatch(tr) {\n let dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction)\n dispatchTransaction.call(this, tr);\n else\n this.updateState(this.state.apply(tr));\n }\n /**\n @internal\n */\n domSelectionRange() {\n let sel = this.domSelection();\n if (!sel)\n return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n return safari && this.root.nodeType === 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n }\n /**\n @internal\n */\n domSelection() {\n return this.root.getSelection();\n }\n}\nfunction computeDocDeco(view) {\n let attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n view.someProp(\"attributes\", value => {\n if (typeof value == \"function\")\n value = value(view.state);\n if (value)\n for (let attr in value) {\n if (attr == \"class\")\n attrs.class += \" \" + value[attr];\n else if (attr == \"style\")\n attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n attrs[attr] = String(value[attr]);\n }\n });\n if (!attrs.translate)\n attrs.translate = \"no\";\n return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n let dom = document.createElement(\"img\");\n dom.className = \"ProseMirror-separator\";\n dom.setAttribute(\"mark-placeholder\", \"true\");\n dom.setAttribute(\"alt\", \"\");\n view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n }\n else {\n view.cursorWrapper = null;\n }\n}\nfunction getEditable(view) {\n return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n let result = Object.create(null);\n function add(obj) {\n for (let prop in obj)\n if (!Object.prototype.hasOwnProperty.call(result, prop))\n result[prop] = obj[prop];\n }\n view.someProp(\"nodeViews\", add);\n view.someProp(\"markViews\", add);\n return result;\n}\nfunction changedNodeViews(a, b) {\n let nA = 0, nB = 0;\n for (let prop in a) {\n if (a[prop] != b[prop])\n return true;\n nA++;\n }\n for (let _ in b)\n nB++;\n return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard, __serializeForClipboard };\n","export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n // On IE, shift effect is never included in `.key`.\n var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n ie && event.shiftKey && event.key && event.key.length == 1 ||\n event.key == \"Unidentified\"\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n","import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n for (let j = 0; childA.text[j] == childB.text[j]; j++)\n pos++;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++;\n posA--;\n posB--;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n else\n child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos, round = -1) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos || round > 0)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return new Fragment(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n type.checkAttrs(mark.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/*\nReplaceError = function(this: any, message: string) {\n let err = Error.call(this, message)\n ;(err as any).__proto__ = ReplaceError.prototype\n return err\n} as any\n\nReplaceError.prototype = Object.create(Error.prototype)\nReplaceError.prototype.constructor = ReplaceError\nReplaceError.prototype.name = \"ReplaceError\"\n*/\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n target[last] = child.withText(target[last].text + child.text);\n else\n target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n node.type.checkContent(content);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n }\n else {\n if (openStart)\n addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd)\n addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--)\n node = $along.node(i).copy(Fragment.from(node));\n return { start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++)\n str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively between\n the given two positions that are relative to start of this\n node's content. The callback is invoked with the node, its\n position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec^leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n this.type.checkAttrs(this.attrs);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n mark.type.checkAttrs(mark.attrs);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size)\n obj.content = this.content.toJSON();\n if (this.marks.length)\n obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n node.type.checkAttrs(node.attrs);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n stream.err(\"Mixing inline and block content\");\n return { type: \"name\", value: type };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let given = value && value[name];\n if (given === undefined) {\n let attr = attrs[name];\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n built[name] = given;\n }\n return built;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let name in values)\n if (!(name in attrs))\n throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);\n for (let name in attrs) {\n let attr = attrs[name];\n if (attr.validate)\n attr.validate(values[name]);\n }\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"node\", this.name);\n }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"mark\", this.name);\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = this.nodeFromJSON.bind(this);\n this.markFromJSON = this.markFromJSON.bind(this);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\")\n type = this.nodeType(type);\n else if (!(type instanceof NodeType))\n throw new RangeError(\"Invalid node type: \" + type);\n else if (type.schema != this)\n throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n Deserialize a node from its JSON representation. This method is\n bound.\n */\n nodeFromJSON(json) {\n return Node.fromJSON(this, json);\n }\n /**\n Deserialize a mark from its JSON representation. This method is\n bound.\n */\n markFromJSON(json) {\n return Mark.fromJSON(this, json);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.ParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match)\n content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n value = value.slice(1);\n }\n }\n else if (preserveWS !== \"full\") {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n else {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n if (value)\n this.insertNode(this.parser.schema.text(value), marks);\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks)) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node, marks) {\n let route, sync;\n for (let depth = this.open; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid)\n break;\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n if (structure.nodeType != null)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType != null)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n throw new RangeError(\"Content hole must be the only child of its parent node\");\n return { dom, contentDOM: dom };\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n","import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(\n /**\n The step maps in this mapping.\n */\n maps = [], \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps.length) {\n this.maps = maps;\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this.maps, this.mirror, from, to);\n }\n /**\n @internal\n */\n copy() {\n return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n this.to = this.maps.push(map);\n if (mirrors != null)\n this.setMirror(this.maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this.maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this.maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this.maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let removed = [], added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n removing.to = end;\n else\n removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start)\n adding.to = end;\n else\n added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth), endIndex = range.$to.indexAfter(depth);\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf)\n return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, tr.doc.resolve(to));\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or a mark of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n if (!(mark instanceof Mark)) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n mark = mark.isInSet(node.marks);\n if (!mark)\n return this;\n }\n this.step(new RemoveNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split.\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n","import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n to = to == null ? from : to;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Start a [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n","import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : false;\nfunction normalizeKeyName(name) {\n let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n if (result == \"Space\")\n result = \" \";\n let alt, ctrl, shift, meta;\n for (let i = 0; i < parts.length - 1; i++) {\n let mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod))\n meta = true;\n else if (/^a(lt)?$/i.test(mod))\n alt = true;\n else if (/^(c|ctrl|control)$/i.test(mod))\n ctrl = true;\n else if (/^s(hift)?$/i.test(mod))\n shift = true;\n else if (/^mod$/i.test(mod)) {\n if (mac)\n meta = true;\n else\n ctrl = true;\n }\n else\n throw new Error(\"Unrecognized modifier name: \" + mod);\n }\n if (alt)\n result = \"Alt-\" + result;\n if (ctrl)\n result = \"Ctrl-\" + result;\n if (meta)\n result = \"Meta-\" + result;\n if (shift)\n result = \"Shift-\" + result;\n return result;\n}\nfunction normalize(map) {\n let copy = Object.create(null);\n for (let prop in map)\n copy[normalizeKeyName(prop)] = map[prop];\n return copy;\n}\nfunction modifiers(name, event, shift = true) {\n if (event.altKey)\n name = \"Alt-\" + name;\n if (event.ctrlKey)\n name = \"Ctrl-\" + name;\n if (event.metaKey)\n name = \"Meta-\" + name;\n if (shift && event.shiftKey)\n name = \"Shift-\" + name;\n return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`—a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n let map = normalize(bindings);\n return function (view, event) {\n let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n if (direct && direct(view.state, view.dispatch, view))\n return true;\n // A character key\n if (name.length == 1 && name != \" \") {\n if (event.shiftKey) {\n // In case the name was already modified by shift, try looking\n // it up without its shift modifier\n let noShift = map[modifiers(name, event, false)];\n if (noShift && noShift(view.state, view.dispatch, view))\n return true;\n }\n if ((event.shiftKey || event.altKey || event.metaKey || name.charCodeAt(0) > 127) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n // Try falling back to the keyCode when there's a modifier\n // active or the character produced isn't ASCII, and our table\n // produces a different name from the the keyCode. See #668,\n // #1060\n let fromCode = map[modifiers(baseName, event)];\n if (fromCode && fromCode(view.state, view.dispatch, view))\n return true;\n }\n }\n return false;\n };\n}\n\nexport { keydownHandler, keymap };\n","import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n if (state.selection.empty)\n return false;\n if (dispatch)\n dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n};\nfunction atBlockStart(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n : $cursor.parentOffset > 0))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it—if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n // If there is no node before this, try to lift\n if (!$cut) {\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n let before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, -1))\n return true;\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n for (let depth = $cursor.depth;; depth--) {\n let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(before, \"end\")\n ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n break;\n }\n }\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nA more limited form of [`joinBackward`]($commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`]($commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n for (; !beforeText.isTextblock; beforePos--) {\n if (beforeText.type.spec.isolating)\n return false;\n let child = beforeText.lastChild;\n if (!child)\n return false;\n beforeText = child;\n }\n let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n for (; !afterText.isTextblock; afterPos++) {\n if (afterText.type.spec.isolating)\n return false;\n let child = afterText.firstChild;\n if (!child)\n return false;\n afterText = child;\n }\n let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n if (!step || step.from != beforePos ||\n step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n return false;\n if (dispatch) {\n let tr = state.tr.step(step);\n tr.setSelection(TextSelection.create(tr.doc, beforePos));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\nfunction textblockAt(node, side, only = false) {\n for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n if (scan.isTextblock)\n return true;\n if (only && scan.childCount != 1)\n return false;\n }\n return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n return false;\n $cut = findCutBefore($head);\n }\n let node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n return true;\n};\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0)\n return $pos.doc.resolve($pos.before(i + 1));\n if ($pos.node(i).type.spec.isolating)\n break;\n }\n return null;\n}\nfunction atBlockEnd(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n : $cursor.parentOffset < $cursor.parent.content.size))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n // If there is no node after this, there's nothing to do\n if (!$cut)\n return false;\n let after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, 1))\n return true;\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n return false;\n $cut = findCutAfter($head);\n }\n let node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n return true;\n};\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n let parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount)\n return $pos.doc.resolve($pos.after(i + 1));\n if (parent.type.spec.isolating)\n break;\n }\n return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n return false;\n point = sel.from;\n }\n else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null)\n return false;\n }\n if (dispatch) {\n let tr = state.tr.join(point);\n if (nodeSel)\n tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n let sel = state.selection, point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n return false;\n point = sel.to;\n }\n else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null)\n return false;\n }\n if (dispatch)\n dispatch(state.tr.join(point).scrollIntoView());\n return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n if (dispatch)\n dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n return true;\n};\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i++) {\n let { type } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs())\n return type;\n }\n return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n if (!type || !above.canReplaceWith(after, after, type))\n return false;\n if (dispatch) {\n let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n let sel = state.selection, { $from, $to } = sel;\n if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n return false;\n let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock)\n return false;\n if (dispatch) {\n let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n let tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n let { $cursor } = state.selection;\n if (!$cursor || $cursor.parent.content.size)\n return false;\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n let before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch)\n dispatch(state.tr.split(before).scrollIntoView());\n return true;\n }\n }\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n return (state, dispatch) => {\n let { $from, $to } = state.selection;\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n return false;\n if (dispatch)\n dispatch(state.tr.split($from.pos).scrollIntoView());\n return true;\n }\n if (!$from.depth)\n return false;\n let types = [];\n let splitDepth, deflt, atEnd = false, atStart = false;\n for (let d = $from.depth;; d--) {\n let node = $from.node(d);\n if (node.isBlock) {\n atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n atStart = $from.start(d) == $from.pos - ($from.depth - d);\n deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n let splitType = splitNode && splitNode($to.parent, atEnd, $from);\n types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n splitDepth = d;\n break;\n }\n else {\n if (d == 1)\n return false;\n types.unshift(null);\n }\n }\n let tr = state.tr;\n if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)\n tr.deleteSelection();\n let splitPos = tr.mapping.map($from.pos);\n let can = canSplit(tr.doc, splitPos, types.length, types);\n if (!can) {\n types[0] = deflt ? { type: deflt } : null;\n can = canSplit(tr.doc, splitPos, types.length, types);\n }\n tr.split(splitPos, types.length, types);\n if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n let first = tr.mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt);\n }\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n return splitBlock(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n let { $from, to } = state.selection, pos;\n let same = $from.sharedDepth(to);\n if (same == 0)\n return false;\n pos = $from.before(same);\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n if (dispatch)\n dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type))\n return false;\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch)\n dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n return true;\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n return false;\n if (dispatch)\n dispatch(state.tr.join($pos.pos).scrollIntoView());\n return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n let isolated = before.type.spec.isolating || after.type.spec.isolating;\n if (!isolated && joinMaybeClear(state, $cut, dispatch))\n return true;\n let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n if (canDelAfter &&\n (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n for (let i = conn.length - 1; i >= 0; i--)\n wrap = Fragment.from(conn[i].create(null, wrap));\n wrap = Fragment.from(before.copy(wrap));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n canJoin(tr.doc, $joinAt.pos))\n tr.join($joinAt.pos);\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n let at = before, wrap = [];\n for (;;) {\n wrap.push(at);\n if (at.isTextblock)\n break;\n at = at.lastChild;\n }\n let afterText = after, afterDepth = 1;\n for (; !afterText.isTextblock; afterText = afterText.firstChild)\n afterDepth++;\n if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n if (dispatch) {\n let end = Fragment.empty;\n for (let i = wrap.length - 1; i >= 0; i--)\n end = Fragment.from(wrap[i].copy(end));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n return false;\n}\nfunction selectTextblockSide(side) {\n return function (state, dispatch) {\n let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n let depth = $pos.depth;\n while ($pos.node(depth).isInline) {\n if (!depth)\n return false;\n depth--;\n }\n if (!$pos.node(depth).isTextblock)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n return true;\n };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping)\n return false;\n if (dispatch)\n dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n return true;\n };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n return function (state, dispatch) {\n let applicable = false;\n for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (applicable)\n return false;\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n return;\n if (node.type == nodeType) {\n applicable = true;\n }\n else {\n let $pos = state.doc.resolve(pos), index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n }\n if (!applicable)\n return false;\n if (dispatch) {\n let tr = state.tr;\n for (let i = 0; i < state.selection.ranges.length; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n tr.setBlockType(from, to, nodeType, attrs);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n return false;\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can)\n return true;\n }\n return false;\n}\nfunction removeInlineAtoms(ranges) {\n let result = [];\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n if (pos + 1 > $from.pos)\n result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n $from = $from.doc.resolve(pos + 1 + node.content.size);\n return false;\n }\n });\n if ($from.pos < $to.pos)\n result.push(new SelectionRange($from, $to));\n }\n return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n let enterAtoms = (options && options.enterInlineAtoms) !== false;\n return function (state, dispatch) {\n let { empty, $cursor, ranges } = state.selection;\n if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n return false;\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks()))\n dispatch(state.tr.removeStoredMark(markType));\n else\n dispatch(state.tr.addStoredMark(markType.create(attrs)));\n }\n else {\n let add, tr = state.tr;\n if (!enterAtoms)\n ranges = removeInlineAtoms(ranges);\n if (removeWhenPresent) {\n add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n }\n else {\n add = !ranges.every(r => {\n let missing = false;\n tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n if (missing)\n return false;\n missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n });\n return !missing;\n });\n }\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n if (!add) {\n tr.removeMark($from.pos, $to.pos, markType);\n }\n else {\n let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n let spaceStart = start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n let spaceEnd = end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n if (from + spaceStart < to) {\n from += spaceStart;\n to -= spaceEnd;\n }\n tr.addMark(from, to, markType.create(attrs));\n }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true;\n };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return (tr) => {\n if (!tr.isGeneric)\n return dispatch(tr);\n let ranges = [];\n for (let i = 0; i < tr.mapping.maps.length; i++) {\n let map = tr.mapping.maps[i];\n for (let j = 0; j < ranges.length; j++)\n ranges[j] = map.map(ranges[j]);\n map.forEach((_s, _e, from, to) => ranges.push(from, to));\n }\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n let joinable = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = ranges[i], to = ranges[i + 1];\n let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n let after = parent.maybeChild(index);\n if (!after)\n break;\n if (index && joinable.indexOf(pos) == -1) {\n let before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after))\n joinable.push(pos);\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort((a, b) => a - b);\n for (let i = joinable.length - 1; i >= 0; i--) {\n if (canJoin(tr.doc, joinable[i]))\n tr.join(joinable[i]);\n }\n dispatch(tr);\n };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n : isJoinable;\n return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n return function (state, dispatch, view) {\n for (let i = 0; i < commands.length; i++)\n if (commands[i](state, dispatch, view))\n return true;\n return false;\n };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Shift-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n \"Ctrl-a\": selectTextblockStart,\n \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n // @ts-ignore\n : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n","var GOOD_LEAF_SIZE = 200;\n\n// :: class A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n if (!other.length) { return this }\n other = RopeSequence.from(other);\n\n return (!this.length && other) ||\n (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence>) → RopeSequence\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n if (!other.length) { return this }\n return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n return new Append(this, other)\n};\n\n// :: (?number, ?number) → RopeSequence\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from >= to) { return RopeSequence.empty }\n return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) → T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n if (i < 0 || i >= this.length) { return undefined }\n return this.getInner(i)\n};\n\n// :: ((element: T, index: number) → ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from <= to)\n { this.forEachInner(f, from, to, 0); }\n else\n { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) → U, ?number, ?number) → [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n var result = [];\n this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n return result\n};\n\n// :: (?union<[T], RopeSequence>) → RopeSequence\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n if (values instanceof RopeSequence) { return values }\n return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n function Leaf(values) {\n RopeSequence.call(this);\n this.values = values;\n }\n\n if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Leaf.prototype.constructor = Leaf;\n\n var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n Leaf.prototype.flatten = function flatten () {\n return this.values\n };\n\n Leaf.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n return new Leaf(this.values.slice(from, to))\n };\n\n Leaf.prototype.getInner = function getInner (i) {\n return this.values[i]\n };\n\n Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n for (var i = from; i < to; i++)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n for (var i = from - 1; i >= to; i--)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.leafAppend = function leafAppend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(this.values.concat(other.flatten())) }\n };\n\n Leaf.prototype.leafPrepend = function leafPrepend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(other.flatten().concat(this.values)) }\n };\n\n prototypeAccessors.length.get = function () { return this.values.length };\n\n prototypeAccessors.depth.get = function () { return 0 };\n\n Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n function Append(left, right) {\n RopeSequence.call(this);\n this.left = left;\n this.right = right;\n this.length = left.length + right.length;\n this.depth = Math.max(left.depth, right.depth) + 1;\n }\n\n if ( RopeSequence ) Append.__proto__ = RopeSequence;\n Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Append.prototype.constructor = Append;\n\n Append.prototype.flatten = function flatten () {\n return this.left.flatten().concat(this.right.flatten())\n };\n\n Append.prototype.getInner = function getInner (i) {\n return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n };\n\n Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from < leftLen &&\n this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n { return false }\n if (to > leftLen &&\n this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n { return false }\n };\n\n Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from > leftLen &&\n this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n { return false }\n if (to < leftLen &&\n this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n { return false }\n };\n\n Append.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n var leftLen = this.left.length;\n if (to <= leftLen) { return this.left.slice(from, to) }\n if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n };\n\n Append.prototype.leafAppend = function leafAppend (other) {\n var inner = this.right.leafAppend(other);\n if (inner) { return new Append(this.left, inner) }\n };\n\n Append.prototype.leafPrepend = function leafPrepend (other) {\n var inner = this.left.leafPrepend(other);\n if (inner) { return new Append(inner, this.right) }\n };\n\n Append.prototype.appendInner = function appendInner (other) {\n if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n { return new Append(this.left, new Append(this.right, other)) }\n return new Append(this, other)\n };\n\n return Append;\n}(RopeSequence));\n\nexport default RopeSequence;\n","import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' — a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n constructor(items, eventCount) {\n this.items = items;\n this.eventCount = eventCount;\n }\n // Pop the latest event off the branch's history and apply it\n // to a document transform.\n popEvent(state, preserveItems) {\n if (this.eventCount == 0)\n return null;\n let end = this.items.length;\n for (;; end--) {\n let next = this.items.get(end - 1);\n if (next.selection) {\n --end;\n break;\n }\n }\n let remap, mapFrom;\n if (preserveItems) {\n remap = this.remapping(end, this.items.length);\n mapFrom = remap.maps.length;\n }\n let transform = state.tr;\n let selection, remaining;\n let addAfter = [], addBefore = [];\n this.items.forEach((item, i) => {\n if (!item.step) {\n if (!remap) {\n remap = this.remapping(end, i + 1);\n mapFrom = remap.maps.length;\n }\n mapFrom--;\n addBefore.push(item);\n return;\n }\n if (remap) {\n addBefore.push(new Item(item.map));\n let step = item.step.map(remap.slice(mapFrom)), map;\n if (step && transform.maybeStep(step).doc) {\n map = transform.mapping.maps[transform.mapping.maps.length - 1];\n addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n }\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n }\n else {\n transform.maybeStep(item.step);\n }\n if (item.selection) {\n selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n return false;\n }\n }, this.items.length, 0);\n return { remaining: remaining, transform, selection: selection };\n }\n // Create a new branch with the given transform added.\n addTransform(transform, selection, histOptions, preserveItems) {\n let newItems = [], eventCount = this.eventCount;\n let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n for (let i = 0; i < transform.steps.length; i++) {\n let step = transform.steps[i].invert(transform.docs[i]);\n let item = new Item(transform.mapping.maps[i], step, selection), merged;\n if (merged = lastItem && lastItem.merge(item)) {\n item = merged;\n if (i)\n newItems.pop();\n else\n oldItems = oldItems.slice(0, oldItems.length - 1);\n }\n newItems.push(item);\n if (selection) {\n eventCount++;\n selection = undefined;\n }\n if (!preserveItems)\n lastItem = item;\n }\n let overflow = eventCount - histOptions.depth;\n if (overflow > DEPTH_OVERFLOW) {\n oldItems = cutOffEvents(oldItems, overflow);\n eventCount -= overflow;\n }\n return new Branch(oldItems.append(newItems), eventCount);\n }\n remapping(from, to) {\n let maps = new Mapping;\n this.items.forEach((item, i) => {\n let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n ? maps.maps.length - item.mirrorOffset : undefined;\n maps.appendMap(item.map, mirrorPos);\n }, from, to);\n return maps;\n }\n addMaps(array) {\n if (this.eventCount == 0)\n return this;\n return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n }\n // When the collab module receives remote changes, the history has\n // to know about those, so that it can adjust the steps that were\n // rebased on top of the remote changes, and include the position\n // maps for the remote changes in its array of items.\n rebased(rebasedTransform, rebasedCount) {\n if (!this.eventCount)\n return this;\n let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);\n let mapping = rebasedTransform.mapping;\n let newUntil = rebasedTransform.steps.length;\n let eventCount = this.eventCount;\n this.items.forEach(item => { if (item.selection)\n eventCount--; }, start);\n let iRebased = rebasedCount;\n this.items.forEach(item => {\n let pos = mapping.getMirror(--iRebased);\n if (pos == null)\n return;\n newUntil = Math.min(newUntil, pos);\n let map = mapping.maps[pos];\n if (item.step) {\n let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n if (selection)\n eventCount++;\n rebasedItems.push(new Item(map, step, selection));\n }\n else {\n rebasedItems.push(new Item(map));\n }\n }, start);\n let newMaps = [];\n for (let i = rebasedCount; i < newUntil; i++)\n newMaps.push(new Item(mapping.maps[i]));\n let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n let branch = new Branch(items, eventCount);\n if (branch.emptyItemCount() > max_empty_items)\n branch = branch.compress(this.items.length - rebasedItems.length);\n return branch;\n }\n emptyItemCount() {\n let count = 0;\n this.items.forEach(item => { if (!item.step)\n count++; });\n return count;\n }\n // Compressing a branch means rewriting it to push the air (map-only\n // items) out. During collaboration, these naturally accumulate\n // because each remote change adds one. The `upto` argument is used\n // to ensure that only the items below a given level are compressed,\n // because `rebased` relies on a clean, untouched set of items in\n // order to associate old items with rebased steps.\n compress(upto = this.items.length) {\n let remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n let items = [], events = 0;\n this.items.forEach((item, i) => {\n if (i >= upto) {\n items.push(item);\n if (item.selection)\n events++;\n }\n else if (item.step) {\n let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n if (step) {\n let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n if (selection)\n events++;\n let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n if (merged = items.length && items[last].merge(newItem))\n items[last] = merged;\n else\n items.push(newItem);\n }\n }\n else if (item.map) {\n mapFrom--;\n }\n }, this.items.length, 0);\n return new Branch(RopeSequence.from(items.reverse()), events);\n }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n let cutPoint;\n items.forEach((item, i) => {\n if (item.selection && (n-- == 0)) {\n cutPoint = i;\n return false;\n }\n });\n return items.slice(cutPoint);\n}\nclass Item {\n constructor(\n // The (forward) step map for this item.\n map, \n // The inverted step\n step, \n // If this is non-null, this item is the start of a group, and\n // this selection is the starting selection for the group (the one\n // that was active before the first step was applied)\n selection, \n // If this item is the inverse of a previous mapping on the stack,\n // this points at the inverse's offset\n mirrorOffset) {\n this.map = map;\n this.step = step;\n this.selection = selection;\n this.mirrorOffset = mirrorOffset;\n }\n merge(other) {\n if (this.step && other.step && !other.selection) {\n let step = other.step.merge(this.step);\n if (step)\n return new Item(step.getMap().invert(), step, this.selection);\n }\n }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n constructor(done, undone, prevRanges, prevTime, prevComposition) {\n this.done = done;\n this.undone = undone;\n this.prevRanges = prevRanges;\n this.prevTime = prevTime;\n this.prevComposition = prevComposition;\n }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n let historyTr = tr.getMeta(historyKey), rebased;\n if (historyTr)\n return historyTr.historyState;\n if (tr.getMeta(closeHistoryKey))\n history = new HistoryState(history.done, history.undone, null, 0, -1);\n let appended = tr.getMeta(\"appendedTransaction\");\n if (tr.steps.length == 0) {\n return history;\n }\n else if (appended && appended.getMeta(historyKey)) {\n if (appended.getMeta(historyKey).redo)\n return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);\n else\n return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n }\n else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n // Group transforms that occur in quick succession into one event.\n let composition = tr.getMeta(\"composition\");\n let newGroup = history.prevTime == 0 ||\n (!appended && history.prevComposition != composition &&\n (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges)));\n let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n }\n else if (rebased = tr.getMeta(\"rebased\")) {\n // Used by the collab module to tell the history that some of its\n // content has been rebased.\n return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n else {\n return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n if (!prevRanges)\n return false;\n if (!transform.docChanged)\n return true;\n let adjacent = false;\n transform.mapping.maps[0].forEach((start, end) => {\n for (let i = 0; i < prevRanges.length; i += 2)\n if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n adjacent = true;\n });\n return adjacent;\n}\nfunction rangesFor(maps) {\n let result = [];\n for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)\n maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n return result;\n}\nfunction mapRanges(ranges, mapping) {\n if (!ranges)\n return null;\n let result = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n if (from <= to)\n result.push(from, to);\n }\n return result;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n let preserveItems = mustPreserveItems(state);\n let histOptions = historyKey.get(state).spec.config;\n let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop)\n return null;\n let selection = pop.selection.resolve(pop.transform.doc);\n let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);\n let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n return pop.transform.setSelection(selection).setMeta(historyKey, { redo, historyState: newHist });\n}\nlet cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n let plugins = state.plugins;\n if (cachedPreserveItemsPlugins != plugins) {\n cachedPreserveItems = false;\n cachedPreserveItemsPlugins = plugins;\n for (let i = 0; i < plugins.length; i++)\n if (plugins[i].spec.historyPreserveItems) {\n cachedPreserveItems = true;\n break;\n }\n }\n return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n config = { depth: config.depth || 100,\n newGroupDelay: config.newGroupDelay || 500 };\n return new Plugin({\n key: historyKey,\n state: {\n init() {\n return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n },\n apply(tr, hist, state) {\n return applyTransaction(hist, state, tr, config);\n }\n },\n config,\n props: {\n handleDOMEvents: {\n beforeinput(view, e) {\n let inputType = e.inputType;\n let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n if (!command)\n return false;\n e.preventDefault();\n return command(view.state, view.dispatch);\n }\n }\n }\n });\n}\nfunction buildCommand(redo, scroll) {\n return (state, dispatch) => {\n let hist = historyKey.getState(state);\n if (!hist || (redo ? hist.undone : hist.done).eventCount == 0)\n return false;\n if (dispatch) {\n let tr = histTransaction(hist, state, redo);\n if (tr)\n dispatch(scroll ? tr.scrollIntoView() : tr);\n }\n return true;\n };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.undone.eventCount : 0;\n}\n\nexport { closeHistory, history, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };\n","export default function crelt() {\n var elt = arguments[0]\n if (typeof elt == \"string\") elt = document.createElement(elt)\n var i = 1, next = arguments[1]\n if (next && typeof next == \"object\" && next.nodeType == null && !Array.isArray(next)) {\n for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {\n var value = next[name]\n if (typeof value == \"string\") elt.setAttribute(name, value)\n else if (value != null) elt[name] = value\n }\n i++\n }\n for (; i < arguments.length; i++) add(elt, arguments[i])\n return elt\n}\n\nfunction add(elt, child) {\n if (typeof child == \"string\") {\n elt.appendChild(document.createTextNode(child))\n } else if (child == null) {\n } else if (child.nodeType != null) {\n elt.appendChild(child)\n } else if (Array.isArray(child)) {\n for (var i = 0; i < child.length; i++) add(elt, child[i])\n } else {\n throw new RangeError(\"Unsupported child node: \" + child)\n }\n}\n","import crel from 'crelt';\nimport { joinUp, lift, selectParentNode, setBlockType, wrapIn } from 'prosemirror-commands';\nimport { undo, redo } from 'prosemirror-history';\nimport { Plugin } from 'prosemirror-state';\n\nconst SVG = \"http://www.w3.org/2000/svg\";\nconst XLINK = \"http://www.w3.org/1999/xlink\";\nconst prefix$2 = \"ProseMirror-icon\";\nfunction hashPath(path) {\n let hash = 0;\n for (let i = 0; i < path.length; i++)\n hash = (((hash << 5) - hash) + path.charCodeAt(i)) | 0;\n return hash;\n}\nfunction getIcon(root, icon) {\n let doc = (root.nodeType == 9 ? root : root.ownerDocument) || document;\n let node = doc.createElement(\"div\");\n node.className = prefix$2;\n if (icon.path) {\n let { path, width, height } = icon;\n let name = \"pm-icon-\" + hashPath(path).toString(16);\n if (!doc.getElementById(name))\n buildSVG(root, name, icon);\n let svg = node.appendChild(doc.createElementNS(SVG, \"svg\"));\n svg.style.width = (width / height) + \"em\";\n let use = svg.appendChild(doc.createElementNS(SVG, \"use\"));\n use.setAttributeNS(XLINK, \"href\", /([^#]*)/.exec(doc.location.toString())[1] + \"#\" + name);\n }\n else if (icon.dom) {\n node.appendChild(icon.dom.cloneNode(true));\n }\n else {\n let { text, css } = icon;\n node.appendChild(doc.createElement(\"span\")).textContent = text || '';\n if (css)\n node.firstChild.style.cssText = css;\n }\n return node;\n}\nfunction buildSVG(root, name, data) {\n let [doc, top] = root.nodeType == 9 ? [root, root.body] : [root.ownerDocument || document, root];\n let collection = doc.getElementById(prefix$2 + \"-collection\");\n if (!collection) {\n collection = doc.createElementNS(SVG, \"svg\");\n collection.id = prefix$2 + \"-collection\";\n collection.style.display = \"none\";\n top.insertBefore(collection, top.firstChild);\n }\n let sym = doc.createElementNS(SVG, \"symbol\");\n sym.id = name;\n sym.setAttribute(\"viewBox\", \"0 0 \" + data.width + \" \" + data.height);\n let path = sym.appendChild(doc.createElementNS(SVG, \"path\"));\n path.setAttribute(\"d\", data.path);\n collection.appendChild(sym);\n}\n\nconst prefix$1 = \"ProseMirror-menu\";\n/**\nAn icon or label that, when clicked, executes a command.\n*/\nclass MenuItem {\n /**\n Create a menu item.\n */\n constructor(\n /**\n The spec used to create this item.\n */\n spec) {\n this.spec = spec;\n }\n /**\n Renders the icon according to its [display\n spec](https://prosemirror.net/docs/ref/#menu.MenuItemSpec.display), and adds an event handler which\n executes the command when the representation is clicked.\n */\n render(view) {\n let spec = this.spec;\n let dom = spec.render ? spec.render(view)\n : spec.icon ? getIcon(view.root, spec.icon)\n : spec.label ? crel(\"div\", null, translate(view, spec.label))\n : null;\n if (!dom)\n throw new RangeError(\"MenuItem without icon or label property\");\n if (spec.title) {\n const title = (typeof spec.title === \"function\" ? spec.title(view.state) : spec.title);\n dom.setAttribute(\"title\", translate(view, title));\n }\n if (spec.class)\n dom.classList.add(spec.class);\n if (spec.css)\n dom.style.cssText += spec.css;\n dom.addEventListener(\"mousedown\", e => {\n e.preventDefault();\n if (!dom.classList.contains(prefix$1 + \"-disabled\"))\n spec.run(view.state, view.dispatch, view, e);\n });\n function update(state) {\n if (spec.select) {\n let selected = spec.select(state);\n dom.style.display = selected ? \"\" : \"none\";\n if (!selected)\n return false;\n }\n let enabled = true;\n if (spec.enable) {\n enabled = spec.enable(state) || false;\n setClass(dom, prefix$1 + \"-disabled\", !enabled);\n }\n if (spec.active) {\n let active = enabled && spec.active(state) || false;\n setClass(dom, prefix$1 + \"-active\", active);\n }\n return true;\n }\n return { dom, update };\n }\n}\nfunction translate(view, text) {\n return view._props.translate ? view._props.translate(text) : text;\n}\nlet lastMenuEvent = { time: 0, node: null };\nfunction markMenuEvent(e) {\n lastMenuEvent.time = Date.now();\n lastMenuEvent.node = e.target;\n}\nfunction isMenuEvent(wrapper) {\n return Date.now() - 100 < lastMenuEvent.time &&\n lastMenuEvent.node && wrapper.contains(lastMenuEvent.node);\n}\n/**\nA drop-down menu, displayed as a label with a downwards-pointing\ntriangle to the right of it.\n*/\nclass Dropdown {\n /**\n Create a dropdown wrapping the elements.\n */\n constructor(content, \n /**\n @internal\n */\n options = {}) {\n this.options = options;\n this.options = options || {};\n this.content = Array.isArray(content) ? content : [content];\n }\n /**\n Render the dropdown menu and sub-items.\n */\n render(view) {\n let content = renderDropdownItems(this.content, view);\n let win = view.dom.ownerDocument.defaultView || window;\n let label = crel(\"div\", { class: prefix$1 + \"-dropdown \" + (this.options.class || \"\"),\n style: this.options.css }, translate(view, this.options.label || \"\"));\n if (this.options.title)\n label.setAttribute(\"title\", translate(view, this.options.title));\n let wrap = crel(\"div\", { class: prefix$1 + \"-dropdown-wrap\" }, label);\n let open = null;\n let listeningOnClose = null;\n let close = () => {\n if (open && open.close()) {\n open = null;\n win.removeEventListener(\"mousedown\", listeningOnClose);\n }\n };\n label.addEventListener(\"mousedown\", e => {\n e.preventDefault();\n markMenuEvent(e);\n if (open) {\n close();\n }\n else {\n open = this.expand(wrap, content.dom);\n win.addEventListener(\"mousedown\", listeningOnClose = () => {\n if (!isMenuEvent(wrap))\n close();\n });\n }\n });\n function update(state) {\n let inner = content.update(state);\n wrap.style.display = inner ? \"\" : \"none\";\n return inner;\n }\n return { dom: wrap, update };\n }\n /**\n @internal\n */\n expand(dom, items) {\n let menuDOM = crel(\"div\", { class: prefix$1 + \"-dropdown-menu \" + (this.options.class || \"\") }, items);\n let done = false;\n function close() {\n if (done)\n return false;\n done = true;\n dom.removeChild(menuDOM);\n return true;\n }\n dom.appendChild(menuDOM);\n return { close, node: menuDOM };\n }\n}\nfunction renderDropdownItems(items, view) {\n let rendered = [], updates = [];\n for (let i = 0; i < items.length; i++) {\n let { dom, update } = items[i].render(view);\n rendered.push(crel(\"div\", { class: prefix$1 + \"-dropdown-item\" }, dom));\n updates.push(update);\n }\n return { dom: rendered, update: combineUpdates(updates, rendered) };\n}\nfunction combineUpdates(updates, nodes) {\n return (state) => {\n let something = false;\n for (let i = 0; i < updates.length; i++) {\n let up = updates[i](state);\n nodes[i].style.display = up ? \"\" : \"none\";\n if (up)\n something = true;\n }\n return something;\n };\n}\n/**\nRepresents a submenu wrapping a group of elements that start\nhidden and expand to the right when hovered over or tapped.\n*/\nclass DropdownSubmenu {\n /**\n Creates a submenu for the given group of menu elements. The\n following options are recognized:\n */\n constructor(content, \n /**\n @internal\n */\n options = {}) {\n this.options = options;\n this.content = Array.isArray(content) ? content : [content];\n }\n /**\n Renders the submenu.\n */\n render(view) {\n let items = renderDropdownItems(this.content, view);\n let win = view.dom.ownerDocument.defaultView || window;\n let label = crel(\"div\", { class: prefix$1 + \"-submenu-label\" }, translate(view, this.options.label || \"\"));\n let wrap = crel(\"div\", { class: prefix$1 + \"-submenu-wrap\" }, label, crel(\"div\", { class: prefix$1 + \"-submenu\" }, items.dom));\n let listeningOnClose = null;\n label.addEventListener(\"mousedown\", e => {\n e.preventDefault();\n markMenuEvent(e);\n setClass(wrap, prefix$1 + \"-submenu-wrap-active\", false);\n if (!listeningOnClose)\n win.addEventListener(\"mousedown\", listeningOnClose = () => {\n if (!isMenuEvent(wrap)) {\n wrap.classList.remove(prefix$1 + \"-submenu-wrap-active\");\n win.removeEventListener(\"mousedown\", listeningOnClose);\n listeningOnClose = null;\n }\n });\n });\n function update(state) {\n let inner = items.update(state);\n wrap.style.display = inner ? \"\" : \"none\";\n return inner;\n }\n return { dom: wrap, update };\n }\n}\n/**\nRender the given, possibly nested, array of menu elements into a\ndocument fragment, placing separators between them (and ensuring no\nsuperfluous separators appear when some of the groups turn out to\nbe empty).\n*/\nfunction renderGrouped(view, content) {\n let result = document.createDocumentFragment();\n let updates = [], separators = [];\n for (let i = 0; i < content.length; i++) {\n let items = content[i], localUpdates = [], localNodes = [];\n for (let j = 0; j < items.length; j++) {\n let { dom, update } = items[j].render(view);\n let span = crel(\"span\", { class: prefix$1 + \"item\" }, dom);\n result.appendChild(span);\n localNodes.push(span);\n localUpdates.push(update);\n }\n if (localUpdates.length) {\n updates.push(combineUpdates(localUpdates, localNodes));\n if (i < content.length - 1)\n separators.push(result.appendChild(separator()));\n }\n }\n function update(state) {\n let something = false, needSep = false;\n for (let i = 0; i < updates.length; i++) {\n let hasContent = updates[i](state);\n if (i)\n separators[i - 1].style.display = needSep && hasContent ? \"\" : \"none\";\n needSep = hasContent;\n if (hasContent)\n something = true;\n }\n return something;\n }\n return { dom: result, update };\n}\nfunction separator() {\n return crel(\"span\", { class: prefix$1 + \"separator\" });\n}\n/**\nA set of basic editor-related icons. Contains the properties\n`join`, `lift`, `selectParentNode`, `undo`, `redo`, `strong`, `em`,\n`code`, `link`, `bulletList`, `orderedList`, and `blockquote`, each\nholding an object that can be used as the `icon` option to\n`MenuItem`.\n*/\nconst icons = {\n join: {\n width: 800, height: 900,\n path: \"M0 75h800v125h-800z M0 825h800v-125h-800z M250 400h100v-100h100v100h100v100h-100v100h-100v-100h-100z\"\n },\n lift: {\n width: 1024, height: 1024,\n path: \"M219 310v329q0 7-5 12t-12 5q-8 0-13-5l-164-164q-5-5-5-13t5-13l164-164q5-5 13-5 7 0 12 5t5 12zM1024 749v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12zM1024 530v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 310v109q0 7-5 12t-12 5h-621q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h621q7 0 12 5t5 12zM1024 91v109q0 7-5 12t-12 5h-987q-7 0-12-5t-5-12v-109q0-7 5-12t12-5h987q7 0 12 5t5 12z\"\n },\n selectParentNode: { text: \"\\u2b1a\", css: \"font-weight: bold\" },\n undo: {\n width: 1024, height: 1024,\n path: \"M761 1024c113-206 132-520-313-509v253l-384-384 384-384v248c534-13 594 472 313 775z\"\n },\n redo: {\n width: 1024, height: 1024,\n path: \"M576 248v-248l384 384-384 384v-253c-446-10-427 303-313 509-280-303-221-789 313-775z\"\n },\n strong: {\n width: 805, height: 1024,\n path: \"M317 869q42 18 80 18 214 0 214-191 0-65-23-102-15-25-35-42t-38-26-46-14-48-6-54-1q-41 0-57 5 0 30-0 90t-0 90q0 4-0 38t-0 55 2 47 6 38zM309 442q24 4 62 4 46 0 81-7t62-25 42-51 14-81q0-40-16-70t-45-46-61-24-70-8q-28 0-74 7 0 28 2 86t2 86q0 15-0 45t-0 45q0 26 0 39zM0 950l1-53q8-2 48-9t60-15q4-6 7-15t4-19 3-18 1-21 0-19v-37q0-561-12-585-2-4-12-8t-25-6-28-4-27-2-17-1l-2-47q56-1 194-6t213-5q13 0 39 0t38 0q40 0 78 7t73 24 61 40 42 59 16 78q0 29-9 54t-22 41-36 32-41 25-48 22q88 20 146 76t58 141q0 57-20 102t-53 74-78 48-93 27-100 8q-25 0-75-1t-75-1q-60 0-175 6t-132 6z\"\n },\n em: {\n width: 585, height: 1024,\n path: \"M0 949l9-48q3-1 46-12t63-21q16-20 23-57 0-4 35-165t65-310 29-169v-14q-13-7-31-10t-39-4-33-3l10-58q18 1 68 3t85 4 68 1q27 0 56-1t69-4 56-3q-2 22-10 50-17 5-58 16t-62 19q-4 10-8 24t-5 22-4 26-3 24q-15 84-50 239t-44 203q-1 5-7 33t-11 51-9 47-3 32l0 10q9 2 105 17-1 25-9 56-6 0-18 0t-18 0q-16 0-49-5t-49-5q-78-1-117-1-29 0-81 5t-69 6z\"\n },\n code: {\n width: 896, height: 1024,\n path: \"M608 192l-96 96 224 224-224 224 96 96 288-320-288-320zM288 192l-288 320 288 320 96-96-224-224 224-224-96-96z\"\n },\n link: {\n width: 951, height: 1024,\n path: \"M832 694q0-22-16-38l-118-118q-16-16-38-16-24 0-41 18 1 1 10 10t12 12 8 10 7 14 2 15q0 22-16 38t-38 16q-8 0-15-2t-14-7-10-8-12-12-10-10q-18 17-18 41 0 22 16 38l117 118q15 15 38 15 22 0 38-14l84-83q16-16 16-38zM430 292q0-22-16-38l-117-118q-16-16-38-16-22 0-38 15l-84 83q-16 16-16 38 0 22 16 38l118 118q15 15 38 15 24 0 41-17-1-1-10-10t-12-12-8-10-7-14-2-15q0-22 16-38t38-16q8 0 15 2t14 7 10 8 12 12 10 10q18-17 18-41zM941 694q0 68-48 116l-84 83q-47 47-116 47-69 0-116-48l-117-118q-47-47-47-116 0-70 50-119l-50-50q-49 50-118 50-68 0-116-48l-118-118q-48-48-48-116t48-116l84-83q47-47 116-47 69 0 116 48l117 118q47 47 47 116 0 70-50 119l50 50q49-50 118-50 68 0 116 48l118 118q48 48 48 116z\"\n },\n bulletList: {\n width: 768, height: 896,\n path: \"M0 512h128v-128h-128v128zM0 256h128v-128h-128v128zM0 768h128v-128h-128v128zM256 512h512v-128h-512v128zM256 256h512v-128h-512v128zM256 768h512v-128h-512v128z\"\n },\n orderedList: {\n width: 768, height: 896,\n path: \"M320 512h448v-128h-448v128zM320 768h448v-128h-448v128zM320 128v128h448v-128h-448zM79 384h78v-256h-36l-85 23v50l43-2v185zM189 590c0-36-12-78-96-78-33 0-64 6-83 16l1 66c21-10 42-15 67-15s32 11 32 28c0 26-30 58-110 112v50h192v-67l-91 2c49-30 87-66 87-113l1-1z\"\n },\n blockquote: {\n width: 640, height: 896,\n path: \"M0 448v256h256v-256h-128c0 0 0-128 128-128v-128c0 0-256 0-256 256zM640 320v-128c0 0-256 0-256 256v256h256v-256h-128c0 0 0-128 128-128z\"\n }\n};\n/**\nMenu item for the `joinUp` command.\n*/\nconst joinUpItem = new MenuItem({\n title: \"Join with above block\",\n run: joinUp,\n select: state => joinUp(state),\n icon: icons.join\n});\n/**\nMenu item for the `lift` command.\n*/\nconst liftItem = new MenuItem({\n title: \"Lift out of enclosing block\",\n run: lift,\n select: state => lift(state),\n icon: icons.lift\n});\n/**\nMenu item for the `selectParentNode` command.\n*/\nconst selectParentNodeItem = new MenuItem({\n title: \"Select parent node\",\n run: selectParentNode,\n select: state => selectParentNode(state),\n icon: icons.selectParentNode\n});\n/**\nMenu item for the `undo` command.\n*/\nlet undoItem = new MenuItem({\n title: \"Undo last change\",\n run: undo,\n enable: state => undo(state),\n icon: icons.undo\n});\n/**\nMenu item for the `redo` command.\n*/\nlet redoItem = new MenuItem({\n title: \"Redo last undone change\",\n run: redo,\n enable: state => redo(state),\n icon: icons.redo\n});\n/**\nBuild a menu item for wrapping the selection in a given node type.\nAdds `run` and `select` properties to the ones present in\n`options`. `options.attrs` may be an object that provides\nattributes for the wrapping node.\n*/\nfunction wrapItem(nodeType, options) {\n let passedOptions = {\n run(state, dispatch) {\n return wrapIn(nodeType, options.attrs)(state, dispatch);\n },\n select(state) {\n return wrapIn(nodeType, options.attrs)(state);\n }\n };\n for (let prop in options)\n passedOptions[prop] = options[prop];\n return new MenuItem(passedOptions);\n}\n/**\nBuild a menu item for changing the type of the textblock around the\nselection to the given type. Provides `run`, `active`, and `select`\nproperties. Others must be given in `options`. `options.attrs` may\nbe an object to provide the attributes for the textblock node.\n*/\nfunction blockTypeItem(nodeType, options) {\n let command = setBlockType(nodeType, options.attrs);\n let passedOptions = {\n run: command,\n enable(state) { return command(state); },\n active(state) {\n let { $from, to, node } = state.selection;\n if (node)\n return node.hasMarkup(nodeType, options.attrs);\n return to <= $from.end() && $from.parent.hasMarkup(nodeType, options.attrs);\n }\n };\n for (let prop in options)\n passedOptions[prop] = options[prop];\n return new MenuItem(passedOptions);\n}\n// Work around classList.toggle being broken in IE11\nfunction setClass(dom, cls, on) {\n if (on)\n dom.classList.add(cls);\n else\n dom.classList.remove(cls);\n}\n\nconst prefix = \"ProseMirror-menubar\";\nfunction isIOS() {\n if (typeof navigator == \"undefined\")\n return false;\n let agent = navigator.userAgent;\n return !/Edge\\/\\d/.test(agent) && /AppleWebKit/.test(agent) && /Mobile\\/\\w+/.test(agent);\n}\n/**\nA plugin that will place a menu bar above the editor. Note that\nthis involves wrapping the editor in an additional `
    `.\n*/\nfunction menuBar(options) {\n return new Plugin({\n view(editorView) { return new MenuBarView(editorView, options); }\n });\n}\nclass MenuBarView {\n constructor(editorView, options) {\n this.editorView = editorView;\n this.options = options;\n this.spacer = null;\n this.maxHeight = 0;\n this.widthForMaxHeight = 0;\n this.floating = false;\n this.scrollHandler = null;\n this.wrapper = crel(\"div\", { class: prefix + \"-wrapper\" });\n this.menu = this.wrapper.appendChild(crel(\"div\", { class: prefix }));\n this.menu.className = prefix;\n if (editorView.dom.parentNode)\n editorView.dom.parentNode.replaceChild(this.wrapper, editorView.dom);\n this.wrapper.appendChild(editorView.dom);\n let { dom, update } = renderGrouped(this.editorView, this.options.content);\n this.contentUpdate = update;\n this.menu.appendChild(dom);\n this.update();\n if (options.floating && !isIOS()) {\n this.updateFloat();\n let potentialScrollers = getAllWrapping(this.wrapper);\n this.scrollHandler = (e) => {\n let root = this.editorView.root;\n if (!(root.body || root).contains(this.wrapper))\n potentialScrollers.forEach(el => el.removeEventListener(\"scroll\", this.scrollHandler));\n else\n this.updateFloat(e.target.getBoundingClientRect ? e.target : undefined);\n };\n potentialScrollers.forEach(el => el.addEventListener('scroll', this.scrollHandler));\n }\n }\n update() {\n this.contentUpdate(this.editorView.state);\n if (this.floating) {\n this.updateScrollCursor();\n }\n else {\n if (this.menu.offsetWidth != this.widthForMaxHeight) {\n this.widthForMaxHeight = this.menu.offsetWidth;\n this.maxHeight = 0;\n }\n if (this.menu.offsetHeight > this.maxHeight) {\n this.maxHeight = this.menu.offsetHeight;\n this.menu.style.minHeight = this.maxHeight + \"px\";\n }\n }\n }\n updateScrollCursor() {\n let selection = this.editorView.root.getSelection();\n if (!selection.focusNode)\n return;\n let rects = selection.getRangeAt(0).getClientRects();\n let selRect = rects[selectionIsInverted(selection) ? 0 : rects.length - 1];\n if (!selRect)\n return;\n let menuRect = this.menu.getBoundingClientRect();\n if (selRect.top < menuRect.bottom && selRect.bottom > menuRect.top) {\n let scrollable = findWrappingScrollable(this.wrapper);\n if (scrollable)\n scrollable.scrollTop -= (menuRect.bottom - selRect.top);\n }\n }\n updateFloat(scrollAncestor) {\n let parent = this.wrapper, editorRect = parent.getBoundingClientRect(), top = scrollAncestor ? Math.max(0, scrollAncestor.getBoundingClientRect().top) : 0;\n if (this.floating) {\n if (editorRect.top >= top || editorRect.bottom < this.menu.offsetHeight + 10) {\n this.floating = false;\n this.menu.style.position = this.menu.style.left = this.menu.style.top = this.menu.style.width = \"\";\n this.menu.style.display = \"\";\n this.spacer.parentNode.removeChild(this.spacer);\n this.spacer = null;\n }\n else {\n let border = (parent.offsetWidth - parent.clientWidth) / 2;\n this.menu.style.left = (editorRect.left + border) + \"px\";\n this.menu.style.display = editorRect.top > (this.editorView.dom.ownerDocument.defaultView || window).innerHeight\n ? \"none\" : \"\";\n if (scrollAncestor)\n this.menu.style.top = top + \"px\";\n }\n }\n else {\n if (editorRect.top < top && editorRect.bottom >= this.menu.offsetHeight + 10) {\n this.floating = true;\n let menuRect = this.menu.getBoundingClientRect();\n this.menu.style.left = menuRect.left + \"px\";\n this.menu.style.width = menuRect.width + \"px\";\n if (scrollAncestor)\n this.menu.style.top = top + \"px\";\n this.menu.style.position = \"fixed\";\n this.spacer = crel(\"div\", { class: prefix + \"-spacer\", style: `height: ${menuRect.height}px` });\n parent.insertBefore(this.spacer, this.menu);\n }\n }\n }\n destroy() {\n if (this.wrapper.parentNode)\n this.wrapper.parentNode.replaceChild(this.editorView.dom, this.wrapper);\n }\n}\n// Not precise, but close enough\nfunction selectionIsInverted(selection) {\n if (selection.anchorNode == selection.focusNode)\n return selection.anchorOffset > selection.focusOffset;\n return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING;\n}\nfunction findWrappingScrollable(node) {\n for (let cur = node.parentNode; cur; cur = cur.parentNode)\n if (cur.scrollHeight > cur.clientHeight)\n return cur;\n}\nfunction getAllWrapping(node) {\n let res = [node.ownerDocument.defaultView || window];\n for (let cur = node.parentNode; cur; cur = cur.parentNode)\n res.push(cur);\n return res;\n}\n\nexport { Dropdown, DropdownSubmenu, MenuItem, blockTypeItem, icons, joinUpItem, liftItem, menuBar, redoItem, renderGrouped, selectParentNodeItem, undoItem, wrapItem };\n","// menu-plugin.ts\nimport { MenuItem } from \"prosemirror-menu\";\nimport { menuBar } from \"prosemirror-menu\";\nimport { toggleMark } from \"prosemirror-commands\";\nimport { Plugin, PluginKey } from \"prosemirror-state\";\n\n\nconst menuPluginKey = new PluginKey('menuPlugin')\n// Modify the menuBar function to accept customSchema as a parameter\nexport function createMenuPlugin(customSchema: any) {\n const boldButton = new MenuItem({\n title: \"Bold\",\n run: toggleMark(customSchema.marks.bold),\n active: (state) => state.selection.$head.marks().some(mark => mark.type === customSchema.marks.bold),\n });\n\n const italicButton = new MenuItem({\n title: \"Italic\",\n run: toggleMark(customSchema.marks.italic),\n active: (state) => state.selection.$head.marks().some(mark => mark.type === customSchema.marks.italic),\n });\n\n const menuContent = [\n [boldButton, italicButton] // Array of buttons or other menu items\n ];\n\n menuBar({\n content: menuContent,\n floating: true,\n });\n console.log('Creating menu plugin');\n\n return new Plugin({\n key: menuPluginKey\n })\n\n}\n","import { LitElement, css, html } from 'lit';\nimport { property, customElement, query } from 'lit/decorators.js';\n\nimport '@shoelace-style/shoelace/dist/components/card/card.js';\n\nimport '@shoelace-style/shoelace/dist/components/button/button.js';\n\nimport { styles } from '../../styles/shared-styles';\n\nimport {EditorState} from 'prosemirror-state'\nimport { Transaction } from 'prosemirror-state';\nimport { EditorView } from 'prosemirror-view';\nimport { Schema } from 'prosemirror-model';\n\n\nimport { keymap } from 'prosemirror-keymap';\nimport { toggleMark } from 'prosemirror-commands';\nimport {undo, redo, history} from 'prosemirror-history'\nimport { baseKeymap } from 'prosemirror-commands';\n\nimport {createMenuPlugin} from '../../components/menu-plugin'\n\n\nexport const customSchema = new Schema({\n\tnodes: {\n\t text: {\n\t\tgroup: 'inline',\n\t },\n\t star: {\n\t\tinline: true,\n\t\tgroup: 'inline',\n\t\ttoDOM() {\n\t\t return ['star', '⭐'];\n\t\t},\n\t\tparseDOM: [{ tag: 'star' }],\n\t },\n\t paragraph: {\n\t\tgroup: 'block',\n\t\tcontent: 'inline*',\n\t\ttoDOM() {\n\t\t return ['p', 0];\n\t\t},\n\t\tparseDOM: [{ tag: 'p' }],\n\t },\n\t boring_paragraph: {\n\t\tgroup: 'block',\n\t\tcontent: 'text*',\n\t\tmarks: '',\n\t\ttoDOM() {\n\t\t return ['p', { class: 'boring' }, 0];\n\t\t},\n\t\tparseDOM: [{ tag: 'p.boring', priority: 60 }],\n\t },\n\t doc: {\n\t\tcontent: 'block+',\n\t },\n\t},\n\tmarks: {\n\t shouting: {\n\t\ttoDOM() {\n\t\t return ['shouting', 0];\n\t\t},\n\t\tparseDOM: [{ tag: 'shouting' }],\n\t },\n\t link: {\n\t\tattrs: { href: {} },\n\t\ttoDOM(node) {\n\t\t return ['a', { href: node.attrs.href }, 0];\n\t\t},\n\t\tparseDOM: [\n\t\t {\n\t\t\ttag: 'a',\n\t\t\tgetAttrs(dom) {\n\t\t\t return { href: dom };\n\t\t\t},\n\t\t },\n\t\t],\n\t\tinclusive: false,\n\t },\n\t},\n });\n\n// Create the menu plugin\nconst menuPlugin = createMenuPlugin(customSchema);\n\n // Commands\nfunction insertStar(state: EditorState, dispatch?: (tr: Transaction) => void): boolean {\n\tconst type = customSchema.nodes.star;\n\tconst { $from } = state.selection;\n\n\t// If the parent cannot replace with the 'star' node, return false\n\tif (!$from.parent.canReplaceWith($from.index(), $from.index(), type)) {\n\t return false;\n\t}\n\n\t// If dispatch is provided, apply the transaction\n\tif (dispatch) {\n\t dispatch(state.tr.replaceSelectionWith(type.create()));\n\t}\n\n\t// Always return true if insertion conditions are met\n\treturn true;\n }\n\nfunction toggleLink(state: EditorState, dispatch?: (tr: Transaction) => void): boolean {\n\tlet {doc, selection} = state\n\tif (selection.empty) return false\n\tlet attrs = null\n\tif (!doc.rangeHasMark(selection.from, selection.to, customSchema.marks.link)) {\n\t attrs = {href: prompt(\"Link to where?\", \"\")}\n\t if (!attrs.href) return false\n\t}\n\treturn toggleMark(customSchema.marks.link, attrs)(state, dispatch)\n }\n\n\n // Keymap\nconst customKeymap = keymap({\n\t'Ctrl-Space': insertStar,\n\t\"Ctrl-b\": (state, dispatch) => {\n console.log(\"Ctrl-b pressed, toggling shouting mark...\");\n return toggleMark(customSchema.marks.shouting)(state, dispatch);\n },\n \t'Ctrl-q': (state, dispatch) => {\n\t\tconsole.log(\"you should have just gotten an alert\");\n\t\treturn toggleLink(state, dispatch);\n\t},\n\n });\n\n\n\n\n@customElement('app-write')\nexport class AppWrite extends LitElement {\n\t@property({ type: String }) placeholder: string = 'Compose your note...';\n\t@property({ type: String }) public value?: string;\n\n\t// Reference to the ProseMirror container\n\t@query('#editor') editorContainer!: HTMLElement;\n\n\tprivate editorView!: EditorView\n\n\n\n\n static styles = [\n styles, css`\n\t\t:host {\n\t\tdisplay: block;\n\t\t}\n\n\t\tshouting {\n all: unset; /* Remove inherited or conflicting styles */\n font-weight: bold;\n text-transform: uppercase;\n color: red; /* Add a visible color for debugging */\n}\n\n\t\t`\n\n ];\n\n protected async firstUpdated() {\n\t\tconsole.log(\"Welcome to the compose page\");\n\t\tawait this.updateComplete;\n\t\tthis.initializeEditor()\n\n}\nprivate initializeEditor() {\n\t\tif (!this.editorContainer) {\n\t\t\tconsole.error('Editor container not here');\n\t\t\treturn\n\t\t}\n \tconst doc = customSchema.nodes.doc.createAndFill();\n\t if (!doc) {\n\t\tconsole.error(\"failed to create initial document\")\n\t\treturn;\n\t}\n\n\tconst state = EditorState.create({\n \tdoc,\n \tplugins: [\n\t\t\tmenuPlugin,\n\t\t\thistory(),\n \t\tkeymap({\n \t'Mod-z': undo,\n \t'Mod-y': redo,\n \t\t}),\n \t\tkeymap(baseKeymap),\n \t // Add the plus-button plugin here\n\t\t\tcustomKeymap\n \t\t],\n\t \t});\n\n\n\n\t\tlet view = new EditorView(this.editorContainer, {\n\t\t\tstate,\n\t\t\tdispatchTransaction(transaction) {\n\t\t\t\tconsole.log('Document size went from', transaction.before.content.size, \"to\",\n\t\t\t\t\ttransaction.doc.content.size\n\t\t\t\t)\n\t\t\t\tlet newState = view.state.apply(transaction)\n\t\t\t\tview.updateState(newState)\n\t\t\t}\n\t\t});\n\t\tthis.editorView = view;\n\t\tconsole.log(state.plugins);\n\n\t\tconsole.log('editor initialized')\n\n\t}\n\n\t/* connectedCallback(): void {\n\t\tsuper.connectedCallback();\n\t\tif(!this.editorView) {\n\t\t\tthis.editorView;\n\t\t}\n\t} */\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n\t\tif (this.editorView) {\n\t\t\tthis.editorView.destroy();\n\t\t\tthis.editorView = null!\n\t\t}\n }\n\n\n\n protected render() {\n return html`\n \n\n\t\t
    \n\t\t
    \n\n \n
    \n

    Editor Demo

    \n
    \n\n\n\n\t\t\t

    Instructions

    \n\t\t\t

    Click inside the white text area to highlight with your cursor.\n\t\t\tYou can type and press enter to insert a new block below.

    \n\t\t\t
    \n\t\t\t

    Try to highlight a piece of text, then CTRL+X to cut and\n\t\t\tCTRL+V to paste.


    \n\t\t\t

    Press Ctrl+Space to add a yellow star to the document.

    \n\t\t\t

    Press Ctrl+B over a highlighted selection to add a \"shouting\"\n\t\t\tmark and format it all caps and red.

    \n\n
    \n\n
    \n
    \n
    \n `}\n\t}"],"names":["OrderedMap","content","key","i","found","value","newKey","self","place","without","f","map","result","prop","findDiffStart","a","b","pos","childA","childB","j","inner","findDiffEnd","posA","posB","iA","iB","size","same","minSize","Fragment$1","Fragment","from","to","nodeStart","parent","child","end","start","blockSeparator","leafText","text","first","node","nodeText","other","last","index","current","copy","p","otherPos","round","retIndex","curPos","cur","n","schema","array","joined","nodes","offset","compareDeep","Mark","type","attrs","set","placed","obj","_","json","mark","marks","Slice$1","Slice","openStart","openEnd","fragment","insertInto","removeRange","openIsolating","indexTo","offsetTo","dist","insert","replace","$from","$to","slice","ReplaceError","replaceOuter","depth","close","prepareSliceForReplace","replaceThreeWay","replaceTwoWay","checkJoin","main","sub","joinable","$before","$after","addNode","target","addRange","$start","$end","startIndex","endIndex","$along","extra","ResolvedPos","path","parentOffset","val","dOff","tmp","after","next","pred","d","NodeRange","str","doc","rem","cache","resolveCache","elt","ResolveCache","resolveCacheSize","emptyAttrs","Node$1","Node","startPos","includeParents","name","wrapMarks","match","replacement","one","two","m","TextNode","base","ContentMatch","validEnd","string","nodeTypes","stream","TokenStream","expr","parseExpr","dfa","nfa","checkForDeadEnds","frag","toEnd","seen","search","types","finished","tp","computed","active","scan","out","tok","exprs","parseExprSeq","parseExprSubscript","parseExprAtom","parseExprRange","parseNum","min","max","resolveName","typeName","connect","compile","edge","term","edges","loop","cmp","nullFrom","labeled","explore","states","state","work","dead","defaultAttrs","defaults","attrName","attr","computeAttrs","built","given","checkAttrs","values","initAttrs","Attribute","NodeType$1","NodeType","spec","group","before","matched","markType","topType","validateType","options","MarkType","rank","Schema","instanceSpec","contentExprCache","contentExpr","markExpr","gatherMarks","excl","ok","isTagRule","rule","isStyleRule","DOMParser","rules","matchedStyles","r","dom","context","ParseContext","matches","style","priority","blockTags","ignoreTags","listTags","OPT_PRESERVE_WS","OPT_PRESERVE_WS_FULL","OPT_OPEN_LEFT","wsOptionsFor","preserveWhitespace","NodeContext","solid","fill","wrap","parser","isOpen","topNode","topContext","topOptions","top","preserveWS","nodeBefore","domNodeBefore","matchAfter","outerWS","ruleID","normalizeList","sync","oldNeedsBlock","innerMarks","styles","continueAfter","nodeType","startIn","contentDOM","route","cx","block","nodeMarks","markMayApply","applyMarks","textNode","parts","option","useRoot","minDepth","part","$context","deflt","prevItem","selector","DOMSerializer","keep","rendered","add","markDOM","renderSpec","inline","toDOM","structure","xmlNS","blockArraysIn","gatherToDOM","suspiciousAttributeCache","suspiciousAttributes","suspiciousAttributesInner","tagName","suspicious","space","innerContent","lower16","factor16","makeRecover","recoverIndex","recoverOffset","DEL_BEFORE","DEL_AFTER","DEL_ACROSS","DEL_SIDE","MapResult$1","delInfo","recover","StepMap$1","StepMap","ranges","inverted","diff","assoc","simple","oldIndex","newIndex","oldSize","newSize","side","del","MapResult","oldStart","newStart","Mapping","maps","mirror","mirrors","mapping","startSize","mirr","totalSize","inverse","corr","stepsByID","Step$1","id","stepClass","StepResult$1","StepResult","failed","message","e","mapFragment","mapped","AddMarkStep","Step","oldSlice","RemoveMarkStep","AddNodeMarkStep","updated","newSet","RemoveNodeMarkStep","ReplaceStep","contentBetween","ReplaceAroundStep","gapFrom","gapTo","gap","inserted","addMark","tr","removed","added","removing","adding","s","removeMark","step","toRemove","clearIncompatible","parentType","clearNewlines","replSteps","allowed","newline","canCut","liftTarget","range","lift","gapStart","gapEnd","splitting","wrappers","setBlockType","mapFrom","attrsHere","canChangeType","convertNewlines","pre","supportLinebreak","replaceLinebreaks","startM","endM","replaceNewlines","$pos","setNodeMarkup","newNode","canSplit","typesAfter","innerType","rest","overrideChild","baseType","split","typeAfter","canJoin","canAppendWithSubstitutedLinebreaks","linebreakReplacement","join","beforeType","$full","insertPoint","dropPoint","pass","bias","insertPos","fits","wrapping","replaceStep","fitsTrivially","Fitter","unplaced","fit","moveInline","placedSize","startDepth","sliceDepth","contentAt","frontierDepth","inject","openAtEnd","dropFromFragment","taken","openEndCount","closeNodeStart","addToFragment","level","contentAfterFits","dropInner","count","open","invalidMarks","definesContent","replaceRange","targetDepths","coveredDepths","preferredTarget","preferredTargetIndex","leftNodes","preferredDepth","leftNode","def","openDepth","targetDepth","expand","closeFragment","startSteps","oldOpen","newOpen","replaceRangeWith","point","deleteRange","covered","AttrStep","DocAttrStep","TransformError","err","Transform","classesById","Selection$1","$anchor","$head","SelectionRange","lastNode","lastParent","selectionToInsertionEnd","dir","textOnly","TextSelection","findSelectionIn","AllSelection","cls","selectionClass","Selection","SelectionRange$1","warnedAboutTextSelection","checkTextSelection","TextBookmark","anchor","head","dPos","TextBookmark$1","NodeSelection","deleted","NodeBookmark","NodeBookmark$1","sel","AllBookmark","startLen","_from","_to","_newFrom","newTo","UPDATED_SEL","UPDATED_MARKS","UPDATED_SCROLL","Transaction","selection","time","inheritMarks","bind","FieldDesc$1","desc","baseFields","FieldDesc","config","instance","_marks","_old","prev","Configuration","plugins","plugin","EditorState","ignore","rootTr","trs","newState","haveNew","oldState","newInstance","fields","field","$config","pluginFields","bindProps","Plugin$1","createKey","keys","PluginKey","domIndex","parentNode","reusedRange","textRange","clearReusedRange","isEquivalentPosition","off","targetNode","targetOff","scanFor","atomElements","nodeSize","hasBlockDesc","textNodeBefore$1","textNodeAfter$1","isOnEdge","atStart","atEnd","selectionCollapsed","domSel","keyEvent","keyCode","event","deepActiveElement","caretFromPoint","x","y","nav","agent","ie_edge","ie_upto10","ie_11up","ie","ie_version","gecko","_chrome","chrome","chrome_version","safari","ios","mac","windows","android","webkit","webkit_version","windowRect","vp","getSide","clientRect","rect","scaleX","scaleY","scrollRectIntoView","view","startDOM","scrollThreshold","scrollMargin","atTop","bounding","moveX","moveY","startX","startY","dX","dY","storeScrollPos","refDOM","refTop","localRect","scrollStack","stack","resetScrollPos","newRefTop","restoreScrollStack","dTop","left","preventScrollSupported","focusPreventScroll","stored","findOffsetInNode","coords","closest","dxClosest","coordsClosest","rowBot","rowTop","firstBelow","coordsBelow","childIndex","rects","dx","findOffsetInText","len","singleRect","inRect","targetKludge","posFromElement","posFromCaret","outsideBlock","sawBlock","elementFromPoint","element","box","startI","posAtCoords","caret","nonZero","BIDI","coordsAtPos","atom","supportEmptyRange","rectBefore","rectAfter","flattenV","takeSide","flattenH","withFlushedState","viewState","endOfTextblockVertical","nearest","boxes","maybeRTL","endOfTextblockHorizontal","oldNode","oldOff","anchorNode","anchorOffset","oldBidiLevel","parentDOM","newOff","cachedState","cachedDir","cachedResult","endOfTextblock","NOT_DIRTY","CHILD_DIRTY","CONTENT_DIRTY","NODE_DIRTY","ViewDesc","children","widget","outerDeco","innerDeco","nodeName","domBefore","domAfter","onlyNodes","nodeDOM","TrailingHackViewDesc","WidgetViewDesc","enter","fromOffset","toOffset","childBase","force","anchorDOM","headDOM","selRange","brKludge","domSelExtended","mutation","startInside","endInside","dirty","stop","CompositionViewDesc","textDOM","mut","MarkViewDesc","custom","replaceNodes","NodeViewDesc","descObj","applyOuterDeco","CustomNodeViewDesc","TextViewDesc","sameOuterDeco","composition","localComposition","compositionInChild","updater","ViewTreeUpdater","iterDeco","insideNode","compIndex","renderDescs","iosHacks","textPos","findTextInFragment","needsWrap","oldDOM","patchOuterDeco","computeOuterDeco","docViewDesc","docView","skip","descs","written","childDOM","rm","OuterDecoLevel","noDeco","outerDOM","prevComputed","curComputed","curDOM","deco","patchAttributes","prevList","curList","lock","preMatch","maxKeep","markDesc","targetDesc","domNode","nextDOM","locked","wrapper","ch","lastChild","hack","parentDesc","curDesc","descI","fI","outer","compareSide","onWidget","onNode","locals","decoIndex","restNode","parentIndex","widgets","cutAt","oldCSS","childStart","selectionFromDOM","origin","nearestDesc","inWidget","nearestDescNode","selectionBetween","editorOwnsSelection","hasSelection","selectionToDOM","syncNodeSelection","curSel","selectCursorWrapper","resetEditableFrom","resetEditableTo","brokenSelectBetweenUneditable","temporarilyEditableNear","resetEditable","removeClassOnSelectionChange","setEditable","img","clearNodeSelection","hasFocusAndSelection","anchorInRightPlace","moveSelectionBlock","$side","apply","selectHorizontally","mods","$newHead","nodePos","nodeLen","isIgnorable","skipIgnoredNodes","skipIgnoredNodesBefore","skipIgnoredNodesAfter","moveNode","moveOffset","isBlockNode","setSelFocus","textNodeAfter","textNodeBefore","findDirection","mid","selectVertically","beyond","stopNativeHorizontalDelete","empty","nextNode","switchEditable","safariDownArrowBug","focusNode","focusOffset","getMods","captureKeyDown","code","serializeForClipboard","serializer","detachedDoc","firstChild","wrapMap","parseFromClipboard","html","plainText","inCode","asText","parsed","readHTML","restoreReplacedSpaces","contextNode","sliceData","inlineParents","addContext","closeSlice","normalizeSiblings","lastWrap","inLast","addToSibling","closeRight","wrapped","withWrappers","sibling","closeRange","_detachedDoc","_policy","maybeWrapTrusted","trustedTypes","metas","firstTag","handlers","editHandlers","passiveHandlers","InputState","initInput","handler","eventBelongsToView","runCustomHandler","ensureListeners","setSelectionOrigin","destroyInput","currentHandlers","dispatchEvent","_event","inOrNearComposition","now","eventCoords","isNear","click","dy","runHandlerOnContext","propName","inside","updateSelection","selectClickedLeaf","selectClickedNode","selectedNode","selectAt","handleSingleClick","selectNode","handleDoubleClick","handleTripleClick","defaultTripleClick","forceDOMFlush","endComposition","selectNodeModifier","flushed","MouseDown","targetPos","timeoutComposition","scheduleComposeEnd","delay","clearComposition","timestampFromCustomEvent","findCompositionNode","textBefore","textAfter","descAfter","lastChanged","descBefore","restarting","captureCopy","brokenClipboardAPI","cut","data","sliceSingleNode","capturePaste","plain","doPaste","preferPlain","singleNode","getText","clipboardData","uris","Dragging","move","dragCopyModifier","mouseDown","draggedSlice","dragging","eventPos","$mouse","isNode","beforeInsert","domChangeCount","$cursor","compareObjs","WidgetType","noSpec","span","oldOffset","Decoration","InlineType","none","DecorationSet","local","decorations","buildTree","predicate","childOff","newLocal","mapChildren","byPos","childNode","childOffset","baseOffset","takeSpansForNode","moveSpans","withoutNulls","dec","localSet","DecorationGroup","removeOverlap","members","mappedDecos","member","sorted","oldChildren","moved","oldEnd","newEnd","dSize","mustRebuild","fromLocal","toLocal","mapAndGatherRemainingDecorations","spans","gather","hasNulls","localStart","subtree","working","insertAhead","viewDecorations","observeOptions","useCharData","SelectionState","DOMObserver","handleDOMChange","mutations","take","ancestors","container","newSel","typeOver","brs","br","blockParent","readSel","checkCSS","previousSibling","nextSibling","cssChecked","cssCheckWarned","rangeToSelectionRange","currentAnchor","safariShadowSelectionRange","read","parseBetween","from_","to_","find","startDoc","ruleFromNode","isInline","readDOMChange","addedNodes","compositionID","shared","parse","compare","preferredPos","preferredSide","change","findDiff","resolveSelection","$fromA","inlineChange","nextSel","looksLikeBackspace","chFrom","chTo","storedMarks","markChange","isMarkChange","parsedSel","curMarks","prevMarks","update","old","$newStart","$newEnd","skipClosingAndOpening","$next","fromEnd","mayOpen","endA","endB","adjust","isSurrogatePair","EditorView","props","checkStateComponent","getEditable","updateCursorWrapper","buildNodeViews","computeDocDeco","prevProps","_a","redraw","updateSel","pluginsChanged","nodeViews","changedNodeViews","scroll","updateDoc","oldScrollPos","forceSelUpdate","selectionContextChanged","chromeKludge","prevState","pluginView","movedPos","cached","dispatchTransaction","sel1","sel2","nA","nB","shift","keyName","ignoreKey","Plugin","normalizeKeyName","alt","ctrl","meta","mod","normalize","modifiers","keymap","bindings","keydownHandler","baseName","direct","noShift","fromCode","deleteSelection","dispatch","atBlockStart","joinBackward","$cut","findCutBefore","deleteBarrier","textblockAt","delStep","only","selectNodeBackward","atBlockEnd","joinForward","findCutAfter","selectNodeForward","newlineInCode","defaultBlockAt","exitCode","above","createParagraphNear","liftEmptyBlock","splitBlockAs","splitNode","splitDepth","splitPos","can","$first","splitBlock","selectAll","joinMaybeClear","conn","isolated","canDelAfter","$joinAt","selAfter","at","afterText","afterDepth","selectTextblockSide","selectTextblockStart","selectTextblockEnd","markApplies","enterAtoms","toggleMark","spaceStart","spaceEnd","chainCommands","commands","backspace","pcBaseKeymap","macBaseKeymap","baseKeymap","GOOD_LEAF_SIZE","RopeSequence","Append","Leaf","prototypeAccessors","right","leftLen","max_empty_items","Branch","items","eventCount","preserveItems","remap","transform","remaining","addAfter","addBefore","item","Item","histOptions","newItems","oldItems","lastItem","merged","overflow","DEPTH_OVERFLOW","cutOffEvents","mirrorPos","rebasedTransform","rebasedCount","rebasedItems","newUntil","iRebased","newMaps","branch","upto","events","newItem","cutPoint","mirrorOffset","HistoryState","done","undone","prevRanges","prevTime","prevComposition","applyTransaction","history","historyTr","historyKey","rebased","closeHistoryKey","appended","mustPreserveItems","rangesFor","newGroup","isAdjacentTo","mapRanges","adjacent","histTransaction","redo","pop","newHist","cachedPreserveItems","cachedPreserveItemsPlugins","hist","inputType","command","undo","buildCommand","crelt","SVG","XLINK","prefix$2","hashPath","hash","getIcon","root","icon","width","height","buildSVG","svg","css","collection","sym","prefix$1","MenuItem","crel","translate","title","selected","enabled","setClass","combineUpdates","updates","something","up","renderGrouped","separators","localUpdates","localNodes","separator","needSep","hasContent","on","prefix","isIOS","menuBar","editorView","MenuBarView","potentialScrollers","getAllWrapping","el","selRect","selectionIsInverted","menuRect","scrollable","findWrappingScrollable","scrollAncestor","editorRect","border","res","menuPluginKey","createMenuPlugin","customSchema","boldButton","italicButton","menuPlugin","insertStar","toggleLink","customKeymap","AppWrite","LitElement","transaction","__decorateClass","property","query","customElement"],"mappings":"yFAEA,SAASA,EAAWC,EAAS,CAC3B,KAAK,QAAUA,CACjB,CAEAD,EAAW,UAAY,CACrB,YAAaA,EAEb,KAAM,SAASE,EAAK,CAClB,QAASC,EAAI,EAAGA,EAAI,KAAK,QAAQ,OAAQA,GAAK,EAC5C,GAAI,KAAK,QAAQA,CAAC,IAAMD,EAAK,OAAOC,EACtC,MAAO,EACR,EAKD,IAAK,SAASD,EAAK,CACjB,IAAIE,EAAQ,KAAK,KAAKF,CAAG,EACzB,OAAOE,GAAS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AAY,OAAO,QAAQ,KAAM,KACvEA,EAAY,IAAI,QAAQ,IACzB,EACA,IAAI1vB,EAAWkE,EAAK,MAAM,MAAMwrB,CAAW,EAC3CxrB,EAAK,YAAYlE,CAAQ,CAAA,CAC1B,CACA,EACD,KAAK,WAAakE,EACV,QAAA,IAAI7Z,EAAM,OAAO,EAEzB,QAAQ,IAAI,oBAAoB,CAAA,CAW9B,sBAA6B,CACzB,MAAM,qBAAqB,EAC7B,KAAK,aACR,KAAK,WAAW,QAAQ,EACxB,KAAK,WAAa,KACnB,CAKY,QAAS,CACR,OAAAmpB;AAAAA,mCACoB,EAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CA4BtC,EA/HYgc,GAYF,OAAS,CACZxgC,GAAQu9B;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA,GAcZ,EA1ByBoD,GAAA,CAA3BC,GAAS,CAAE,KAAM,MAAQ,CAAA,CAAA,EADdJ,GACgB,UAAA,cAAA,CAAA,EACOG,GAAA,CAAlCC,GAAS,CAAE,KAAM,MAAQ,CAAA,CAAA,EAFdJ,GAEuB,UAAA,QAAA,CAAA,EAGjBG,GAAA,CAAjBE,GAAM,SAAS,CAAA,EALJL,GAKM,UAAA,kBAAA,CAAA,EALNA,GAANG,GAAA,CADNG,GAAc,WAAW,CAAA,EACbN,EAAA","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]} \ No newline at end of file diff --git a/dist2/code/index-CBloBB_n.js b/dist2/code/index-CBloBB_n.js new file mode 100644 index 0000000..d889aad --- /dev/null +++ b/dist2/code/index-CBloBB_n.js @@ -0,0 +1,2 @@ +var P=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,s,r,h,u){this.type=t,this.name=e,this.prefix=s,this.value=r,this.suffix=h,this.modifier=u}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},J=/[$_\p{ID_Start}]/u,Q=/[$_\u200C\u200D\p{ID_Continue}]/u,D=".*";function Y(t,e){return/^[\x00-\x7F]*$/.test(t)}function M(t,e=!1){let s=[],r=0;for(;r{if(on("OTHER_MODIFIER")??n("ASTERISK"),f=p=>{let c=n(p);if(c!==void 0)return c;let{type:l,index:E}=s[o];throw new TypeError(`Unexpected ${l} at ${E}, expected ${p}`)},w=()=>{let p="",c;for(;c=n("CHAR")??n("ESCAPED_CHAR");)p+=c;return p},k=p=>p,T=e.encodePart||k,O="",U=p=>{O+=p},I=()=>{O.length&&(h.push(new P(3,"","",T(O),"",3)),O="")},_=(p,c,l,E,v)=>{let g=3;switch(v){case"?":g=1;break;case"*":g=0;break;case"+":g=2;break}if(!c&&!l&&g===3){U(p);return}if(I(),!c&&!l){if(!p)return;h.push(new P(3,"","",T(p),"",g));return}let m;l?l==="*"?m=D:m=l:m=r;let C=2;m===r?(C=1,m=""):m===D&&(C=0,m="");let b;if(c?b=c:l&&(b=u++),i.has(b))throw new TypeError(`Duplicate name '${b}'.`);i.add(b),h.push(new P(C,b,T(p),m,T(E),g))};for(;o-1)}return o||(r+=`(?=${u}|${h})`),new RegExp(r,j(s))}var $={delimiter:"",prefixes:"",sensitive:!0,strict:!0},et={delimiter:".",prefixes:"",sensitive:!0,strict:!0},st={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function it(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}function G(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}function rt(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}function K(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}var X=["ftp","file","http","https","ws","wss"];function V(t){if(!t)return!0;for(let e of X)if(t.test(e))return!0;return!1}function nt(t,e){if(t=G(t,"#"),e||t==="")return t;let s=new URL("https://example.com");return s.hash=t,s.hash?s.hash.substring(1,s.hash.length):""}function ot(t,e){if(t=G(t,"?"),e||t==="")return t;let s=new URL("https://example.com");return s.search=t,s.search?s.search.substring(1,s.search.length):""}function ht(t,e){return e||t===""?t:K(t)?q(t):Z(t)}function at(t,e){if(e||t==="")return t;let s=new URL("https://example.com");return s.password=t,s.password}function ut(t,e){if(e||t==="")return t;let s=new URL("https://example.com");return s.username=t,s.username}function pt(t,e,s){if(s||t==="")return t;if(e&&!X.includes(e))return new URL(`${e}:${t}`).pathname;let r=t[0]=="/";return t=new URL(r?t:"/-"+t,"https://example.com").pathname,r||(t=t.substring(2,t.length)),t}function ct(t,e,s){return z(e)===t&&(t=""),s||t===""?t:B(t)}function ft(t,e){return t=rt(t,":"),e||t===""?t:N(t)}function z(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function N(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}function lt(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}function mt(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}function Z(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}function q(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}function B(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}function dt(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}function gt(t){return t===""?t:new URL(`data:${t}`).pathname}function wt(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}function yt(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}var vt=class{#n;#i=[];#e={};#t=0;#r=1;#u=0;#h=0;#l=0;#m=0;#d=!1;constructor(t){this.#n=t}get result(){return this.#e}parse(){for(this.#i=M(this.#n,!0);this.#t0)if(this.#C())this.#l-=1;else continue;if(this.#k()){this.#l+=1;continue}switch(this.#h){case 0:this.#b()&&this.#f(1);break;case 1:if(this.#b()){this.#P();let t=7,e=1;this.#$()?(t=2,e=3):this.#d&&(t=2),this.#s(t,e)}break;case 2:this.#w()?this.#f(3):(this.#y()||this.#c()||this.#p())&&this.#f(5);break;case 3:this.#E()?this.#s(4,1):this.#w()&&this.#s(5,1);break;case 4:this.#w()&&this.#s(5,1);break;case 5:this.#L()?this.#m+=1:this.#A()&&(this.#m-=1),this.#R()&&!this.#m?this.#s(6,1):this.#y()?this.#s(7,0):this.#c()?this.#s(8,1):this.#p()&&this.#s(9,1);break;case 6:this.#y()?this.#s(7,0):this.#c()?this.#s(8,1):this.#p()&&this.#s(9,1);break;case 7:this.#c()?this.#s(8,1):this.#p()&&this.#s(9,1);break;case 8:this.#p()&&this.#s(9,1);break}}this.#e.hostname!==void 0&&this.#e.port===void 0&&(this.#e.port="")}#s(t,e){switch(this.#h){case 0:break;case 1:this.#e.protocol=this.#a();break;case 2:break;case 3:this.#e.username=this.#a();break;case 4:this.#e.password=this.#a();break;case 5:this.#e.hostname=this.#a();break;case 6:this.#e.port=this.#a();break;case 7:this.#e.pathname=this.#a();break;case 8:this.#e.search=this.#a();break;case 9:this.#e.hash=this.#a();break}this.#h!==0&&t!==10&&([1,2,3,4].includes(this.#h)&&[6,7,8,9].includes(t)&&(this.#e.hostname??=""),[1,2,3,4,5,6].includes(this.#h)&&[8,9].includes(t)&&(this.#e.pathname??=this.#d?"/":""),[1,2,3,4,5,6,7].includes(this.#h)&&t===9&&(this.#e.search??="")),this.#x(t,e)}#x(t,e){this.#h=t,this.#u=this.#t+e,this.#t+=e,this.#r=0}#v(){this.#t=this.#u,this.#r=0}#f(t){this.#v(),this.#h=t}#g(t){return t<0&&(t=this.#i.length-t),t=0&&(t.pathname=y(r.pathname.substring(0,h+1),s)+t.pathname)}t.pathname=pt(t.pathname,t.protocol,s)}return typeof e.search=="string"&&(t.search=ot(e.search,s)),typeof e.hash=="string"&&(t.hash=nt(e.hash,s)),t}function A(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}function bt(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function xt(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let s=".*",r=`[^${bt(e.delimiter)}]+?`,h=/[$_\u200C\u200D\p{ID_Continue}]/u,u="";for(let o=0;o0?t[o-1]:null,w=o0?w.value[0]:"";a=h.test(k)}else a=!w.hasCustomName();if(!a&&!i.prefix.length&&f&&f.type===3){let k=f.value[f.value.length-1];a=e.prefixes.includes(k)}a&&(u+="{"),u+=A(i.prefix),n&&(u+=`:${i.name}`),i.type===2?u+=`(${i.value})`:i.type===1?n||(u+=`(${r})`):i.type===0&&(!n&&(!f||f.type===3||f.modifier!==3||a||i.prefix!=="")?u+="*":u+=`(${s})`),i.type===1&&n&&i.suffix.length&&h.test(i.suffix[0])&&(u+="\\"),u+=A(i.suffix),a&&(u+="}"),i.modifier!==3&&(u+=R(i.modifier))}return u}var $t=class{#n;#i={};#e={};#t={};#r={};#u=!1;constructor(t={},e,s){try{let r;if(typeof e=="string"?r=e:s=e,typeof t=="string"){let i=new vt(t);if(i.parse(),t=i.result,r===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=r}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(r)throw new TypeError("parameter 1 is not of type 'string'.")}typeof s>"u"&&(s={ignoreCase:!1});let h={ignoreCase:s.ignoreCase===!0},u={pathname:x,protocol:x,username:x,password:x,hostname:x,port:x,search:x,hash:x};this.#n=L(u,t,!0),z(this.#n.protocol)===this.#n.port&&(this.#n.port="");let o;for(o of S){if(!(o in this.#n))continue;let i={},n=this.#n[o];switch(this.#e[o]=[],o){case"protocol":Object.assign(i,$),i.encodePart=N;break;case"username":Object.assign(i,$),i.encodePart=lt;break;case"password":Object.assign(i,$),i.encodePart=mt;break;case"hostname":Object.assign(i,et),K(n)?i.encodePart=q:i.encodePart=Z;break;case"port":Object.assign(i,$),i.encodePart=B;break;case"pathname":V(this.#i.protocol)?(Object.assign(i,st,h),i.encodePart=dt):(Object.assign(i,$,h),i.encodePart=gt);break;case"search":Object.assign(i,$,h),i.encodePart=wt;break;case"hash":Object.assign(i,$,h),i.encodePart=yt;break}try{this.#r[o]=W(n,i),this.#i[o]=F(this.#r[o],this.#e[o],i),this.#t[o]=xt(this.#r[o],i),this.#u=this.#u||this.#r[o].some(a=>a.type===2)}catch{throw new TypeError(`invalid ${o} pattern '${this.#n[o]}'.`)}}}catch(r){throw new TypeError(`Failed to construct 'URLPattern': ${r.message}`)}}test(t={},e){let s={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?s=L(s,t,!1):s=L(s,H(t,e),!1)}catch{return!1}let r;for(r of S)if(!this.#i[r].exec(s[r]))return!1;return!0}exec(t={},e){let s={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?s=L(s,t,!1):s=L(s,H(t,e),!1)}catch{return null}let r={};e?r.inputs=[t,e]:r.inputs=[t];let h;for(h of S){let u=this.#i[h].exec(s[h]);if(!u)return null;let o={};for(let[i,n]of this.#e[h].entries())if(typeof n=="string"||typeof n=="number"){let a=u[i+1];o[n]=a}r[h]={input:s[h]??"",groups:o}}return r}static compareComponent(t,e,s){let r=(i,n)=>{for(let a of["type","modifier","prefix","value","suffix"]){if(i[a]{let a=0;for(;a{if(la(\"OTHER_MODIFIER\")??a(\"ASTERISK\"),d=h=>{let u=a(h);if(u!==void 0)return u;let{type:p,index:A}=r[l];throw new TypeError(`Unexpected ${p} at ${A}, expected ${h}`)},T=()=>{let h=\"\",u;for(;u=a(\"CHAR\")??a(\"ESCAPED_CHAR\");)h+=u;return h},Se=h=>h,L=t.encodePart||Se,I=\"\",U=h=>{I+=h},$=()=>{I.length&&(o.push(new R(3,\"\",\"\",L(I),\"\",3)),I=\"\")},V=(h,u,p,A,Y)=>{let g=3;switch(Y){case\"?\":g=1;break;case\"*\":g=0;break;case\"+\":g=2;break}if(!u&&!p&&g===3){U(h);return}if($(),!u&&!p){if(!h)return;o.push(new R(3,\"\",\"\",L(h),\"\",g));return}let m;p?p===\"*\"?m=M:m=p:m=n;let O=2;m===n?(O=1,m=\"\"):m===M&&(O=0,m=\"\");let P;if(u?P=u:p&&(P=c++),i.has(P))throw new TypeError(`Duplicate name '${P}'.`);i.add(P),o.push(new R(O,P,L(h),m,L(A),g))};for(;l-1)}return l||(n+=`(?=${c}|${o})`),new RegExp(n,X(r))}var x={delimiter:\"\",prefixes:\"\",sensitive:!0,strict:!0},B={delimiter:\".\",prefixes:\"\",sensitive:!0,strict:!0},q={delimiter:\"/\",prefixes:\"/\",sensitive:!0,strict:!0};function J(e,t){return e.length?e[0]===\"/\"?!0:!t||e.length<2?!1:(e[0]==\"\\\\\"||e[0]==\"{\")&&e[1]==\"/\":!1}function Q(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Ee(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function W(e){return!e||e.length<2?!1:e[0]===\"[\"||(e[0]===\"\\\\\"||e[0]===\"{\")&&e[1]===\"[\"}var ee=[\"ftp\",\"file\",\"http\",\"https\",\"ws\",\"wss\"];function N(e){if(!e)return!0;for(let t of ee)if(e.test(t))return!0;return!1}function te(e,t){if(e=Q(e,\"#\"),t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):\"\"}function re(e,t){if(e=Q(e,\"?\"),t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.search=e,r.search?r.search.substring(1,r.search.length):\"\"}function ne(e,t){return t||e===\"\"?e:W(e)?j(e):z(e)}function se(e,t){if(t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.password=e,r.password}function ie(e,t){if(t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.username=e,r.username}function ae(e,t,r){if(r||e===\"\")return e;if(t&&!ee.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]==\"/\";return e=new URL(n?e:\"/-\"+e,\"https://example.com\").pathname,n||(e=e.substring(2,e.length)),e}function oe(e,t,r){return _(t)===e&&(e=\"\"),r||e===\"\"?e:K(e)}function ce(e,t){return e=Ee(e,\":\"),t||e===\"\"?e:y(e)}function _(e){switch(e){case\"ws\":case\"http\":return\"80\";case\"wws\":case\"https\":return\"443\";case\"ftp\":return\"21\";default:return\"\"}}function y(e){if(e===\"\")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function le(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.username=e,t.username}function fe(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.password=e,t.password}function z(e){if(e===\"\")return e;if(/[\\t\\n\\r #%/:<>?@[\\]^\\\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL(\"https://example.com\");return t.hostname=e,t.hostname}function j(e){if(e===\"\")return e;if(/[^0-9a-fA-F[\\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function K(e){if(e===\"\"||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function he(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.pathname=e[0]!==\"/\"?\"/-\"+e:e,e[0]!==\"/\"?t.pathname.substring(2,t.pathname.length):t.pathname}function ue(e){return e===\"\"?e:new URL(`data:${e}`).pathname}function de(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.search=e,t.search.substring(1,t.search.length)}function pe(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.hash=e,t.hash.substring(1,t.hash.length)}var H=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t}get result(){return this.#t}parse(){for(this.#n=v(this.#i,!0);this.#e0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=\"\")}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=\"\"),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?\"/\":\"\"),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??=\"\")),this.#R(t,r)}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(t){this.#b(),this.#o=t}#m(t){return t<0&&(t=this.#n.length-t),t=0&&(e.pathname=b(n.pathname.substring(0,o+1),r)+e.pathname)}e.pathname=ae(e.pathname,e.protocol,r)}return typeof t.search==\"string\"&&(e.search=re(t.search,r)),typeof t.hash==\"string\"&&(e.hash=te(t.hash,r)),e}function C(e){return e.replace(/([+*?:{}()\\\\])/g,\"\\\\$1\")}function Oe(e){return e.replace(/([.+*?^${}()[\\]|/\\\\])/g,\"\\\\$1\")}function ke(e,t){t.delimiter??=\"/#?\",t.prefixes??=\"./\",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=\"\";let r=\".*\",n=`[^${Oe(t.delimiter)}]+?`,o=/[$_\\u200C\\u200D\\p{ID_Continue}]/u,c=\"\";for(let l=0;l0?e[l-1]:null,d=l0?d.value[0]:\"\";a=o.test(T)}else a=!d.hasCustomName();if(!a&&!s.prefix.length&&f&&f.type===3){let T=f.value[f.value.length-1];a=t.prefixes.includes(T)}a&&(c+=\"{\"),c+=C(s.prefix),i&&(c+=`:${s.name}`),s.type===2?c+=`(${s.value})`:s.type===1?i||(c+=`(${n})`):s.type===0&&(!i&&(!f||f.type===3||f.modifier!==3||a||s.prefix!==\"\")?c+=\"*\":c+=`(${r})`),s.type===1&&i&&s.suffix.length&&o.test(s.suffix[0])&&(c+=\"\\\\\"),c+=C(s.suffix),a&&(c+=\"}\"),s.modifier!==3&&(c+=k(s.modifier))}return c}var me=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let o;if(typeof r==\"string\"?o=r:n=r,typeof t==\"string\"){let i=new H(t);if(i.parse(),t=i.result,o===void 0&&typeof t.protocol!=\"string\")throw new TypeError(\"A base URL must be provided for a relative constructor string.\");t.baseURL=o}else{if(!t||typeof t!=\"object\")throw new TypeError(\"parameter 1 is not of type 'string' and cannot convert to dictionary.\");if(o)throw new TypeError(\"parameter 1 is not of type 'string'.\")}typeof n>\"u\"&&(n={ignoreCase:!1});let c={ignoreCase:n.ignoreCase===!0},l={pathname:E,protocol:E,username:E,password:E,hostname:E,port:E,search:E,hash:E};this.#i=w(l,t,!0),_(this.#i.protocol)===this.#i.port&&(this.#i.port=\"\");let s;for(s of G){if(!(s in this.#i))continue;let i={},a=this.#i[s];switch(this.#t[s]=[],s){case\"protocol\":Object.assign(i,x),i.encodePart=y;break;case\"username\":Object.assign(i,x),i.encodePart=le;break;case\"password\":Object.assign(i,x),i.encodePart=fe;break;case\"hostname\":Object.assign(i,B),W(a)?i.encodePart=j:i.encodePart=z;break;case\"port\":Object.assign(i,x),i.encodePart=K;break;case\"pathname\":N(this.#n.protocol)?(Object.assign(i,q,c),i.encodePart=he):(Object.assign(i,x,c),i.encodePart=ue);break;case\"search\":Object.assign(i,x,c),i.encodePart=de;break;case\"hash\":Object.assign(i,x,c),i.encodePart=pe;break}try{this.#s[s]=D(a,i),this.#n[s]=F(this.#s[s],this.#t[s],i),this.#e[s]=ke(this.#s[s],i),this.#l=this.#l||this.#s[s].some(f=>f.type===2)}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},r){let n={pathname:\"\",protocol:\"\",username:\"\",password:\"\",hostname:\"\",port:\"\",search:\"\",hash:\"\"};if(typeof t!=\"string\"&&r)throw new TypeError(\"parameter 1 is not of type 'string'.\");if(typeof t>\"u\")return!1;try{typeof t==\"object\"?n=w(n,t,!1):n=w(n,ge(t,r),!1)}catch{return!1}let o;for(o of G)if(!this.#n[o].exec(n[o]))return!1;return!0}exec(t={},r){let n={pathname:\"\",protocol:\"\",username:\"\",password:\"\",hostname:\"\",port:\"\",search:\"\",hash:\"\"};if(typeof t!=\"string\"&&r)throw new TypeError(\"parameter 1 is not of type 'string'.\");if(typeof t>\"u\")return;try{typeof t==\"object\"?n=w(n,t,!1):n=w(n,ge(t,r),!1)}catch{return null}let o={};r?o.inputs=[t,r]:o.inputs=[t];let c;for(c of G){let l=this.#n[c].exec(n[c]);if(!l)return null;let s={};for(let[i,a]of this.#t[c].entries())if(typeof a==\"string\"||typeof a==\"number\"){let f=l[i+1];s[a]=f}o[c]={input:n[c]??\"\",groups:s}}return o}static compareComponent(t,r,n){let o=(i,a)=>{for(let f of[\"type\",\"modifier\",\"prefix\",\"value\",\"suffix\"]){if(i[f]{let f=0;for(;f{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function r(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(o){if(o.ep)return;o.ep=!0;const i=r(o);fetch(o.href,i)}})();var Ar="";function Sr(e){Ar=e}function ps(e=""){if(!Ar){const t=[...document.getElementsByTagName("script")],r=t.find(n=>n.hasAttribute("data-shoelace"));if(r)Sr(r.getAttribute("data-shoelace"));else{const n=t.find(i=>/shoelace(\.min)?\.js($|\?)/.test(i.src)||/shoelace-autoloader(\.min)?\.js($|\?)/.test(i.src));let o="";n&&(o=n.getAttribute("src")),Sr(o.split("/").slice(0,-1).join("/"))}}return Ar.replace(/\/$/,"")+(e?`/${e.replace(/^\//,"")}`:"")}var go=Object.defineProperty,gs=Object.defineProperties,bs=Object.getOwnPropertyDescriptor,ms=Object.getOwnPropertyDescriptors,Tn=Object.getOwnPropertySymbols,ys=Object.prototype.hasOwnProperty,ws=Object.prototype.propertyIsEnumerable,In=(e,t,r)=>t in e?go(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,_e=(e,t)=>{for(var r in t||(t={}))ys.call(t,r)&&In(e,r,t[r]);if(Tn)for(var r of Tn(t))ws.call(t,r)&&In(e,r,t[r]);return e},bo=(e,t)=>gs(e,ms(t)),T=(e,t,r,n)=>{for(var o=n>1?void 0:n?bs(t,r):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(o=(n?s(t,r,o):s(o))||o);return n&&o&&go(t,r,o),o},mo=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},vs=(e,t,r)=>(mo(e,t,"read from private field"),t.get(e)),xs=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Es=(e,t,r,n)=>(mo(e,t,"write to private field"),t.set(e,r),r);Sr("https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.16.0/cdn/");/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Be=globalThis,qr=Be.ShadowRoot&&(Be.ShadyCSS===void 0||Be.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,jr=Symbol(),Mn=new WeakMap;let yo=class{constructor(t,r,n){if(this._$cssResult$=!0,n!==jr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=r}get styleSheet(){let t=this.o;const r=this.t;if(qr&&t===void 0){const n=r!==void 0&&r.length===1;n&&(t=Mn.get(r)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&Mn.set(r,t))}return t}toString(){return this.cssText}};const _s=e=>new yo(typeof e=="string"?e:e+"",void 0,jr),ct=(e,...t)=>{const r=e.length===1?e[0]:t.reduce((n,o,i)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[i+1],e[0]);return new yo(r,e,jr)},$s=(e,t)=>{if(qr)e.adoptedStyleSheets=t.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of t){const n=document.createElement("style"),o=Be.litNonce;o!==void 0&&n.setAttribute("nonce",o),n.textContent=r.cssText,e.appendChild(n)}},Rn=qr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let r="";for(const n of t.cssRules)r+=n.cssText;return _s(r)})(e):e;/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const{is:As,defineProperty:Ss,getOwnPropertyDescriptor:ks,getOwnPropertyNames:Ps,getOwnPropertySymbols:Cs,getPrototypeOf:Bs}=Object,Ve=globalThis,Nn=Ve.trustedTypes,Ls=Nn?Nn.emptyScript:"",Us=Ve.reactiveElementPolyfillSupport,me=(e,t)=>e,Ie={toAttribute(e,t){switch(t){case Boolean:e=e?Ls:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let r=e;switch(t){case Boolean:r=e!==null;break;case Number:r=e===null?null:Number(e);break;case Object:case Array:try{r=JSON.parse(e)}catch{r=null}}return r}},Fr=(e,t)=>!As(e,t),On={attribute:!0,type:String,converter:Ie,reflect:!1,hasChanged:Fr};Symbol.metadata??=Symbol("metadata"),Ve.litPropertyMetadata??=new WeakMap;class Yt extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,r=On){if(r.state&&(r.attribute=!1),this._$Ei(),this.elementProperties.set(t,r),!r.noAccessor){const n=Symbol(),o=this.getPropertyDescriptor(t,n,r);o!==void 0&&Ss(this.prototype,t,o)}}static getPropertyDescriptor(t,r,n){const{get:o,set:i}=ks(this.prototype,t)??{get(){return this[r]},set(s){this[r]=s}};return{get(){return o?.call(this)},set(s){const l=o?.call(this);i.call(this,s),this.requestUpdate(t,l,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??On}static _$Ei(){if(this.hasOwnProperty(me("elementProperties")))return;const t=Bs(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(me("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(me("properties"))){const r=this.properties,n=[...Ps(r),...Cs(r)];for(const o of n)this.createProperty(o,r[o])}const t=this[Symbol.metadata];if(t!==null){const r=litPropertyMetadata.get(t);if(r!==void 0)for(const[n,o]of r)this.elementProperties.set(n,o)}this._$Eh=new Map;for(const[r,n]of this.elementProperties){const o=this._$Eu(r,n);o!==void 0&&this._$Eh.set(o,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const r=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const o of n)r.unshift(Rn(o))}else t!==void 0&&r.push(Rn(t));return r}static _$Eu(t,r){const n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,r=this.constructor.elementProperties;for(const n of r.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return $s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,r,n){this._$AK(t,n)}_$EC(t,r){const n=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,n);if(o!==void 0&&n.reflect===!0){const i=(n.converter?.toAttribute!==void 0?n.converter:Ie).toAttribute(r,n.type);this._$Em=t,i==null?this.removeAttribute(o):this.setAttribute(o,i),this._$Em=null}}_$AK(t,r){const n=this.constructor,o=n._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const i=n.getPropertyOptions(o),s=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Ie;this._$Em=o,this[o]=s.fromAttribute(r,i.type),this._$Em=null}}requestUpdate(t,r,n){if(t!==void 0){if(n??=this.constructor.getPropertyOptions(t),!(n.hasChanged??Fr)(this[t],r))return;this.P(t,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(t,r,n){this._$AL.has(t)||this._$AL.set(t,r),n.reflect===!0&&this._$Em!==t&&(this._$Ej??=new Set).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,i]of this._$Ep)this[o]=i;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[o,i]of n)i.wrapped!==!0||this._$AL.has(o)||this[o]===void 0||this.P(o,this[o],i)}let t=!1;const r=this._$AL;try{t=this.shouldUpdate(r),t?(this.willUpdate(r),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(r)):this._$EU()}catch(n){throw t=!1,this._$EU(),n}t&&this._$AE(r)}willUpdate(t){}_$AE(t){this._$EO?.forEach(r=>r.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&=this._$Ej.forEach(r=>this._$EC(r,this[r])),this._$EU()}updated(t){}firstUpdated(t){}}Yt.elementStyles=[],Yt.shadowRootOptions={mode:"open"},Yt[me("elementProperties")]=new Map,Yt[me("finalized")]=new Map,Us?.({ReactiveElement:Yt}),(Ve.reactiveElementVersions??=[]).push("2.0.4");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Wr=globalThis,Me=Wr.trustedTypes,Hn=Me?Me.createPolicy("lit-html",{createHTML:e=>e}):void 0,wo="$lit$",Ct=`lit$${Math.random().toFixed(9).slice(2)}$`,vo="?"+Ct,Ts=`<${vo}>`,qt=document,ye=()=>qt.createComment(""),we=e=>e===null||typeof e!="object"&&typeof e!="function",Kr=Array.isArray,Is=e=>Kr(e)||typeof e?.[Symbol.iterator]=="function",lr=`[ +\f\r]`,de=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zn=/-->/g,Vn=/>/g,Ot=RegExp(`>|${lr}(?:([^\\s"'>=/]+)(${lr}*=${lr}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Dn=/'/g,qn=/"/g,xo=/^(?:script|style|textarea|title)$/i,Ms=e=>(t,...r)=>({_$litType$:e,strings:t,values:r}),G=Ms(1),jt=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),jn=new WeakMap,Vt=qt.createTreeWalker(qt,129);function Eo(e,t){if(!Kr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Hn!==void 0?Hn.createHTML(t):t}const Rs=(e,t)=>{const r=e.length-1,n=[];let o,i=t===2?"":t===3?"":"",s=de;for(let l=0;l"?(s=o??de,d=-1):u[1]===void 0?d=-2:(d=s.lastIndex-u[2].length,c=u[1],s=u[3]===void 0?Ot:u[3]==='"'?qn:Dn):s===qn||s===Dn?s=Ot:s===zn||s===Vn?s=de:(s=Ot,o=void 0);const g=s===Ot&&e[l+1].startsWith("/>")?" ":"";i+=s===de?a+Ts:d>=0?(n.push(c),a.slice(0,d)+wo+a.slice(d)+Ct+g):a+Ct+(d===-2?l:g)}return[Eo(e,i+(e[r]||"")+(t===2?"":t===3?"":"")),n]};class ve{constructor({strings:t,_$litType$:r},n){let o;this.parts=[];let i=0,s=0;const l=t.length-1,a=this.parts,[c,u]=Rs(t,r);if(this.el=ve.createElement(c,n),Vt.currentNode=this.el.content,r===2||r===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(o=Vt.nextNode())!==null&&a.length0){o.textContent=Me?Me.emptyScript:"";for(let g=0;g2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=F}_$AI(t,r=this,n,o){const i=this.strings;let s=!1;if(i===void 0)t=te(this,t,r,0),s=!we(t)||t!==this._$AH&&t!==jt,s&&(this._$AH=t);else{const l=t;let a,c;for(t=i[0],a=0;a{const n=r?.renderBefore??t;let o=n._$litPart$;if(o===void 0){const i=r?.renderBefore??null;n._$litPart$=o=new $e(t.insertBefore(ye(),i),i,void 0,r??{})}return o._$AI(e),o};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */let gt=class extends Yt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=qs(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return jt}};gt._$litElement$=!0,gt.finalized=!0,globalThis.litElementHydrateSupport?.({LitElement:gt});const js=globalThis.litElementPolyfillSupport;js?.({LitElement:gt});(globalThis.litElementVersions??=[]).push("4.1.1");/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const qe=e=>(t,r)=>{r!==void 0?r.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Fs={attribute:!0,type:String,converter:Ie,reflect:!1,hasChanged:Fr},Ws=(e=Fs,t,r)=>{const{kind:n,metadata:o}=r;let i=globalThis.litPropertyMetadata.get(o);if(i===void 0&&globalThis.litPropertyMetadata.set(o,i=new Map),i.set(r.name,e),n==="accessor"){const{name:s}=r;return{set(l){const a=t.get.call(this);t.set.call(this,l),this.requestUpdate(s,a,e)},init(l){return l!==void 0&&this.P(s,void 0,e),l}}}if(n==="setter"){const{name:s}=r;return function(l){const a=this[s];t.call(this,l),this.requestUpdate(s,a,e)}}throw Error("Unsupported decorator location: "+n)};function S(e){return(t,r)=>typeof r=="object"?Ws(e,t,r):((n,o,i)=>{const s=o.hasOwnProperty(i);return o.constructor.createProperty(i,s?{...n,wrapped:!0}:n),s?Object.getOwnPropertyDescriptor(o,i):void 0})(e,t,r)}/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */function Zr(e){return S({...e,state:!0,attribute:!1})}/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Ks=(e,t,r)=>(r.configurable=!0,r.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,r),r);/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */function Zs(e,t){return(r,n,o)=>{const i=s=>s.renderRoot?.querySelector(e)??null;return Ks(r,n,{get(){return i(this)}})}}function Fn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function _o(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Gs(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Fn(e.outputLen),Fn(e.blockLen)}function Re(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Js(e,t){_o(e);const r=t.outputLen;if(e.lengthe instanceof Uint8Array,dr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),ot=(e,t)=>e<<32-t|e>>>t,Ys=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ys)throw new Error("Non little-endian hardware is not supported");function Xs(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Gr(e){if(typeof e=="string"&&(e=Xs(e)),!$o(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function Qs(...e){const t=new Uint8Array(e.reduce((n,o)=>n+o.length,0));let r=0;return e.forEach(n=>{if(!$o(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}let Ao=class{clone(){return this._cloneInto()}};function ta(e){const t=n=>e().update(Gr(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function So(e=32){if(cr&&typeof cr.getRandomValues=="function")return cr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function ea(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),l=Number(r&i),a=n?4:0,c=n?0:4;e.setUint32(t+a,s,n),e.setUint32(t+c,l,n)}let ra=class extends Ao{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=dr(this.buffer)}update(t){Re(this);const{view:r,buffer:n,blockLen:o}=this;t=Gr(t);const i=t.length;for(let s=0;so-s&&(this.process(n,0),s=0);for(let d=s;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;de&t^~e&r,oa=(e,t,r)=>e&t^e&r^t&r,ia=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]),$t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),At=new Uint32Array(64);let sa=class extends ra{constructor(){super(64,32,8,!1),this.A=$t[0]|0,this.B=$t[1]|0,this.C=$t[2]|0,this.D=$t[3]|0,this.E=$t[4]|0,this.F=$t[5]|0,this.G=$t[6]|0,this.H=$t[7]|0}get(){const{A:t,B:r,C:n,D:o,E:i,F:s,G:l,H:a}=this;return[t,r,n,o,i,s,l,a]}set(t,r,n,o,i,s,l,a){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=l|0,this.H=a|0}process(t,r){for(let d=0;d<16;d++,r+=4)At[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const m=At[d-15],g=At[d-2],p=ot(m,7)^ot(m,18)^m>>>3,h=ot(g,17)^ot(g,19)^g>>>10;At[d]=h+At[d-7]+p+At[d-16]|0}let{A:n,B:o,C:i,D:s,E:l,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){const m=ot(l,6)^ot(l,11)^ot(l,25),g=u+m+na(l,a,c)+ia[d]+At[d]|0,h=(ot(n,2)^ot(n,13)^ot(n,22))+oa(n,o,i)|0;u=c,c=a,a=l,l=s+g|0,s=i,i=o,o=n,n=g+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,l=l+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,o,i,s,l,a,c,u)}roundClean(){At.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const kr=ta(()=>new sa);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ko=BigInt(0),je=BigInt(1),aa=BigInt(2),Fe=e=>e instanceof Uint8Array,la=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ee(e){if(!Fe(e))throw new Error("Uint8Array expected");let t="";for(let r=0;rn+o.length,0));let r=0;return e.forEach(n=>{if(!Fe(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}function da(e,t){if(e.length!==t.length)return!1;for(let r=0;rko;e>>=je,t+=1);return t}function fa(e,t){return e>>BigInt(t)&je}const pa=(e,t,r)=>e|(r?je:ko)<(aa<new Uint8Array(e),Wn=e=>Uint8Array.from(e);function Co(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=ur(e),o=ur(e),i=0;const s=()=>{n.fill(1),o.fill(0),i=0},l=(...d)=>r(o,n,...d),a=(d=ur())=>{o=l(Wn([0]),d),n=l(),d.length!==0&&(o=l(Wn([1]),d),n=l())},c=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const m=[];for(;d{s(),a(d);let g;for(;!(g=m(c()));)a();return s(),g}}const ga={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function Ae(e,t,r={}){const n=(o,i,s)=>{const l=ga[i];if(typeof l!="function")throw new Error(`Invalid validator "${i}", expected function`);const a=e[o];if(!(s&&a===void 0)&&!l(a,e))throw new Error(`Invalid param ${String(o)}=${a} (${typeof a}), expected ${i}`)};for(const[o,i]of Object.entries(t))n(o,i,!1);for(const[o,i]of Object.entries(r))n(o,i,!0);return e}const ba=Object.freeze(Object.defineProperty({__proto__:null,bitGet:fa,bitLen:ha,bitMask:Qr,bitSet:pa,bytesToHex:ee,bytesToNumberBE:X,bytesToNumberLE:Yr,concatBytes:Ft,createHmacDrbg:Co,ensureBytes:Z,equalBytes:da,hexToBytes:re,hexToNumber:Jr,numberToBytesBE:Tt,numberToBytesLE:Xr,numberToHexUnpadded:Po,numberToVarBytesBE:ca,utf8ToBytes:ua,validateObject:Ae},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const W=BigInt(0),j=BigInt(1),Ht=BigInt(2),ma=BigInt(3),Pr=BigInt(4),Kn=BigInt(5),Zn=BigInt(8);BigInt(9);BigInt(16);function K(e,t){const r=e%t;return r>=W?r:t+r}function ya(e,t,r){if(r<=W||t 0");if(r===j)return W;let n=j;for(;t>W;)t&j&&(n=n*e%r),e=e*e%r,t>>=j;return n}function Q(e,t,r){let n=e;for(;t-- >W;)n*=n,n%=r;return n}function Cr(e,t){if(e===W||t<=W)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=K(e,t),n=t,o=W,i=j;for(;r!==W;){const l=n/r,a=n%r,c=o-i*l;n=r,r=a,o=i,i=c}if(n!==j)throw new Error("invert: does not exist");return K(o,t)}function wa(e){const t=(e-j)/Ht;let r,n,o;for(r=e-j,n=0;r%Ht===W;r/=Ht,n++);for(o=Ht;o(n[o]="function",n),t);return Ae(e,r)}function _a(e,t,r){if(r 0");if(r===W)return e.ONE;if(r===j)return t;let n=e.ONE,o=t;for(;r>W;)r&j&&(n=e.mul(n,o)),o=e.sqr(o),r>>=j;return n}function $a(e,t){const r=new Array(t.length),n=t.reduce((i,s,l)=>e.is0(s)?i:(r[l]=i,e.mul(i,s)),e.ONE),o=e.inv(n);return t.reduceRight((i,s,l)=>e.is0(s)?i:(r[l]=e.mul(i,r[l]),e.mul(i,s)),o),r}function Bo(e,t){const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Aa(e,t,r=!1,n={}){if(e<=W)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:o,nByteLength:i}=Bo(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const s=va(e),l=Object.freeze({ORDER:e,BITS:o,BYTES:i,MASK:Qr(o),ZERO:W,ONE:j,create:a=>K(a,e),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return W<=a&&aa===W,isOdd:a=>(a&j)===j,neg:a=>K(-a,e),eql:(a,c)=>a===c,sqr:a=>K(a*a,e),add:(a,c)=>K(a+c,e),sub:(a,c)=>K(a-c,e),mul:(a,c)=>K(a*c,e),pow:(a,c)=>_a(l,a,c),div:(a,c)=>K(a*Cr(c,e),e),sqrN:a=>a*a,addN:(a,c)=>a+c,subN:(a,c)=>a-c,mulN:(a,c)=>a*c,inv:a=>Cr(a,e),sqrt:n.sqrt||(a=>s(l,a)),invertBatch:a=>$a(l,a),cmov:(a,c,u)=>u?c:a,toBytes:a=>r?Xr(a,i):Tt(a,i),fromBytes:a=>{if(a.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${a.length}`);return r?Yr(a):X(a)}});return Object.freeze(l)}function Lo(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Uo(e){const t=Lo(e);return t+Math.ceil(t/2)}function Sa(e,t,r=!1){const n=e.length,o=Lo(t),i=Uo(t);if(n<16||n1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);const s=r?X(e):Yr(e),l=K(s,t-j)+j;return r?Xr(l,o):Tt(l,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ka=BigInt(0),hr=BigInt(1);function Pa(e,t){const r=(o,i)=>{const s=i.negate();return o?s:i},n=o=>{const i=Math.ceil(t/o)+1,s=2**(o-1);return{windows:i,windowSize:s}};return{constTimeNegate:r,unsafeLadder(o,i){let s=e.ZERO,l=o;for(;i>ka;)i&hr&&(s=s.add(l)),l=l.double(),i>>=hr;return s},precomputeWindow(o,i){const{windows:s,windowSize:l}=n(i),a=[];let c=o,u=c;for(let d=0;d>=g,f>a&&(f-=m,s+=hr);const b=h,x=h+Math.abs(f)-1,A=p%2!==0,U=f<0;f===0?u=u.add(r(A,i[b])):c=c.add(r(U,i[x]))}return{p:c,f:u}},wNAFCached(o,i,s,l){const a=o._WINDOW_SIZE||1;let c=i.get(o);return c||(c=this.precomputeWindow(o,a),a!==1&&i.set(o,l(c))),this.wNAF(a,c,s)}}}function To(e){return Ea(e.Fp),Ae(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Bo(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ca(e){const t=To(e);Ae(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:Ba,hexToBytes:La}=ba,Dt={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){const{Err:t}=Dt;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");const r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:Ba(n),l:e.subarray(r+2)}},toSig(e){const{Err:t}=Dt,r=typeof e=="string"?La(e):e;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");const{d:o,l:i}=Dt._parseInt(r.subarray(2)),{d:s,l}=Dt._parseInt(i);if(l.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(e){const t=c=>Number.parseInt(c[0],16)&8?"00"+c:c,r=c=>{const u=c.toString(16);return u.length&1?`0${u}`:u},n=t(r(e.s)),o=t(r(e.r)),i=n.length/2,s=o.length/2,l=r(i),a=r(s);return`30${r(s+i+4)}02${a}${o}02${l}${n}`}},ht=BigInt(0),tt=BigInt(1);BigInt(2);const Gn=BigInt(3);BigInt(4);function Ua(e){const t=Ca(e),{Fp:r}=t,n=t.toBytes||((p,h,f)=>{const b=h.toAffine();return Ft(Uint8Array.from([4]),r.toBytes(b.x),r.toBytes(b.y))}),o=t.fromBytes||(p=>{const h=p.subarray(1),f=r.fromBytes(h.subarray(0,r.BYTES)),b=r.fromBytes(h.subarray(r.BYTES,2*r.BYTES));return{x:f,y:b}});function i(p){const{a:h,b:f}=t,b=r.sqr(p),x=r.mul(b,p);return r.add(r.add(x,r.mul(p,h)),f)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function s(p){return typeof p=="bigint"&&htr.eql(A,r.ZERO);return x(f)&&x(b)?d.ZERO:new d(f,b,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){const f=r.invertBatch(h.map(b=>b.pz));return h.map((b,x)=>b.toAffine(f[x])).map(d.fromAffine)}static fromHex(h){const f=d.fromAffine(o(Z("pointHex",h)));return f.assertValidity(),f}static fromPrivateKey(h){return d.BASE.multiply(a(h))}_setWindowSize(h){this._WINDOW_SIZE=h,c.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:h,y:f}=this.toAffine();if(!r.isValid(h)||!r.isValid(f))throw new Error("bad point: x or y not FE");const b=r.sqr(f),x=i(h);if(!r.eql(b,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:h}=this.toAffine();if(r.isOdd)return!r.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);const{px:f,py:b,pz:x}=this,{px:A,py:U,pz:C}=h,v=r.eql(r.mul(f,C),r.mul(A,x)),E=r.eql(r.mul(b,C),r.mul(U,x));return v&&E}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:h,b:f}=t,b=r.mul(f,Gn),{px:x,py:A,pz:U}=this;let C=r.ZERO,v=r.ZERO,E=r.ZERO,_=r.mul(x,x),V=r.mul(A,A),L=r.mul(U,U),k=r.mul(x,A);return k=r.add(k,k),E=r.mul(x,U),E=r.add(E,E),C=r.mul(h,E),v=r.mul(b,L),v=r.add(C,v),C=r.sub(V,v),v=r.add(V,v),v=r.mul(C,v),C=r.mul(k,C),E=r.mul(b,E),L=r.mul(h,L),k=r.sub(_,L),k=r.mul(h,k),k=r.add(k,E),E=r.add(_,_),_=r.add(E,_),_=r.add(_,L),_=r.mul(_,k),v=r.add(v,_),L=r.mul(A,U),L=r.add(L,L),_=r.mul(L,k),C=r.sub(C,_),E=r.mul(L,V),E=r.add(E,E),E=r.add(E,E),new d(C,v,E)}add(h){u(h);const{px:f,py:b,pz:x}=this,{px:A,py:U,pz:C}=h;let v=r.ZERO,E=r.ZERO,_=r.ZERO;const V=t.a,L=r.mul(t.b,Gn);let k=r.mul(f,A),O=r.mul(b,U),H=r.mul(x,C),D=r.add(f,b),y=r.add(A,U);D=r.mul(D,y),y=r.add(k,O),D=r.sub(D,y),y=r.add(f,x);let w=r.add(A,C);return y=r.mul(y,w),w=r.add(k,H),y=r.sub(y,w),w=r.add(b,x),v=r.add(U,C),w=r.mul(w,v),v=r.add(O,H),w=r.sub(w,v),_=r.mul(V,y),v=r.mul(L,H),_=r.add(v,_),v=r.sub(O,_),_=r.add(O,_),E=r.mul(v,_),O=r.add(k,k),O=r.add(O,k),H=r.mul(V,H),y=r.mul(L,y),O=r.add(O,H),H=r.sub(k,H),H=r.mul(V,H),y=r.add(y,H),k=r.mul(O,y),E=r.add(E,k),k=r.mul(w,y),v=r.mul(D,v),v=r.sub(v,k),k=r.mul(D,O),_=r.mul(w,_),_=r.add(_,k),new d(v,E,_)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return g.wNAFCached(this,c,h,f=>{const b=r.invertBatch(f.map(x=>x.pz));return f.map((x,A)=>x.toAffine(b[A])).map(d.fromAffine)})}multiplyUnsafe(h){const f=d.ZERO;if(h===ht)return f;if(l(h),h===tt)return this;const{endo:b}=t;if(!b)return g.unsafeLadder(this,h);let{k1neg:x,k1:A,k2neg:U,k2:C}=b.splitScalar(h),v=f,E=f,_=this;for(;A>ht||C>ht;)A&tt&&(v=v.add(_)),C&tt&&(E=E.add(_)),_=_.double(),A>>=tt,C>>=tt;return x&&(v=v.negate()),U&&(E=E.negate()),E=new d(r.mul(E.px,b.beta),E.py,E.pz),v.add(E)}multiply(h){l(h);let f=h,b,x;const{endo:A}=t;if(A){const{k1neg:U,k1:C,k2neg:v,k2:E}=A.splitScalar(f);let{p:_,f:V}=this.wNAF(C),{p:L,f:k}=this.wNAF(E);_=g.constTimeNegate(U,_),L=g.constTimeNegate(v,L),L=new d(r.mul(L.px,A.beta),L.py,L.pz),b=_.add(L),x=V.add(k)}else{const{p:U,f:C}=this.wNAF(f);b=U,x=C}return d.normalizeZ([b,x])[0]}multiplyAndAddUnsafe(h,f,b){const x=d.BASE,A=(C,v)=>v===ht||v===tt||!C.equals(x)?C.multiplyUnsafe(v):C.multiply(v),U=A(this,f).add(A(h,b));return U.is0()?void 0:U}toAffine(h){const{px:f,py:b,pz:x}=this,A=this.is0();h==null&&(h=A?r.ONE:r.inv(x));const U=r.mul(f,h),C=r.mul(b,h),v=r.mul(x,h);if(A)return{x:r.ZERO,y:r.ZERO};if(!r.eql(v,r.ONE))throw new Error("invZ was invalid");return{x:U,y:C}}isTorsionFree(){const{h,isTorsionFree:f}=t;if(h===tt)return!0;if(f)return f(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h,clearCofactor:f}=t;return h===tt?this:f?f(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),n(d,this,h)}toHex(h=!0){return ee(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const m=t.nBitLength,g=Pa(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:a,weierstrassEquation:i,isWithinCurveOrder:s}}function Ta(e){const t=To(e);return Ae(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Ia(e){const t=Ta(e),{Fp:r,n}=t,o=r.BYTES+1,i=2*r.BYTES+1;function s(y){return htee(Tt(y,t.nByteLength));function p(y){const w=n>>tt;return y>w}function h(y){return p(y)?l(-y):y}const f=(y,w,$)=>X(y.slice(w,$));class b{constructor(w,$,B){this.r=w,this.s=$,this.recovery=B,this.assertValidity()}static fromCompact(w){const $=t.nByteLength;return w=Z("compactSignature",w,$*2),new b(f(w,0,$),f(w,$,2*$))}static fromDER(w){const{r:$,s:B}=Dt.toSig(Z("DER",w));return new b($,B)}assertValidity(){if(!m(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!m(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(w){return new b(this.r,this.s,w)}recoverPublicKey(w){const{r:$,s:B,recovery:P}=this,I=E(Z("msgHash",w));if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");const z=P===2||P===3?$+t.n:$;if(z>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const R=P&1?"03":"02",et=c.fromHex(R+g(z)),Et=a(z),Kt=l(-I*Et),ce=l(B*Et),_t=c.BASE.multiplyAndAddUnsafe(et,Kt,ce);if(!_t)throw new Error("point at infinify");return _t.assertValidity(),_t}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,l(-this.s),this.recovery):this}toDERRawBytes(){return re(this.toDERHex())}toDERHex(){return Dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return re(this.toCompactHex())}toCompactHex(){return g(this.r)+g(this.s)}}const x={isValidPrivateKey(y){try{return u(y),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const y=Uo(t.n);return Sa(t.randomBytes(y),t.n)},precompute(y=8,w=c.BASE){return w._setWindowSize(y),w.multiply(BigInt(3)),w}};function A(y,w=!0){return c.fromPrivateKey(y).toRawBytes(w)}function U(y){const w=y instanceof Uint8Array,$=typeof y=="string",B=(w||$)&&y.length;return w?B===o||B===i:$?B===2*o||B===2*i:y instanceof c}function C(y,w,$=!0){if(U(y))throw new Error("first arg must be private key");if(!U(w))throw new Error("second arg must be public key");return c.fromHex(w).multiply(u(y)).toRawBytes($)}const v=t.bits2int||function(y){const w=X(y),$=y.length*8-t.nBitLength;return $>0?w>>BigInt($):w},E=t.bits2int_modN||function(y){return l(v(y))},_=Qr(t.nBitLength);function V(y){if(typeof y!="bigint")throw new Error("bigint expected");if(!(ht<=y&&y<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Tt(y,t.nByteLength)}function L(y,w,$=k){if(["recovered","canonical"].some(Nt=>Nt in $))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:P}=t;let{lowS:I,prehash:z,extraEntropy:R}=$;I==null&&(I=!0),y=Z("msgHash",y),z&&(y=Z("prehashed msgHash",B(y)));const et=E(y),Et=u(w),Kt=[V(Et),V(et)];if(R!=null){const Nt=R===!0?P(r.BYTES):R;Kt.push(Z("extraEntropy",Nt))}const ce=Ft(...Kt),_t=et;function ar(Nt){const Zt=v(Nt);if(!m(Zt))return;const Bn=a(Zt),nt=c.BASE.multiply(Zt).toAffine(),Gt=l(nt.x);if(Gt===ht)return;const Se=l(Bn*l(_t+Gt*Et));if(Se===ht)return;let Ln=(nt.x===Gt?0:2)|Number(nt.y&tt),Un=Se;return I&&p(Se)&&(Un=h(Se),Ln^=1),new b(Gt,Un,Ln)}return{seed:ce,k2sig:ar}}const k={lowS:t.lowS,prehash:!1},O={lowS:t.lowS,prehash:!1};function H(y,w,$=k){const{seed:B,k2sig:P}=L(y,w,$),I=t;return Co(I.hash.outputLen,I.nByteLength,I.hmac)(B,P)}c.BASE._setWindowSize(8);function D(y,w,$,B=O){const P=y;if(w=Z("msgHash",w),$=Z("publicKey",$),"strict"in B)throw new Error("options.strict was renamed to lowS");const{lowS:I,prehash:z}=B;let R,et;try{if(typeof P=="string"||P instanceof Uint8Array)try{R=b.fromDER(P)}catch(nt){if(!(nt instanceof Dt.Err))throw nt;R=b.fromCompact(P)}else if(typeof P=="object"&&typeof P.r=="bigint"&&typeof P.s=="bigint"){const{r:nt,s:Gt}=P;R=new b(nt,Gt)}else throw new Error("PARSE");et=c.fromHex($)}catch(nt){if(nt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(I&&R.hasHighS())return!1;z&&(w=t.hash(w));const{r:Et,s:Kt}=R,ce=E(w),_t=a(Kt),ar=l(ce*_t),Nt=l(Et*_t),Zt=c.BASE.multiplyAndAddUnsafe(et,ar,Nt)?.toAffine();return Zt?l(Zt.x)===Et:!1}return{CURVE:t,getPublicKey:A,getSharedSecret:C,sign:H,verify:D,ProjectivePoint:c,Signature:b,utils:x}}let Io=class extends Ao{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,Gs(t);const n=Gr(r);if(this.iHash=t.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 o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;snew Io(e,t).update(r).digest();Mo.create=(e,t)=>new Io(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ma(e){return{hash:e,hmac:(t,...r)=>Mo(e,t,Qs(...r)),randomBytes:So}}function Ra(e,t){const r=n=>Ia({...e,...Ma(n)});return Object.freeze({...r(t),create:r})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const We=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ne=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ro=BigInt(1),Oe=BigInt(2),Jn=(e,t)=>(e+t/Oe)/t;function No(e){const t=We,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),l=BigInt(44),a=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=Q(u,r,t)*u%t,m=Q(d,r,t)*u%t,g=Q(m,Oe,t)*c%t,p=Q(g,o,t)*g%t,h=Q(p,i,t)*p%t,f=Q(h,l,t)*h%t,b=Q(f,a,t)*f%t,x=Q(b,l,t)*h%t,A=Q(x,r,t)*u%t,U=Q(A,s,t)*p%t,C=Q(U,n,t)*c%t,v=Q(C,Oe,t);if(!Br.eql(Br.sqr(v),e))throw new Error("Cannot find square root");return v}const Br=Aa(We,void 0,void 0,{sqrt:No}),se=Ra({a:BigInt(0),b:BigInt(7),Fp:Br,n:Ne,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ne,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Ro*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),l=Jn(i*e,t),a=Jn(-n*e,t);let c=K(e-l*r-a*o,t),u=K(-l*n-a*i,t);const d=c>s,m=u>s;if(d&&(c=t-c),m&&(u=t-u),c>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:c,k2neg:m,k2:u}}}},kr),Ke=BigInt(0),Oo=e=>typeof e=="bigint"&&Ketypeof e=="bigint"&&Keo.charCodeAt(0)));r=Ft(n,n),Yn[e]=r}return kr(Ft(r,...t))}const tn=e=>e.toRawBytes(!0).slice(1),Lr=e=>Tt(e,32),fr=e=>K(e,We),xe=e=>K(e,Ne),en=se.ProjectivePoint,Oa=(e,t,r)=>en.BASE.multiplyAndAddUnsafe(e,t,r);function Ur(e){let t=se.utils.normPrivateKeyToScalar(e),r=en.fromPrivateKey(t);return{scalar:r.hasEvenY()?t:xe(-t),bytes:tn(r)}}function Ho(e){if(!Oo(e))throw new Error("bad x: need 0 < x < p");const t=fr(e*e),r=fr(t*e+BigInt(7));let n=No(r);n%Oe!==Ke&&(n=fr(-n));const o=new en(e,n,Ro);return o.assertValidity(),o}function zo(...e){return xe(X(He("BIP0340/challenge",...e)))}function Ha(e){return Ur(e).bytes}function za(e,t,r=So(32)){const n=Z("message",e),{bytes:o,scalar:i}=Ur(t),s=Z("auxRand",r,32),l=Lr(i^X(He("BIP0340/aux",s))),a=He("BIP0340/nonce",l,o,n),c=xe(X(a));if(c===Ke)throw new Error("sign failed: k is zero");const{bytes:u,scalar:d}=Ur(c),m=zo(u,o,n),g=new Uint8Array(64);if(g.set(u,0),g.set(Lr(xe(d+m*i)),32),!Vo(g,n,o))throw new Error("sign: Invalid signature produced");return g}function Vo(e,t,r){const n=Z("signature",e,64),o=Z("message",t),i=Z("publicKey",r,32);try{const s=Ho(X(i)),l=X(n.subarray(0,32));if(!Oo(l))return!1;const a=X(n.subarray(32,64));if(!Na(a))return!1;const c=zo(Lr(l),tn(s),o),u=Oa(s,a,xe(-c));return!(!u||!u.hasEvenY()||u.toAffine().x!==l)}catch{return!1}}const ue={getPublicKey:Ha,sign:za,verify:Vo,utils:{randomPrivateKey:se.utils.randomPrivateKey,lift_x:Ho,pointToBytes:tn,numberToBytesBE:Tt,bytesToNumberBE:X,taggedHash:He,mod:K}},pr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rn=e=>e instanceof Uint8Array,gr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),it=(e,t)=>e<<32-t|e>>>t,Va=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Va)throw new Error("Non little-endian hardware is not supported");const Da=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Y(e){if(!rn(e))throw new Error("Uint8Array expected");let t="";for(let r=0;rn+o.length,0));let r=0;return e.forEach(n=>{if(!rn(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}class Do{clone(){return this._cloneInto()}}function qo(e){const t=n=>e().update(Ee(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function jo(e=32){if(pr&&typeof pr.getRandomValues=="function")return pr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Tr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function ja(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Fo(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function Fa(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Tr(e.outputLen),Tr(e.blockLen)}function Wa(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ka(e,t){Fo(e);const r=t.outputLen;if(e.length>o&i),l=Number(r&i),a=n?4:0,c=n?0:4;e.setUint32(t+a,s,n),e.setUint32(t+c,l,n)}class Ga extends Do{constructor(t,r,n,o){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=gr(this.buffer)}update(t){st.exists(this);const{view:r,buffer:n,blockLen:o}=this;t=Ee(t);const i=t.length;for(let s=0;so-s&&(this.process(n,0),s=0);for(let d=s;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;de&t^~e&r,Ya=(e,t,r)=>e&t^e&r^t&r,Xa=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]),St=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),kt=new Uint32Array(64);class Wo extends Ga{constructor(){super(64,32,8,!1),this.A=St[0]|0,this.B=St[1]|0,this.C=St[2]|0,this.D=St[3]|0,this.E=St[4]|0,this.F=St[5]|0,this.G=St[6]|0,this.H=St[7]|0}get(){const{A:t,B:r,C:n,D:o,E:i,F:s,G:l,H:a}=this;return[t,r,n,o,i,s,l,a]}set(t,r,n,o,i,s,l,a){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=l|0,this.H=a|0}process(t,r){for(let d=0;d<16;d++,r+=4)kt[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const m=kt[d-15],g=kt[d-2],p=it(m,7)^it(m,18)^m>>>3,h=it(g,17)^it(g,19)^g>>>10;kt[d]=h+kt[d-7]+p+kt[d-16]|0}let{A:n,B:o,C:i,D:s,E:l,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){const m=it(l,6)^it(l,11)^it(l,25),g=u+m+Ja(l,a,c)+Xa[d]+kt[d]|0,h=(it(n,2)^it(n,13)^it(n,22))+Ya(n,o,i)|0;u=c,c=a,a=l,l=s+g|0,s=i,i=o,o=n,n=g+h|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,l=l+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,o,i,s,l,a,c,u)}roundClean(){kt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Qa extends Wo{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 ae=qo(()=>new Wo);qo(()=>new Qa);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function le(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function yt(...e){const t=(o,i)=>s=>o(i(s)),r=Array.from(e).reverse().reduce((o,i)=>o?t(o,i.encode):i.encode,void 0),n=e.reduce((o,i)=>o?t(o,i.decode):i.decode,void 0);return{encode:r,decode:n}}function wt(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return t.map(r=>{if(le(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("alphabet.decode input should be array of strings");return t.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);const n=e.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return n})}}}function vt(e=""){if(typeof e!="string")throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of t)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return t.join(e)},decode:t=>{if(typeof t!="string")throw new Error("join.decode input should be string");return t.split(e)}}}function Ge(e,t="="){if(le(e),typeof t!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*e%8;)r.push(t);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let o of r)if(typeof o!="string")throw new Error(`padding.decode: non-string input=${o}`);let n=r.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function Ko(e){if(typeof e!="function")throw new Error("normalize fn should be function");return{encode:t=>t,decode:t=>e(t)}}function Xn(e,t,r){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let n=0;const o=[],i=Array.from(e);for(i.forEach(s=>{if(le(s),s<0||s>=t)throw new Error(`Wrong integer: ${s}`)});;){let s=0,l=!0;for(let a=n;at?Zo(t,e%t):e,ze=(e,t)=>e+(t-Zo(e,t));function Ir(e,t,r,n){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(ze(t,r)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${ze(t,r)}`);let o=0,i=0;const s=2**r-1,l=[];for(const a of e){if(le(a),a>=2**t)throw new Error(`convertRadix2: invalid data word=${a} from=${t}`);if(o=o<32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=r;i-=r)l.push((o>>i-r&s)>>>0);o&=2**i-1}if(o=o<=t)throw new Error("Excess padding");if(!n&&o)throw new Error(`Non-zero padding: ${o}`);return n&&i>0&&l.push(o>>>0),l}function tl(e){return le(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return Xn(Array.from(t),2**8,e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(Xn(t,e,2**8))}}}function It(e,t=!1){if(le(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(ze(8,e)>32||ze(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Ir(Array.from(r),8,e,!t)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Ir(r,e,8,t))}}}function Qn(e){if(typeof e!="function")throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch{}}}const el=yt(It(4),wt("0123456789ABCDEF"),vt("")),rl=yt(It(5),wt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ge(5),vt(""));yt(It(5),wt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ge(5),vt(""));yt(It(5),wt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),vt(""),Ko(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const bt=yt(It(6),wt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ge(6),vt("")),nl=yt(It(6),wt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ge(6),vt("")),nn=e=>yt(tl(58),wt(e),vt("")),Mr=nn("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");nn("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");nn("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const to=[0,2,3,5,6,7,9,10,11],ol={encode(e){let t="";for(let r=0;r>25;let r=(e&33554431)<<5;for(let n=0;n>n&1)===1&&(r^=eo[n]);return r}function ro(e,t,r=1){const n=e.length;let o=1;for(let i=0;i126)throw new Error(`Invalid prefix (${e})`);o=he(o)^s>>5}o=he(o);for(let i=0;im)throw new TypeError(`Length ${g} exceeds limit ${m}`);return u=u.toLowerCase(),`${u}1${Rr.encode(d)}${ro(u,d,t)}`}function l(u,d=90){if(typeof u!="string")throw new Error(`bech32.decode input should be string, not ${typeof u}`);if(u.length<8||d!==!1&&u.length>d)throw new TypeError(`Wrong string length: ${u.length} (${u}). Expected (8..${d})`);const m=u.toLowerCase();if(u!==m&&u!==u.toUpperCase())throw new Error("String must be lowercase or uppercase");u=m;const g=u.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const p=u.slice(0,g),h=u.slice(g+1);if(h.length<6)throw new Error("Data must be at least 6 characters long");const f=Rr.decode(h).slice(0,-6),b=ro(p,f,t);if(!h.endsWith(b))throw new Error(`Invalid checksum in ${u}: expected "${b}"`);return{prefix:p,words:f}}const a=Qn(l);function c(u){const{prefix:d,words:m}=l(u,!1);return{prefix:d,words:m,bytes:n(m)}}return{encode:s,decode:l,decodeToBytes:c,decodeUnsafe:a,fromWords:n,fromWordsUnsafe:i,toWords:o}}const oe=Go("bech32");Go("bech32m");const il={encode:e=>new TextDecoder().decode(e),decode:e=>new TextEncoder().encode(e)},sl=yt(It(4),wt("0123456789abcdef"),vt(""),Ko(e=>{if(typeof e!="string"||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})),al={utf8:il,hex:sl,base16:el,base32:rl,base64:bt,base64url:nl,base58:Mr,base58xmr:ol};`${Object.keys(al).join(", ")}`;function br(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function no(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function ll(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function ft(e,...t){if(!ll(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const J=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),cl=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!cl)throw new Error("Non little-endian hardware is not supported");function dl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function ul(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n(Object.assign(t,e),t),Ut=16,fl=283;function on(e){return e<<1^fl&-(e>>7)}function Xt(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(t&1),e=on(e);return r}const Nr=(()=>{let e=new Uint8Array(256);for(let r=0,n=1;r<256;r++,n^=on(n))e[r]=n;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=(n^n>>4^n>>5^n>>6^n>>7^99)&255}return t})(),pl=Nr.map((e,t)=>Nr.indexOf(t)),gl=e=>e<<24|e>>>8,mr=e=>e<<8|e>>>24;function Jo(e,t){if(e.length!==256)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map((c,u)=>t(e[u])),n=r.map(mr),o=n.map(mr),i=o.map(mr),s=new Uint32Array(256*256),l=new Uint32Array(256*256),a=new Uint16Array(256*256);for(let c=0;c<256;c++)for(let u=0;u<256;u++){const d=c*256+u;s[d]=r[c]^n[u],l[d]=o[c]^i[u],a[d]=e[c]<<8|e[u]}return{sbox:e,sbox2:a,T0:r,T1:n,T2:o,T3:i,T01:s,T23:l}}const sn=Jo(Nr,e=>Xt(e,3)<<24|e<<16|e<<8|Xt(e,2)),Yo=Jo(pl,e=>Xt(e,11)<<24|Xt(e,13)<<16|Xt(e,9)<<8|Xt(e,14)),bl=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=on(r))e[t]=r;return e})();function Xo(e){ft(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:r}=sn,n=J(e),o=n.length,i=l=>at(r,l,l,l,l),s=new Uint32Array(t+28);s.set(n);for(let l=o;l6&&l%o===4&&(a=i(a)),s[l]=s[l-o]^a}return s}function ml(e){const t=Xo(e),r=t.slice(),n=t.length,{sbox2:o}=sn,{T0:i,T1:s,T2:l,T3:a}=Yo;for(let c=0;c>>8&255]^l[d>>>16&255]^a[d>>>24]}return r}function Bt(e,t,r,n,o,i){return e[r<<8&65280|n>>>8&255]^t[o>>>8&65280|i>>>24&255]}function at(e,t,r,n,o){return e[t&255|r&65280]|e[n>>>16&255|o>>>16&65280]<<16}function oo(e,t,r,n,o){const{sbox2:i,T01:s,T23:l}=sn;let a=0;t^=e[a++],r^=e[a++],n^=e[a++],o^=e[a++];const c=e.length/4-2;for(let p=0;p16)throw new Error(`aes/pcks5: wrong padding byte: ${n}`);const o=e.subarray(0,-n);for(let i=0;i{const l=Xo(t),{b:a,o:c,out:u}=vl(i,o,s),d=J(r);let m=d[0],g=d[1],p=d[2],h=d[3],f=0;for(;f+4<=a.length;)m^=a[f+0],g^=a[f+1],p^=a[f+2],h^=a[f+3],{s0:m,s1:g,s2:p,s3:h}=oo(l,m,g,p,h),c[f++]=m,c[f++]=g,c[f++]=p,c[f++]=h;if(o){const b=El(i.subarray(f*4));m^=b[0],g^=b[1],p^=b[2],h^=b[3],{s0:m,s1:g,s2:p,s3:h}=oo(l,m,g,p,h),c[f++]=m,c[f++]=g,c[f++]=p,c[f++]=h}return l.fill(0),u},decrypt:(i,s)=>{wl(i);const l=ml(t),a=J(r),c=Qo(i.length,s),u=J(i),d=J(c);let m=a[0],g=a[1],p=a[2],h=a[3];for(let f=0;f+4<=u.length;){const b=m,x=g,A=p,U=h;m=u[f+0],g=u[f+1],p=u[f+2],h=u[f+3];const{s0:C,s1:v,s2:E,s3:_}=yl(l,m,g,p,h);d[f++]=C^b,d[f++]=v^x,d[f++]=E^A,d[f++]=_^U}return l.fill(0),xl(c,o)}}}),ei=e=>Uint8Array.from(e.split("").map(t=>t.charCodeAt(0))),_l=ei("expand 16-byte k"),$l=ei("expand 32-byte k"),Al=J(_l),ri=J($l);ri.slice();function M(e,t){return e<>>32-t}function Or(e){return e.byteOffset%4===0}const ke=64,Sl=16,ni=2**32-1,io=new Uint32Array;function kl(e,t,r,n,o,i,s,l){const a=o.length,c=new Uint8Array(ke),u=J(c),d=Or(o)&&Or(i),m=d?J(o):io,g=d?J(i):io;for(let p=0;p=ni)throw new Error("arx: counter overflow");const h=Math.min(ke,a-p);if(d&&h===ke){const f=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let b=0,x;b{ft(l),ft(a),ft(c);const m=c.length;if(u||(u=new Uint8Array(m)),ft(u),br(d),d<0||d>=ni)throw new Error("arx: counter overflow");if(u.length0;)g.pop().fill(0);return u}}function Cl(e,t,r,n,o,i=20){let s=e[0],l=e[1],a=e[2],c=e[3],u=t[0],d=t[1],m=t[2],g=t[3],p=t[4],h=t[5],f=t[6],b=t[7],x=o,A=r[0],U=r[1],C=r[2],v=s,E=l,_=a,V=c,L=u,k=d,O=m,H=g,D=p,y=h,w=f,$=b,B=x,P=A,I=U,z=C;for(let et=0;eto?t.create().update(n).digest():n);for(let s=0;snew ii(e,t).update(r).digest();Je.create=(e,t)=>new ii(e,t);function Bl(e,t,r){return st.hash(e),Je(e,Ee(r),Ee(t))}const yr=new Uint8Array([0]),so=new Uint8Array;function Ll(e,t,r,n=32){if(st.hash(e),st.number(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(n/e.outputLen);r===void 0&&(r=so);const i=new Uint8Array(o*e.outputLen),s=Je.create(e,t),l=s._cloneInto(),a=new Uint8Array(s.outputLen);for(let c=0;c{for(var r in t)Ul(e,r,{get:t[r],enumerable:!0})},Jt=Symbol("verified"),Tl=e=>e instanceof Object;function an(e){if(!Tl(e)||typeof e.kind!="number"||typeof e.content!="string"||typeof e.created_at!="number"||typeof e.pubkey!="string"||!e.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(e.tags))return!1;for(let t=0;tli,QueueNode:()=>ai,binarySearch:()=>ln,insertEventIntoAscendingList:()=>Rl,insertEventIntoDescendingList:()=>Ml,normalizeURL:()=>si,utf8Decoder:()=>pt,utf8Encoder:()=>rt});var pt=new TextDecoder("utf-8"),rt=new TextEncoder;function si(e){e.indexOf("://")===-1&&(e="wss://"+e);let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),(t.port==="80"&&t.protocol==="ws:"||t.port==="443"&&t.protocol==="wss:")&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}function Ml(e,t){const[r,n]=ln(e,o=>t.id===o.id?0:t.created_at===o.created_at?-1:o.created_at-t.created_at);return n||e.splice(r,0,t),e}function Rl(e,t){const[r,n]=ln(e,o=>t.id===o.id?0:t.created_at===o.created_at?-1:t.created_at-o.created_at);return n||e.splice(r,0,t),e}function ln(e,t){let r=0,n=e.length-1;for(;r<=n;){const o=Math.floor((r+n)/2),i=t(e[o]);if(i===0)return[o,!0];i<0?n=o-1:r=o+1}return[r,!1]}var ai=class{value;next=null;prev=null;constructor(e){this.value=e}},li=class{first;last;constructor(){this.first=null,this.last=null}enqueue(e){const t=new ai(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,e.value}},Nl=class{generateSecretKey(){return ue.utils.randomPrivateKey()}getPublicKey(e){return Y(ue.getPublicKey(e))}finalizeEvent(e,t){const r=e;return r.pubkey=Y(ue.getPublicKey(t)),r.id=Le(r),r.sig=Y(ue.sign(Le(r),t)),r[Jt]=!0,r}verifyEvent(e){if(typeof e[Jt]=="boolean")return e[Jt];const t=Le(e);if(t!==e.id)return e[Jt]=!1,!1;try{const r=ue.verify(e.sig,t,e.pubkey);return e[Jt]=r,r}catch{return e[Jt]=!1,!1}}};function Ol(e){if(!an(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function Le(e){let t=ae(rt.encode(Ol(e)));return Y(t)}var Ye=new Nl,Hl=Ye.generateSecretKey,ci=Ye.getPublicKey,dt=Ye.finalizeEvent,Xe=Ye.verifyEvent,zl={};q(zl,{Application:()=>Dc,BadgeAward:()=>Gl,BadgeDefinition:()=>Mc,BlockedRelaysList:()=>wc,BookmarkList:()=>bc,Bookmarksets:()=>Uc,Calendar:()=>Gc,CalendarEventRSVP:()=>Jc,ChannelCreation:()=>gi,ChannelHideMessage:()=>yi,ChannelMessage:()=>mi,ChannelMetadata:()=>bi,ChannelMuteUser:()=>wi,ClassifiedListing:()=>Fc,ClientAuth:()=>xi,CommunitiesList:()=>mc,CommunityDefinition:()=>Qc,CommunityPostApproval:()=>ic,Contacts:()=>Wl,CreateOrUpdateProduct:()=>Oc,CreateOrUpdateStall:()=>Nc,Curationsets:()=>Tc,Date:()=>Kc,DirectMessageRelaysList:()=>_c,DraftClassifiedListing:()=>Wc,DraftLong:()=>zc,Emojisets:()=>Vc,EncryptedDirectMessage:()=>Kl,EventDeletion:()=>Zl,FileMetadata:()=>Ql,FileServerPreference:()=>$c,Followsets:()=>Cc,GenericRepost:()=>Yl,Genericlists:()=>Bc,GiftWrap:()=>vi,HTTPAuth:()=>un,Handlerinformation:()=>Xc,Handlerrecommendation:()=>Yc,Highlights:()=>hc,InterestsList:()=>xc,Interestsets:()=>Rc,JobFeedback:()=>lc,JobRequest:()=>sc,JobResult:()=>ac,Label:()=>oc,LightningPubRPC:()=>Sc,LiveChatMessage:()=>tc,LiveEvent:()=>qc,LongFormArticle:()=>Hc,Metadata:()=>ql,Mutelist:()=>fc,NWCWalletInfo:()=>Ac,NWCWalletRequest:()=>Ei,NWCWalletResponse:()=>kc,NostrConnect:()=>Pc,OpenTimestamps:()=>Xl,Pinlist:()=>pc,PrivateDirectMessage:()=>Jl,ProblemTracker:()=>ec,ProfileBadges:()=>Ic,PublicChatsList:()=>yc,Reaction:()=>dn,RecommendRelay:()=>Fl,RelayList:()=>gc,Relaysets:()=>Lc,Report:()=>rc,Reporting:()=>nc,Repost:()=>cn,Seal:()=>pi,SearchRelaysList:()=>vc,ShortTextNote:()=>jl,Time:()=>Zc,UserEmojiList:()=>Ec,UserStatuses:()=>jc,Zap:()=>uc,ZapGoal:()=>cc,ZapRequest:()=>dc,classifyKind:()=>Vl,isEphemeralKind:()=>hi,isKind:()=>Dl,isParameterizedReplaceableKind:()=>fi,isRegularKind:()=>di,isReplaceableKind:()=>ui});function di(e){return 1e3<=e&&e<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(e)}function ui(e){return[0,3].includes(e)||1e4<=e&&e<2e4}function hi(e){return 2e4<=e&&e<3e4}function fi(e){return 3e4<=e&&e<4e4}function Vl(e){return di(e)?"regular":ui(e)?"replaceable":hi(e)?"ephemeral":fi(e)?"parameterized":"unknown"}function Dl(e,t){const r=t instanceof Array?t:[t];return an(e)&&r.includes(e.kind)||!1}var ql=0,jl=1,Fl=2,Wl=3,Kl=4,Zl=5,cn=6,dn=7,Gl=8,pi=13,Jl=14,Yl=16,gi=40,bi=41,mi=42,yi=43,wi=44,Xl=1040,vi=1059,Ql=1063,tc=1311,ec=1971,rc=1984,nc=1984,oc=1985,ic=4550,sc=5999,ac=6999,lc=7e3,cc=9041,dc=9734,uc=9735,hc=9802,fc=1e4,pc=10001,gc=10002,bc=10003,mc=10004,yc=10005,wc=10006,vc=10007,xc=10015,Ec=10030,_c=10050,$c=10096,Ac=13194,Sc=21e3,xi=22242,Ei=23194,kc=23195,Pc=24133,un=27235,Cc=3e4,Bc=30001,Lc=30002,Uc=30003,Tc=30004,Ic=30008,Mc=30009,Rc=30015,Nc=30017,Oc=30018,Hc=30023,zc=30024,Vc=30030,Dc=30078,qc=30311,jc=30315,Fc=30402,Wc=30403,Kc=31922,Zc=31923,Gc=31924,Jc=31925,Yc=31989,Xc=31990,Qc=34550;function td(e,t){if(e.ids&&e.ids.indexOf(t.id)===-1||e.kinds&&e.kinds.indexOf(t.kind)===-1||e.authors&&e.authors.indexOf(t.pubkey)===-1)return!1;for(let r in e)if(r[0]==="#"){let n=r.slice(1),o=e[`#${n}`];if(o&&!t.tags.find(([i,s])=>i===r.slice(1)&&o.indexOf(s)!==-1))return!1}return!(e.since&&t.created_ate.until)}function ed(e,t){for(let r=0;rQe,getInt:()=>_i,getSubscriptionId:()=>$i,matchEventId:()=>nd,matchEventKind:()=>id,matchEventPubkey:()=>od});function Qe(e,t){let r=t.length+3,n=e.indexOf(`"${t}":`)+r,o=e.slice(n).indexOf('"')+n+1;return e.slice(o,o+64)}function _i(e,t){let r=t.length,n=e.indexOf(`"${t}":`)+r+3,o=e.slice(n),i=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,i),10)}function $i(e){let t=e.slice(0,22).indexOf('"EVENT"');if(t===-1)return null;let r=e.slice(t+7+1).indexOf('"');if(r===-1)return null;let n=t+7+1+r,o=e.slice(n+1,80).indexOf('"');if(o===-1)return null;let i=n+1+o;return e.slice(n+1,i)}function nd(e,t){return t===Qe(e,"id")}function od(e,t){return t===Qe(e,"pubkey")}function id(e,t){return t===_i(e,"kind")}var sd={};q(sd,{makeAuthEvent:()=>Ai});function Ai(e,t){return{kind:xi,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}async function ad(){return new Promise(e=>{const t=new MessageChannel,r=()=>{t.port1.removeEventListener("message",r),e()};t.port1.addEventListener("message",r),t.port2.postMessage(0),t.port1.start()})}var Si=class{url;_connected=!1;onclose=null;onnotice=e=>console.debug(`NOTICE from ${this.url}: ${e}`);_onauth=null;baseEoseTimeout=4400;connectionTimeout=4400;publishTimeout=4400;openSubs=new Map;connectionTimeoutHandle;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;incomingMessageQueue=new li;queueRunning=!1;challenge;serial=0;verifyEvent;_WebSocket;constructor(e,t){this.url=si(e),this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation||WebSocket}static async connect(e,t){const r=new Si(e,t);return await r.connect(),r}closeAllSubscriptions(e){for(let[t,r]of this.openSubs)r.close(e);this.openSubs.clear();for(let[t,r]of this.openEventPublishes)r.reject(new Error(e));this.openEventPublishes.clear();for(let[t,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,t)=>{this.connectionTimeoutHandle=setTimeout(()=>{t("connection timed out"),this.connectionPromise=void 0,this.onclose?.(),this.closeAllSubscriptions("relay connection timed out")},this.connectionTimeout);try{this.ws=new this._WebSocket(this.url)}catch(r){t(r);return}this.ws.onopen=()=>{clearTimeout(this.connectionTimeoutHandle),this._connected=!0,e()},this.ws.onerror=r=>{t(r.message||"websocket error"),this._connected&&(this._connected=!1,this.connectionPromise=void 0,this.onclose?.(),this.closeAllSubscriptions("relay connection errored"))},this.ws.onclose=async()=>{this._connected&&(this._connected=!1,this.connectionPromise=void 0,this.onclose?.(),this.closeAllSubscriptions("relay connection closed"))},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}async runQueue(){for(this.queueRunning=!0;this.handleNext()!==!1;)await ad();this.queueRunning=!1}handleNext(){const e=this.incomingMessageQueue.dequeue();if(!e)return!1;const t=$i(e);if(t){const r=this.openSubs.get(t);if(!r)return;const n=Qe(e,"id"),o=r.alreadyHaveEvent?.(n);if(r.receivedEvent?.(this,n),o)return}try{let r=JSON.parse(e);switch(r[0]){case"EVENT":{const n=this.openSubs.get(r[1]),o=r[2];this.verifyEvent(o)&&ed(n.filters,o)&&n.onevent(o);return}case"COUNT":{const n=r[1],o=r[2],i=this.openCountRequests.get(n);i&&(i.resolve(o.count),this.openCountRequests.delete(n));return}case"EOSE":{const n=this.openSubs.get(r[1]);if(!n)return;n.receivedEose();return}case"OK":{const n=r[1],o=r[2],i=r[3],s=this.openEventPublishes.get(n);s&&(o?s.resolve(i):s.reject(new Error(i)),this.openEventPublishes.delete(n));return}case"CLOSED":{const n=r[1],o=this.openSubs.get(n);if(!o)return;o.closed=!0,o.close(r[2]);return}case"NOTICE":this.onnotice(r[1]);return;case"AUTH":{this.challenge=r[1],this._onauth?.(r[1]);return}}}catch{return}}async send(e){if(!this.connectionPromise)throw new Error("sending on closed connection");this.connectionPromise.then(()=>{this.ws?.send(e)})}async auth(e){if(!this.challenge)throw new Error("can't perform auth, no challenge was received");const t=await e(Ai(this.url,this.challenge)),r=new Promise((n,o)=>{this.openEventPublishes.set(t.id,{resolve:n,reject:o})});return this.send('["AUTH",'+JSON.stringify(t)+"]"),r}async publish(e){const t=new Promise((r,n)=>{this.openEventPublishes.set(e.id,{resolve:r,reject:n})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),setTimeout(()=>{const r=this.openEventPublishes.get(e.id);r&&(r.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout),t}async count(e,t){this.serial++;const r=t?.id||"count:"+this.serial,n=new Promise((o,i)=>{this.openCountRequests.set(r,{resolve:o,reject:i})});return this.send('["COUNT","'+r+'",'+JSON.stringify(e).substring(1)),n}subscribe(e,t){const r=this.prepareSubscription(e,t);return r.fire(),r}prepareSubscription(e,t){this.serial++;const r=t.id||"sub:"+this.serial,n=new ld(this,r,e,t);return this.openSubs.set(r,n),n}close(){this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.ws?.close()}_onmessage(e){this.incomingMessageQueue.enqueue(e.data),this.queueRunning||this.runQueue()}},ld=class{relay;id;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oneose;onclose;eoseTimeout;eoseTimeoutHandle;constructor(e,t,r,n){this.relay=e,this.filters=r,this.id=t,this.alreadyHaveEvent=n.alreadyHaveEvent,this.receivedEvent=n.receivedEvent,this.eoseTimeout=n.eoseTimeout||e.baseEoseTimeout,this.oneose=n.oneose,this.onclose=n.onclose,this.onevent=n.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(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(e="closed by caller"){!this.closed&&this.relay.connected&&(this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]"),this.closed=!0),this.relay.openSubs.delete(this.id),this.onclose?.(e)}},ki;try{ki=WebSocket}catch{}var tr=class extends Si{constructor(e){super(e,{verifyEvent:Xe,websocketImplementation:ki})}static async connect(e){const t=new tr(e);return await t.connect(),t}},cd;try{cd=WebSocket}catch{}var dd={};q(dd,{BECH32_REGEX:()=>Pi,Bech32MaxSize:()=>hn,NostrTypeGuard:()=>ud,decode:()=>er,encodeBytes:()=>nr,naddrEncode:()=>yd,neventEncode:()=>md,noteEncode:()=>gd,nprofileEncode:()=>bd,npubEncode:()=>pd,nsecEncode:()=>fd});var ud={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},hn=5e3,Pi=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function hd(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=e&255,t}function er(e){let{prefix:t,words:r}=oe.decode(e,hn),n=new Uint8Array(oe.fromWords(r));switch(t){case"nprofile":{let o=wr(n);if(!o[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:Y(o[0][0]),relays:o[1]?o[1].map(i=>pt.decode(i)):[]}}}case"nevent":{let o=wr(n);if(!o[0]?.[0])throw new Error("missing TLV 0 for nevent");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(o[2]&&o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(o[3]&&o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:Y(o[0][0]),relays:o[1]?o[1].map(i=>pt.decode(i)):[],author:o[2]?.[0]?Y(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(Y(o[3][0]),16):void 0}}}case"naddr":{let o=wr(n);if(!o[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!o[2]?.[0])throw new Error("missing TLV 2 for naddr");if(o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!o[3]?.[0])throw new Error("missing TLV 3 for naddr");if(o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:pt.decode(o[0][0]),pubkey:Y(o[2][0]),kind:parseInt(Y(o[3][0]),16),relays:o[1]?o[1].map(i=>pt.decode(i)):[]}}}case"nsec":return{type:t,data:n};case"npub":case"note":return{type:t,data:Y(n)};default:throw new Error(`unknown prefix ${t}`)}}function wr(e){let t={},r=e;for(;r.length>0;){let n=r[0],o=r[1],i=r.slice(2,2+o);if(r=r.slice(2+o),i.lengthrt.encode(r))});return rr("nprofile",t)}function md(e){let t;e.kind!==void 0&&(t=hd(e.kind));let r=fn({0:[ne(e.id)],1:(e.relays||[]).map(n=>rt.encode(n)),2:e.author?[ne(e.author)]:[],3:t?[new Uint8Array(t)]:[]});return rr("nevent",r)}function yd(e){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,e.kind,!1);let r=fn({0:[rt.encode(e.identifier)],1:(e.relays||[]).map(n=>rt.encode(n)),2:[ne(e.pubkey)],3:[new Uint8Array(t)]});return rr("naddr",r)}function fn(e){let t=[];return Object.entries(e).reverse().forEach(([r,n])=>{n.forEach(o=>{let i=new Uint8Array(o.length+2);i.set([parseInt(r)],0),i.set([o.length],1),i.set(o,2),t.push(i)})}),Ze(...t)}var wd={};q(wd,{decrypt:()=>vd,encrypt:()=>Ci});async function Ci(e,t,r){const n=e instanceof Uint8Array?Y(e):e,o=se.getSharedSecret(n,"02"+t),i=Bi(o);let s=Uint8Array.from(jo(16)),l=rt.encode(r),a=ti(i,s).encrypt(l),c=bt.encode(new Uint8Array(a)),u=bt.encode(new Uint8Array(s.buffer));return`${c}?iv=${u}`}async function vd(e,t,r){const n=e instanceof Uint8Array?Y(e):e;let[o,i]=r.split("?iv="),s=se.getSharedSecret(n,"02"+t),l=Bi(s),a=bt.decode(i),c=bt.decode(o),u=ti(l,a).decrypt(c);return pt.decode(u)}function Bi(e){return e.slice(1,33)}var xd={};q(xd,{NIP05_REGEX:()=>pn,isNip05:()=>Ed,isValid:()=>Ad,queryProfile:()=>Li,searchDomain:()=>$d,useFetchImplementation:()=>_d});var pn=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,Ed=e=>pn.test(e||""),or;try{or=fetch}catch{}function _d(e){or=e}async function $d(e,t=""){try{const r=`https://${e}/.well-known/nostr.json?name=${t}`,n=await or(r,{redirect:"manual"});if(n.status!==200)throw Error("Wrong response code");return(await n.json()).names}catch{return{}}}async function Li(e){const t=e.match(pn);if(!t)return null;const[,r="_",n]=t;try{const o=`https://${n}/.well-known/nostr.json?name=${r}`,i=await or(o,{redirect:"manual"});if(i.status!==200)throw Error("Wrong response code");const s=await i.json(),l=s.names[r];return l?{pubkey:l,relays:s.relays?.[l]}:null}catch{return null}}async function Ad(e,t){const r=await Li(t);return r?r.pubkey===e:!1}var Sd={};q(Sd,{parse:()=>kd});function kd(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[]},r=[];for(const n of e.tags)n[0]==="e"&&n[1]&&r.push(n),n[0]==="p"&&n[1]&&t.profiles.push({pubkey:n[1],relays:n[2]?[n[2]]:[]});for(let n=0;nBd,useFetchImplementation:()=>Cd});var Ui;try{Ui=fetch}catch{}function Cd(e){Ui=e}async function Bd(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var Ld={};q(Ld,{fastEventHash:()=>Ii,getPow:()=>Ti,minePow:()=>Ud});function Ti(e){let t=0;for(let r=0;r<64;r+=8){const n=parseInt(e.substring(r,r+8),16);if(n===0)t+=32;else{t+=Math.clz32(n);break}}return t}function Ud(e,t){let r=0;const n=e,o=["nonce",r.toString(),t.toString()];for(n.tags.push(o);;){const i=Math.floor(new Date().getTime()/1e3);if(i!==n.created_at&&(r=0,n.created_at=i),o[1]=(++r).toString(),n.id=Ii(n),Ti(n.id)>=t)break}return n}function Ii(e){return Y(ae(rt.encode(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))))}var Td={};q(Td,{finishRepostEvent:()=>Id,getRepostedEvent:()=>Md,getRepostedEventPointer:()=>Mi});function Id(e,t,r,n){return dt({kind:cn,tags:[...e.tags??[],["e",t.id,r],["p",t.pubkey]],content:e.content===""?"":JSON.stringify(t),created_at:e.created_at},n)}function Mi(e){if(e.kind!==cn)return;let t,r;for(let n=e.tags.length-1;n>=0&&(t===void 0||r===void 0);n--){const o=e.tags[n];o.length>=2&&(o[0]==="e"&&t===void 0?t=o:o[0]==="p"&&r===void 0&&(r=o))}if(t!==void 0)return{id:t[1],relays:[t[2],r?.[2]].filter(n=>typeof n=="string"),author:r?.[1]}}function Md(e,{skipVerification:t}={}){const r=Mi(e);if(r===void 0||e.content==="")return;let n;try{n=JSON.parse(e.content)}catch{return}if(n.id===r.id&&!(!t&&!Xe(n)))return n}var Rd={};q(Rd,{NOSTR_URI_REGEX:()=>ir,parse:()=>Od,test:()=>Nd});var ir=new RegExp(`nostr:(${Pi.source})`);function Nd(e){return typeof e=="string"&&new RegExp(`^${ir.source}$`).test(e)}function Od(e){const t=e.match(new RegExp(`^${ir.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:er(t[1])}}var Hd={};q(Hd,{finishReactionEvent:()=>zd,getReactedEventPointer:()=>Vd});function zd(e,t,r){const n=t.tags.filter(o=>o.length>=2&&(o[0]==="e"||o[0]==="p"));return dt({...e,kind:dn,tags:[...e.tags??[],...n,["e",t.id],["p",t.pubkey]],content:e.content??"+"},r)}function Vd(e){if(e.kind!==dn)return;let t,r;for(let n=e.tags.length-1;n>=0&&(t===void 0||r===void 0);n--){const o=e.tags[n];o.length>=2&&(o[0]==="e"&&t===void 0?t=o:o[0]==="p"&&r===void 0&&(r=o))}if(!(t===void 0||r===void 0))return{id:t[1],relays:[t[2],r[2]].filter(n=>n!==void 0),author:r[1]}}var Dd={};q(Dd,{matchAll:()=>qd,regex:()=>gn,replaceAll:()=>jd});var gn=()=>new RegExp(`\\b${ir.source}\\b`,"g");function*qd(e){const t=e.matchAll(gn());for(const r of t)try{const[n,o]=r;yield{uri:n,value:o,decoded:er(o),start:r.index,end:r.index+n.length}}catch{}}function jd(e,t){return e.replaceAll(gn(),(r,n)=>t({uri:r,value:n,decoded:er(n)}))}var Fd={};q(Fd,{channelCreateEvent:()=>Wd,channelHideMessageEvent:()=>Gd,channelMessageEvent:()=>Zd,channelMetadataEvent:()=>Kd,channelMuteUserEvent:()=>Jd});var Wd=(e,t)=>{let r;if(typeof e.content=="object")r=JSON.stringify(e.content);else if(typeof e.content=="string")r=e.content;else return;return dt({kind:gi,tags:[...e.tags??[]],content:r,created_at:e.created_at},t)},Kd=(e,t)=>{let r;if(typeof e.content=="object")r=JSON.stringify(e.content);else if(typeof e.content=="string")r=e.content;else return;return dt({kind:bi,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:r,created_at:e.created_at},t)},Zd=(e,t)=>{const r=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&r.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),dt({kind:mi,tags:[...r,...e.tags??[]],content:e.content,created_at:e.created_at},t)},Gd=(e,t)=>{let r;if(typeof e.content=="object")r=JSON.stringify(e.content);else if(typeof e.content=="string")r=e.content;else return;return dt({kind:yi,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:r,created_at:e.created_at},t)},Jd=(e,t)=>{let r;if(typeof e.content=="object")r=JSON.stringify(e.content);else if(typeof e.content=="string")r=e.content;else return;return dt({kind:wi,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:r,created_at:e.created_at},t)},Yd={};q(Yd,{EMOJI_SHORTCODE_REGEX:()=>Ri,matchAll:()=>Xd,regex:()=>bn,replaceAll:()=>Qd});var Ri=/:(\w+):/,bn=()=>new RegExp(`\\B${Ri.source}\\B`,"g");function*Xd(e){const t=e.matchAll(bn());for(const r of t)try{const[n,o]=r;yield{shortcode:n,name:o,start:r.index,end:r.index+n.length}}catch{}}function Qd(e,t){return e.replaceAll(bn(),(r,n)=>t({shortcode:r,name:n}))}var tu={};q(tu,{useFetchImplementation:()=>eu,validateGithub:()=>ru});var mn;try{mn=fetch}catch{}function eu(e){mn=e}async function ru(e,t,r){try{return await(await mn(`https://gist.github.com/${t}/${r}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch{return!1}}var nu={};q(nu,{decrypt:()=>xn,encrypt:()=>vn,getConversationKey:()=>yn,v2:()=>lu});var Ni=1,Oi=65535;function yn(e,t){const r=se.getSharedSecret(e,"02"+t).subarray(1,33);return Bl(ae,r,"nip44-v2")}function Hi(e,t){const r=Ll(ae,e,t,76);return{chacha_key:r.subarray(0,32),chacha_nonce:r.subarray(32,44),hmac_key:r.subarray(44,76)}}function wn(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<Oi)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function iu(e){const t=rt.encode(e),r=t.length,n=ou(r),o=new Uint8Array(wn(r)-r);return Ze(n,t,o)}function su(e){const t=new DataView(e.buffer).getUint16(0),r=e.subarray(2,2+t);if(tOi||r.length!==t||e.length!==2+wn(t))throw new Error("invalid padding");return pt.decode(r)}function zi(e,t,r){if(r.length!==32)throw new Error("AAD associated data must be 32 bytes");const n=Ze(r,t);return Je(ae,e,n)}function au(e){if(typeof e!="string")throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if(e[0]==="#")throw new Error("unknown encryption version");let r;try{r=bt.decode(e)}catch(i){throw new Error("invalid base64: "+i.message)}const n=r.length;if(n<99||n>65603)throw new Error("invalid data length: "+n);const o=r[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:r.subarray(1,33),ciphertext:r.subarray(33,-32),mac:r.subarray(-32)}}function vn(e,t,r=jo(32)){const{chacha_key:n,chacha_nonce:o,hmac_key:i}=Hi(t,r),s=iu(e),l=oi(n,o,s),a=zi(i,l,r);return bt.encode(Ze(new Uint8Array([2]),r,l,a))}function xn(e,t){const{nonce:r,ciphertext:n,mac:o}=au(e),{chacha_key:i,chacha_nonce:s,hmac_key:l}=Hi(t,r),a=zi(l,n,r);if(!ul(a,o))throw new Error("invalid MAC");const c=oi(i,s,n);return su(c)}var lu={utils:{getConversationKey:yn,calcPaddedLen:wn},encrypt:vn,decrypt:xn},cu={};q(cu,{makeNwcRequestEvent:()=>uu,parseConnectionString:()=>du});function du(e){const{pathname:t,searchParams:r}=new URL(e),n=t,o=r.get("relay"),i=r.get("secret");if(!n||!o||!i)throw new Error("invalid connection string");return{pubkey:n,relay:o,secret:i}}async function uu(e,t,r){const o=await Ci(t,e,JSON.stringify({method:"pay_invoice",params:{invoice:r}})),i={kind:Ei,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e]]};return dt(i,t)}var hu={};q(hu,{getZapEndpoint:()=>pu,makeZapReceipt:()=>mu,makeZapRequest:()=>gu,useFetchImplementation:()=>fu,validateZapRequest:()=>bu});var En;try{En=fetch}catch{}function fu(e){En=e}async function pu(e){try{let t="",{lud06:r,lud16:n}=JSON.parse(e.content);if(r){let{words:s}=oe.decode(r,1e3),l=oe.fromWords(s);t=pt.decode(l)}else if(n){let[s,l]=n.split("@");t=new URL(`/.well-known/lnurlp/${s}`,`https://${l}`).toString()}else return null;let i=await(await En(t)).json();if(i.allowsNostr&&i.nostrPubkey)return i.callback}catch{}return null}function gu({profile:e,event:t,amount:r,relays:n,comment:o=""}){if(!r)throw new Error("amount not given");if(!e)throw new Error("profile not given");let i={kind:9734,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",e],["amount",r.toString()],["relays",...n]]};return t&&i.tags.push(["e",t]),i}function bu(e){let t;try{t=JSON.parse(e)}catch{return"Invalid zap request JSON."}if(!an(t))return"Zap request is not a valid Nostr event.";if(!Xe(t))return"Invalid signature on zap request.";let r=t.tags.find(([i,s])=>i==="p"&&s);if(!r)return"Zap request doesn't have a 'p' tag.";if(!r[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let n=t.tags.find(([i,s])=>i==="e"&&s);return n&&!n[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([i,s])=>i==="relays"&&s)?null:"Zap request doesn't have a 'relays' tag."}function mu({zapRequest:e,preimage:t,bolt11:r,paidAt:n}){let o=JSON.parse(e),i=o.tags.filter(([l])=>l==="e"||l==="p"||l==="a"),s={kind:9735,created_at:Math.round(n.getTime()/1e3),content:"",tags:[...i,["P",o.pubkey],["bolt11",r],["description",e]]};return t&&s.tags.push(["preimage",t]),s}var yu={};q(yu,{createRumor:()=>Fi,createSeal:()=>Wi,createWrap:()=>Ki,unwrapEvent:()=>Zi,unwrapManyEvents:()=>xu,wrapEvent:()=>Hr,wrapManyEvents:()=>vu});var wu=2*24*60*60,Vi=()=>Math.round(Date.now()/1e3),Di=()=>Math.round(Vi()-Math.random()*wu),qi=(e,t)=>yn(e,t),ji=(e,t,r)=>vn(JSON.stringify(e),qi(t,r)),ao=(e,t)=>JSON.parse(xn(e.content,qi(t,e.pubkey)));function Fi(e,t){const r={created_at:Vi(),content:"",tags:[],...e,pubkey:ci(t)};return r.id=Le(r),r}function Wi(e,t,r){return dt({kind:pi,content:ji(e,t,r),created_at:Di(),tags:[]},t)}function Ki(e,t){const r=Hl();return dt({kind:vi,content:ji(e,r,t),created_at:Di(),tags:[["p",t]]},r)}function Hr(e,t,r){const n=Fi(e,t),o=Wi(n,t,r);return Ki(o,r)}function vu(e,t,r){if(!r||r.length===0)throw new Error("At least one recipient is required.");const n=ci(t),o=[Hr(e,t,n)];return r.forEach(i=>{o.push(Hr(e,t,i))}),o}function Zi(e,t){const r=ao(e,t);return ao(r,t)}function xu(e,t){let r=[];return e.forEach(n=>{r.push(Zi(n,t))}),r.sort((n,o)=>n.created_at-o.created_at),r}var Eu={};q(Eu,{getToken:()=>_u,hashPayload:()=>_n,unpackEventFromToken:()=>Ji,validateEvent:()=>rs,validateEventKind:()=>Xi,validateEventMethodTag:()=>ts,validateEventPayloadTag:()=>es,validateEventTimestamp:()=>Yi,validateEventUrlTag:()=>Qi,validateToken:()=>$u});var Gi="Nostr ";async function _u(e,t,r,n=!1,o){const i={kind:un,tags:[["u",e],["method",t]],created_at:Math.round(new Date().getTime()/1e3),content:""};o&&i.tags.push(["payload",_n(o)]);const s=await r(i);return(n?Gi:"")+bt.encode(rt.encode(JSON.stringify(s)))}async function $u(e,t,r){const n=await Ji(e).catch(i=>{throw i});return await rs(n,t,r).catch(i=>{throw i})}async function Ji(e){if(!e)throw new Error("Missing token");e=e.replace(Gi,"");const t=pt.decode(bt.decode(e));if(!t||t.length===0||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function Yi(e){return e.created_at?Math.round(new Date().getTime()/1e3)-e.created_at<60:!1}function Xi(e){return e.kind===un}function Qi(e,t){const r=e.tags.find(n=>n[0]==="u");return r?r.length>0&&r[1]===t:!1}function ts(e,t){const r=e.tags.find(n=>n[0]==="method");return r?r.length>0&&r[1].toLowerCase()===t.toLowerCase():!1}function _n(e){const t=ae(rt.encode(JSON.stringify(e)));return Y(t)}function es(e,t){const r=e.tags.find(o=>o[0]==="payload");if(!r)return!1;const n=_n(t);return r.length>0&&r[1]===n}async function rs(e,t,r,n){if(!Xe(e))throw new Error("Invalid nostr event, signature invalid");if(!Xi(e))throw new Error("Invalid nostr event, kind invalid");if(!Yi(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!Qi(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!ts(e,r))throw new Error("Invalid nostr event, method tag invalid");if(n&&typeof n=="object"&&Object.keys(n).length>0&&!es(e,n))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}var Au=ct` + :host { + --border-color: var(--sl-color-neutral-200); + --border-radius: var(--sl-border-radius-medium); + --border-width: 1px; + --padding: var(--sl-spacing-large); + + display: inline-block; + } + + .card { + display: flex; + flex-direction: column; + background-color: var(--sl-panel-background-color); + box-shadow: var(--sl-shadow-x-small); + border: solid var(--border-width) var(--border-color); + border-radius: var(--border-radius); + } + + .card__image { + display: flex; + border-top-left-radius: var(--border-radius); + border-top-right-radius: var(--border-radius); + margin: calc(-1 * var(--border-width)); + overflow: hidden; + } + + .card__image::slotted(img) { + display: block; + width: 100%; + } + + .card:not(.card--has-image) .card__image { + display: none; + } + + .card__header { + display: block; + border-bottom: solid var(--border-width) var(--border-color); + padding: calc(var(--padding) / 2) var(--padding); + } + + .card:not(.card--has-header) .card__header { + display: none; + } + + .card:not(.card--has-image) .card__header { + border-top-left-radius: var(--border-radius); + border-top-right-radius: var(--border-radius); + } + + .card__body { + display: block; + padding: var(--padding); + } + + .card--has-footer .card__footer { + display: block; + border-top: solid var(--border-width) var(--border-color); + padding: var(--padding); + } + + .card:not(.card--has-footer) .card__footer { + display: none; + } +`,ns=class{constructor(e,...t){this.slotNames=[],this.handleSlotChange=r=>{const n=r.target;(this.slotNames.includes("[default]")&&!n.name||n.name&&this.slotNames.includes(n.name))&&this.host.requestUpdate()},(this.host=e).addController(this),this.slotNames=t}hasDefaultSlot(){return[...this.host.childNodes].some(e=>{if(e.nodeType===e.TEXT_NODE&&e.textContent.trim()!=="")return!0;if(e.nodeType===e.ELEMENT_NODE){const t=e;if(t.tagName.toLowerCase()==="sl-visually-hidden")return!1;if(!t.hasAttribute("slot"))return!0}return!1})}hasNamedSlot(e){return this.host.querySelector(`:scope > [slot="${e}"]`)!==null}test(e){return e==="[default]"?this.hasDefaultSlot():this.hasNamedSlot(e)}hostConnected(){this.host.shadowRoot.addEventListener("slotchange",this.handleSlotChange)}hostDisconnected(){this.host.shadowRoot.removeEventListener("slotchange",this.handleSlotChange)}},sr=ct` + :host { + box-sizing: border-box; + } + + :host *, + :host *::before, + :host *::after { + box-sizing: inherit; + } + + [hidden] { + display: none !important; + } +`,Ue,Mt=class extends gt{constructor(){super(),xs(this,Ue,!1),this.initialReflectedProperties=new Map,Object.entries(this.constructor.dependencies).forEach(([e,t])=>{this.constructor.define(e,t)})}emit(e,t){const r=new CustomEvent(e,_e({bubbles:!0,cancelable:!1,composed:!0,detail:{}},t));return this.dispatchEvent(r),r}static define(e,t=this,r={}){const n=customElements.get(e);if(!n){try{customElements.define(e,t,r)}catch{customElements.define(e,class extends t{},r)}return}let o=" (unknown version)",i=o;"version"in t&&t.version&&(o=" v"+t.version),"version"in n&&n.version&&(i=" v"+n.version),!(o&&i&&o===i)&&console.warn(`Attempted to register <${e}>${o}, but <${e}>${i} has already been registered.`)}attributeChangedCallback(e,t,r){vs(this,Ue)||(this.constructor.elementProperties.forEach((n,o)=>{n.reflect&&this[o]!=null&&this.initialReflectedProperties.set(o,this[o])}),Es(this,Ue,!0)),super.attributeChangedCallback(e,t,r)}willUpdate(e){super.willUpdate(e),this.initialReflectedProperties.forEach((t,r)=>{e.has(r)&&this[r]==null&&(this[r]=t)})}};Ue=new WeakMap;Mt.version="2.18.0";Mt.dependencies={};T([S()],Mt.prototype,"dir",2);T([S()],Mt.prototype,"lang",2);/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Su={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},ku=e=>(...t)=>({_$litDirective$:e,values:t});let Pu=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,r,n){this._$Ct=t,this._$AM=r,this._$Ci=n}_$AS(t,r){return this.update(t,r)}update(t,r){return this.render(...r)}};/** + * @license + * Copyright 2018 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const os=ku(class extends Pu{constructor(e){if(super(e),e.type!==Su.ATTRIBUTE||e.name!=="class"||e.strings?.length>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(e){return" "+Object.keys(e).filter(t=>e[t]).join(" ")+" "}update(e,[t]){if(this.st===void 0){this.st=new Set,e.strings!==void 0&&(this.nt=new Set(e.strings.join(" ").split(/\s/).filter(n=>n!=="")));for(const n in t)t[n]&&!this.nt?.has(n)&&this.st.add(n);return this.render(t)}const r=e.element.classList;for(const n of this.st)n in t||(r.remove(n),this.st.delete(n));for(const n in t){const o=!!t[n];o===this.st.has(n)||this.nt?.has(n)||(o?(r.add(n),this.st.add(n)):(r.remove(n),this.st.delete(n)))}return jt}});var is=class extends Mt{constructor(){super(...arguments),this.hasSlotController=new ns(this,"footer","header","image")}render(){return G` +
    + + + + +
    + `}};is.styles=[sr,Au];is.define("sl-card");var Cu=ct` + :host { + --track-width: 2px; + --track-color: rgb(128 128 128 / 25%); + --indicator-color: var(--sl-color-primary-600); + --speed: 2s; + + display: inline-flex; + width: 1em; + height: 1em; + flex: none; + } + + .spinner { + flex: 1 1 auto; + height: 100%; + width: 100%; + } + + .spinner__track, + .spinner__indicator { + fill: none; + stroke-width: var(--track-width); + r: calc(0.5em - var(--track-width) / 2); + cx: 0.5em; + cy: 0.5em; + transform-origin: 50% 50%; + } + + .spinner__track { + stroke: var(--track-color); + transform-origin: 0% 0%; + } + + .spinner__indicator { + stroke: var(--indicator-color); + stroke-linecap: round; + stroke-dasharray: 150% 75%; + animation: spin var(--speed) linear infinite; + } + + @keyframes spin { + 0% { + transform: rotate(0deg); + stroke-dasharray: 0.05em, 3em; + } + + 50% { + transform: rotate(450deg); + stroke-dasharray: 1.375em, 1.375em; + } + + 100% { + transform: rotate(1080deg); + stroke-dasharray: 0.05em, 3em; + } + } +`;const zr=new Set,Qt=new Map;let zt,$n="ltr",An="en";const ss=typeof MutationObserver<"u"&&typeof document<"u"&&typeof document.documentElement<"u";if(ss){const e=new MutationObserver(ls);$n=document.documentElement.dir||"ltr",An=document.documentElement.lang||navigator.language,e.observe(document.documentElement,{attributes:!0,attributeFilter:["dir","lang"]})}function as(...e){e.map(t=>{const r=t.$code.toLowerCase();Qt.has(r)?Qt.set(r,Object.assign(Object.assign({},Qt.get(r)),t)):Qt.set(r,t),zt||(zt=t)}),ls()}function ls(){ss&&($n=document.documentElement.dir||"ltr",An=document.documentElement.lang||navigator.language),[...zr.keys()].map(e=>{typeof e.requestUpdate=="function"&&e.requestUpdate()})}let Bu=class{constructor(t){this.host=t,this.host.addController(this)}hostConnected(){zr.add(this.host)}hostDisconnected(){zr.delete(this.host)}dir(){return`${this.host.dir||$n}`.toLowerCase()}lang(){return`${this.host.lang||An}`.toLowerCase()}getTranslationData(t){var r,n;const o=new Intl.Locale(t.replace(/_/g,"-")),i=o?.language.toLowerCase(),s=(n=(r=o?.region)===null||r===void 0?void 0:r.toLowerCase())!==null&&n!==void 0?n:"",l=Qt.get(`${i}-${s}`),a=Qt.get(i);return{locale:o,language:i,region:s,primary:l,secondary:a}}exists(t,r){var n;const{primary:o,secondary:i}=this.getTranslationData((n=r.lang)!==null&&n!==void 0?n:this.lang());return r=Object.assign({includeFallback:!1},r),!!(o&&o[t]||i&&i[t]||r.includeFallback&&zt&&zt[t])}term(t,...r){const{primary:n,secondary:o}=this.getTranslationData(this.lang());let i;if(n&&n[t])i=n[t];else if(o&&o[t])i=o[t];else if(zt&&zt[t])i=zt[t];else return console.error(`No translation found for: ${String(t)}`),String(t);return typeof i=="function"?i(...r):i}date(t,r){return t=new Date(t),new Intl.DateTimeFormat(this.lang(),r).format(t)}number(t,r){return t=Number(t),isNaN(t)?"":new Intl.NumberFormat(this.lang(),r).format(t)}relativeTime(t,r,n){return new Intl.RelativeTimeFormat(this.lang(),n).format(t,r)}};var cs={$code:"en",$name:"English",$dir:"ltr",carousel:"Carousel",clearEntry:"Clear entry",close:"Close",copied:"Copied",copy:"Copy",currentValue:"Current value",error:"Error",goToSlide:(e,t)=>`Go to slide ${e} of ${t}`,hidePassword:"Hide password",loading:"Loading",nextSlide:"Next slide",numOptionsSelected:e=>e===0?"No options selected":e===1?"1 option selected":`${e} options selected`,previousSlide:"Previous slide",progress:"Progress",remove:"Remove",resize:"Resize",scrollToEnd:"Scroll to end",scrollToStart:"Scroll to start",selectAColorFromTheScreen:"Select a color from the screen",showPassword:"Show password",slideNum:e=>`Slide ${e}`,toggleColorFormat:"Toggle color format"};as(cs);var Lu=cs,ds=class extends Bu{};as(Lu);var us=class extends Mt{constructor(){super(...arguments),this.localize=new ds(this)}render(){return G` + + + + + `}};us.styles=[sr,Cu];var fe=new WeakMap,pe=new WeakMap,ge=new WeakMap,vr=new WeakSet,Pe=new WeakMap,Uu=class{constructor(e,t){this.handleFormData=r=>{const n=this.options.disabled(this.host),o=this.options.name(this.host),i=this.options.value(this.host),s=this.host.tagName.toLowerCase()==="sl-button";this.host.isConnected&&!n&&!s&&typeof o=="string"&&o.length>0&&typeof i<"u"&&(Array.isArray(i)?i.forEach(l=>{r.formData.append(o,l.toString())}):r.formData.append(o,i.toString()))},this.handleFormSubmit=r=>{var n;const o=this.options.disabled(this.host),i=this.options.reportValidity;this.form&&!this.form.noValidate&&((n=fe.get(this.form))==null||n.forEach(s=>{this.setUserInteracted(s,!0)})),this.form&&!this.form.noValidate&&!o&&!i(this.host)&&(r.preventDefault(),r.stopImmediatePropagation())},this.handleFormReset=()=>{this.options.setValue(this.host,this.options.defaultValue(this.host)),this.setUserInteracted(this.host,!1),Pe.set(this.host,[])},this.handleInteraction=r=>{const n=Pe.get(this.host);n.includes(r.type)||n.push(r.type),n.length===this.options.assumeInteractionOn.length&&this.setUserInteracted(this.host,!0)},this.checkFormValidity=()=>{if(this.form&&!this.form.noValidate){const r=this.form.querySelectorAll("*");for(const n of r)if(typeof n.checkValidity=="function"&&!n.checkValidity())return!1}return!0},this.reportFormValidity=()=>{if(this.form&&!this.form.noValidate){const r=this.form.querySelectorAll("*");for(const n of r)if(typeof n.reportValidity=="function"&&!n.reportValidity())return!1}return!0},(this.host=e).addController(this),this.options=_e({form:r=>{const n=r.form;if(n){const i=r.getRootNode().querySelector(`#${n}`);if(i)return i}return r.closest("form")},name:r=>r.name,value:r=>r.value,defaultValue:r=>r.defaultValue,disabled:r=>{var n;return(n=r.disabled)!=null?n:!1},reportValidity:r=>typeof r.reportValidity=="function"?r.reportValidity():!0,checkValidity:r=>typeof r.checkValidity=="function"?r.checkValidity():!0,setValue:(r,n)=>r.value=n,assumeInteractionOn:["sl-input"]},t)}hostConnected(){const e=this.options.form(this.host);e&&this.attachForm(e),Pe.set(this.host,[]),this.options.assumeInteractionOn.forEach(t=>{this.host.addEventListener(t,this.handleInteraction)})}hostDisconnected(){this.detachForm(),Pe.delete(this.host),this.options.assumeInteractionOn.forEach(e=>{this.host.removeEventListener(e,this.handleInteraction)})}hostUpdated(){const e=this.options.form(this.host);e||this.detachForm(),e&&this.form!==e&&(this.detachForm(),this.attachForm(e)),this.host.hasUpdated&&this.setValidity(this.host.validity.valid)}attachForm(e){e?(this.form=e,fe.has(this.form)?fe.get(this.form).add(this.host):fe.set(this.form,new Set([this.host])),this.form.addEventListener("formdata",this.handleFormData),this.form.addEventListener("submit",this.handleFormSubmit),this.form.addEventListener("reset",this.handleFormReset),pe.has(this.form)||(pe.set(this.form,this.form.reportValidity),this.form.reportValidity=()=>this.reportFormValidity()),ge.has(this.form)||(ge.set(this.form,this.form.checkValidity),this.form.checkValidity=()=>this.checkFormValidity())):this.form=void 0}detachForm(){if(!this.form)return;const e=fe.get(this.form);e&&(e.delete(this.host),e.size<=0&&(this.form.removeEventListener("formdata",this.handleFormData),this.form.removeEventListener("submit",this.handleFormSubmit),this.form.removeEventListener("reset",this.handleFormReset),pe.has(this.form)&&(this.form.reportValidity=pe.get(this.form),pe.delete(this.form)),ge.has(this.form)&&(this.form.checkValidity=ge.get(this.form),ge.delete(this.form)),this.form=void 0))}setUserInteracted(e,t){t?vr.add(e):vr.delete(e),e.requestUpdate()}doAction(e,t){if(this.form){const r=document.createElement("button");r.type=e,r.style.position="absolute",r.style.width="0",r.style.height="0",r.style.clipPath="inset(50%)",r.style.overflow="hidden",r.style.whiteSpace="nowrap",t&&(r.name=t.name,r.value=t.value,["formaction","formenctype","formmethod","formnovalidate","formtarget"].forEach(n=>{t.hasAttribute(n)&&r.setAttribute(n,t.getAttribute(n))})),this.form.append(r),r.click(),r.remove()}}getForm(){var e;return(e=this.form)!=null?e:null}reset(e){this.doAction("reset",e)}submit(e){this.doAction("submit",e)}setValidity(e){const t=this.host,r=!!vr.has(t),n=!!t.required;t.toggleAttribute("data-required",n),t.toggleAttribute("data-optional",!n),t.toggleAttribute("data-invalid",!e),t.toggleAttribute("data-valid",e),t.toggleAttribute("data-user-invalid",!e&&r),t.toggleAttribute("data-user-valid",e&&r)}updateValidity(){const e=this.host;this.setValidity(e.validity.valid)}emitInvalidEvent(e){const t=new CustomEvent("sl-invalid",{bubbles:!1,composed:!1,cancelable:!0,detail:{}});e||t.preventDefault(),this.host.dispatchEvent(t)||e?.preventDefault()}},Sn=Object.freeze({badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:!0,valueMissing:!1});Object.freeze(bo(_e({},Sn),{valid:!1,valueMissing:!0}));Object.freeze(bo(_e({},Sn),{valid:!1,customError:!0}));var Tu=ct` + :host { + display: inline-block; + position: relative; + width: auto; + cursor: pointer; + } + + .button { + display: inline-flex; + align-items: stretch; + justify-content: center; + width: 100%; + border-style: solid; + border-width: var(--sl-input-border-width); + font-family: var(--sl-input-font-family); + font-weight: var(--sl-font-weight-semibold); + text-decoration: none; + user-select: none; + -webkit-user-select: none; + white-space: nowrap; + vertical-align: middle; + padding: 0; + transition: + var(--sl-transition-x-fast) background-color, + var(--sl-transition-x-fast) color, + var(--sl-transition-x-fast) border, + var(--sl-transition-x-fast) box-shadow; + cursor: inherit; + } + + .button::-moz-focus-inner { + border: 0; + } + + .button:focus { + outline: none; + } + + .button:focus-visible { + outline: var(--sl-focus-ring); + outline-offset: var(--sl-focus-ring-offset); + } + + .button--disabled { + opacity: 0.5; + cursor: not-allowed; + } + + /* When disabled, prevent mouse events from bubbling up from children */ + .button--disabled * { + pointer-events: none; + } + + .button__prefix, + .button__suffix { + flex: 0 0 auto; + display: flex; + align-items: center; + pointer-events: none; + } + + .button__label { + display: inline-block; + } + + .button__label::slotted(sl-icon) { + vertical-align: -2px; + } + + /* + * Standard buttons + */ + + /* Default */ + .button--standard.button--default { + background-color: var(--sl-color-neutral-0); + border-color: var(--sl-input-border-color); + color: var(--sl-color-neutral-700); + } + + .button--standard.button--default:hover:not(.button--disabled) { + background-color: var(--sl-color-primary-50); + border-color: var(--sl-color-primary-300); + color: var(--sl-color-primary-700); + } + + .button--standard.button--default:active:not(.button--disabled) { + background-color: var(--sl-color-primary-100); + border-color: var(--sl-color-primary-400); + color: var(--sl-color-primary-700); + } + + /* Primary */ + .button--standard.button--primary { + background-color: var(--sl-color-primary-600); + border-color: var(--sl-color-primary-600); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--primary:hover:not(.button--disabled) { + background-color: var(--sl-color-primary-500); + border-color: var(--sl-color-primary-500); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--primary:active:not(.button--disabled) { + background-color: var(--sl-color-primary-600); + border-color: var(--sl-color-primary-600); + color: var(--sl-color-neutral-0); + } + + /* Success */ + .button--standard.button--success { + background-color: var(--sl-color-success-600); + border-color: var(--sl-color-success-600); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--success:hover:not(.button--disabled) { + background-color: var(--sl-color-success-500); + border-color: var(--sl-color-success-500); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--success:active:not(.button--disabled) { + background-color: var(--sl-color-success-600); + border-color: var(--sl-color-success-600); + color: var(--sl-color-neutral-0); + } + + /* Neutral */ + .button--standard.button--neutral { + background-color: var(--sl-color-neutral-600); + border-color: var(--sl-color-neutral-600); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--neutral:hover:not(.button--disabled) { + background-color: var(--sl-color-neutral-500); + border-color: var(--sl-color-neutral-500); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--neutral:active:not(.button--disabled) { + background-color: var(--sl-color-neutral-600); + border-color: var(--sl-color-neutral-600); + color: var(--sl-color-neutral-0); + } + + /* Warning */ + .button--standard.button--warning { + background-color: var(--sl-color-warning-600); + border-color: var(--sl-color-warning-600); + color: var(--sl-color-neutral-0); + } + .button--standard.button--warning:hover:not(.button--disabled) { + background-color: var(--sl-color-warning-500); + border-color: var(--sl-color-warning-500); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--warning:active:not(.button--disabled) { + background-color: var(--sl-color-warning-600); + border-color: var(--sl-color-warning-600); + color: var(--sl-color-neutral-0); + } + + /* Danger */ + .button--standard.button--danger { + background-color: var(--sl-color-danger-600); + border-color: var(--sl-color-danger-600); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--danger:hover:not(.button--disabled) { + background-color: var(--sl-color-danger-500); + border-color: var(--sl-color-danger-500); + color: var(--sl-color-neutral-0); + } + + .button--standard.button--danger:active:not(.button--disabled) { + background-color: var(--sl-color-danger-600); + border-color: var(--sl-color-danger-600); + color: var(--sl-color-neutral-0); + } + + /* + * Outline buttons + */ + + .button--outline { + background: none; + border: solid 1px; + } + + /* Default */ + .button--outline.button--default { + border-color: var(--sl-input-border-color); + color: var(--sl-color-neutral-700); + } + + .button--outline.button--default:hover:not(.button--disabled), + .button--outline.button--default.button--checked:not(.button--disabled) { + border-color: var(--sl-color-primary-600); + background-color: var(--sl-color-primary-600); + color: var(--sl-color-neutral-0); + } + + .button--outline.button--default:active:not(.button--disabled) { + border-color: var(--sl-color-primary-700); + background-color: var(--sl-color-primary-700); + color: var(--sl-color-neutral-0); + } + + /* Primary */ + .button--outline.button--primary { + border-color: var(--sl-color-primary-600); + color: var(--sl-color-primary-600); + } + + .button--outline.button--primary:hover:not(.button--disabled), + .button--outline.button--primary.button--checked:not(.button--disabled) { + background-color: var(--sl-color-primary-600); + color: var(--sl-color-neutral-0); + } + + .button--outline.button--primary:active:not(.button--disabled) { + border-color: var(--sl-color-primary-700); + background-color: var(--sl-color-primary-700); + color: var(--sl-color-neutral-0); + } + + /* Success */ + .button--outline.button--success { + border-color: var(--sl-color-success-600); + color: var(--sl-color-success-600); + } + + .button--outline.button--success:hover:not(.button--disabled), + .button--outline.button--success.button--checked:not(.button--disabled) { + background-color: var(--sl-color-success-600); + color: var(--sl-color-neutral-0); + } + + .button--outline.button--success:active:not(.button--disabled) { + border-color: var(--sl-color-success-700); + background-color: var(--sl-color-success-700); + color: var(--sl-color-neutral-0); + } + + /* Neutral */ + .button--outline.button--neutral { + border-color: var(--sl-color-neutral-600); + color: var(--sl-color-neutral-600); + } + + .button--outline.button--neutral:hover:not(.button--disabled), + .button--outline.button--neutral.button--checked:not(.button--disabled) { + background-color: var(--sl-color-neutral-600); + color: var(--sl-color-neutral-0); + } + + .button--outline.button--neutral:active:not(.button--disabled) { + border-color: var(--sl-color-neutral-700); + background-color: var(--sl-color-neutral-700); + color: var(--sl-color-neutral-0); + } + + /* Warning */ + .button--outline.button--warning { + border-color: var(--sl-color-warning-600); + color: var(--sl-color-warning-600); + } + + .button--outline.button--warning:hover:not(.button--disabled), + .button--outline.button--warning.button--checked:not(.button--disabled) { + background-color: var(--sl-color-warning-600); + color: var(--sl-color-neutral-0); + } + + .button--outline.button--warning:active:not(.button--disabled) { + border-color: var(--sl-color-warning-700); + background-color: var(--sl-color-warning-700); + color: var(--sl-color-neutral-0); + } + + /* Danger */ + .button--outline.button--danger { + border-color: var(--sl-color-danger-600); + color: var(--sl-color-danger-600); + } + + .button--outline.button--danger:hover:not(.button--disabled), + .button--outline.button--danger.button--checked:not(.button--disabled) { + background-color: var(--sl-color-danger-600); + color: var(--sl-color-neutral-0); + } + + .button--outline.button--danger:active:not(.button--disabled) { + border-color: var(--sl-color-danger-700); + background-color: var(--sl-color-danger-700); + color: var(--sl-color-neutral-0); + } + + @media (forced-colors: active) { + .button.button--outline.button--checked:not(.button--disabled) { + outline: solid 2px transparent; + } + } + + /* + * Text buttons + */ + + .button--text { + background-color: transparent; + border-color: transparent; + color: var(--sl-color-primary-600); + } + + .button--text:hover:not(.button--disabled) { + background-color: transparent; + border-color: transparent; + color: var(--sl-color-primary-500); + } + + .button--text:focus-visible:not(.button--disabled) { + background-color: transparent; + border-color: transparent; + color: var(--sl-color-primary-500); + } + + .button--text:active:not(.button--disabled) { + background-color: transparent; + border-color: transparent; + color: var(--sl-color-primary-700); + } + + /* + * Size modifiers + */ + + .button--small { + height: auto; + min-height: var(--sl-input-height-small); + font-size: var(--sl-button-font-size-small); + line-height: calc(var(--sl-input-height-small) - var(--sl-input-border-width) * 2); + border-radius: var(--sl-input-border-radius-small); + } + + .button--medium { + height: auto; + min-height: var(--sl-input-height-medium); + font-size: var(--sl-button-font-size-medium); + line-height: calc(var(--sl-input-height-medium) - var(--sl-input-border-width) * 2); + border-radius: var(--sl-input-border-radius-medium); + } + + .button--large { + height: auto; + min-height: var(--sl-input-height-large); + font-size: var(--sl-button-font-size-large); + line-height: calc(var(--sl-input-height-large) - var(--sl-input-border-width) * 2); + border-radius: var(--sl-input-border-radius-large); + } + + /* + * Pill modifier + */ + + .button--pill.button--small { + border-radius: var(--sl-input-height-small); + } + + .button--pill.button--medium { + border-radius: var(--sl-input-height-medium); + } + + .button--pill.button--large { + border-radius: var(--sl-input-height-large); + } + + /* + * Circle modifier + */ + + .button--circle { + padding-left: 0; + padding-right: 0; + } + + .button--circle.button--small { + width: var(--sl-input-height-small); + border-radius: 50%; + } + + .button--circle.button--medium { + width: var(--sl-input-height-medium); + border-radius: 50%; + } + + .button--circle.button--large { + width: var(--sl-input-height-large); + border-radius: 50%; + } + + .button--circle .button__prefix, + .button--circle .button__suffix, + .button--circle .button__caret { + display: none; + } + + /* + * Caret modifier + */ + + .button--caret .button__suffix { + display: none; + } + + .button--caret .button__caret { + height: auto; + } + + /* + * Loading modifier + */ + + .button--loading { + position: relative; + cursor: wait; + } + + .button--loading .button__prefix, + .button--loading .button__label, + .button--loading .button__suffix, + .button--loading .button__caret { + visibility: hidden; + } + + .button--loading sl-spinner { + --indicator-color: currentColor; + position: absolute; + font-size: 1em; + height: 1em; + width: 1em; + top: calc(50% - 0.5em); + left: calc(50% - 0.5em); + } + + /* + * Badges + */ + + .button ::slotted(sl-badge) { + position: absolute; + top: 0; + right: 0; + translate: 50% -50%; + pointer-events: none; + } + + .button--rtl ::slotted(sl-badge) { + right: auto; + left: 0; + translate: -50% -50%; + } + + /* + * Button spacing + */ + + .button--has-label.button--small .button__label { + padding: 0 var(--sl-spacing-small); + } + + .button--has-label.button--medium .button__label { + padding: 0 var(--sl-spacing-medium); + } + + .button--has-label.button--large .button__label { + padding: 0 var(--sl-spacing-large); + } + + .button--has-prefix.button--small { + padding-inline-start: var(--sl-spacing-x-small); + } + + .button--has-prefix.button--small .button__label { + padding-inline-start: var(--sl-spacing-x-small); + } + + .button--has-prefix.button--medium { + padding-inline-start: var(--sl-spacing-small); + } + + .button--has-prefix.button--medium .button__label { + padding-inline-start: var(--sl-spacing-small); + } + + .button--has-prefix.button--large { + padding-inline-start: var(--sl-spacing-small); + } + + .button--has-prefix.button--large .button__label { + padding-inline-start: var(--sl-spacing-small); + } + + .button--has-suffix.button--small, + .button--caret.button--small { + padding-inline-end: var(--sl-spacing-x-small); + } + + .button--has-suffix.button--small .button__label, + .button--caret.button--small .button__label { + padding-inline-end: var(--sl-spacing-x-small); + } + + .button--has-suffix.button--medium, + .button--caret.button--medium { + padding-inline-end: var(--sl-spacing-small); + } + + .button--has-suffix.button--medium .button__label, + .button--caret.button--medium .button__label { + padding-inline-end: var(--sl-spacing-small); + } + + .button--has-suffix.button--large, + .button--caret.button--large { + padding-inline-end: var(--sl-spacing-small); + } + + .button--has-suffix.button--large .button__label, + .button--caret.button--large .button__label { + padding-inline-end: var(--sl-spacing-small); + } + + /* + * Button groups support a variety of button types (e.g. buttons with tooltips, buttons as dropdown triggers, etc.). + * This means buttons aren't always direct descendants of the button group, thus we can't target them with the + * ::slotted selector. To work around this, the button group component does some magic to add these special classes to + * buttons and we style them here instead. + */ + + :host([data-sl-button-group__button--first]:not([data-sl-button-group__button--last])) .button { + border-start-end-radius: 0; + border-end-end-radius: 0; + } + + :host([data-sl-button-group__button--inner]) .button { + border-radius: 0; + } + + :host([data-sl-button-group__button--last]:not([data-sl-button-group__button--first])) .button { + border-start-start-radius: 0; + border-end-start-radius: 0; + } + + /* All except the first */ + :host([data-sl-button-group__button]:not([data-sl-button-group__button--first])) { + margin-inline-start: calc(-1 * var(--sl-input-border-width)); + } + + /* Add a visual separator between solid buttons */ + :host( + [data-sl-button-group__button]:not( + [data-sl-button-group__button--first], + [data-sl-button-group__button--radio], + [variant='default'] + ):not(:hover) + ) + .button:after { + content: ''; + position: absolute; + top: 0; + inset-inline-start: 0; + bottom: 0; + border-left: solid 1px rgb(128 128 128 / 33%); + mix-blend-mode: multiply; + } + + /* Bump hovered, focused, and checked buttons up so their focus ring isn't clipped */ + :host([data-sl-button-group__button--hover]) { + z-index: 1; + } + + /* Focus and checked are always on top */ + :host([data-sl-button-group__button--focus]), + :host([data-sl-button-group__button][checked]) { + z-index: 2; + } +`,Iu={name:"default",resolver:e=>ps(`assets/icons/${e}.svg`)},Mu=Iu,lo={caret:` + + + + `,check:` + + + + + + + + + + + `,"chevron-down":` + + + + `,"chevron-left":` + + + + `,"chevron-right":` + + + + `,copy:` + + + + `,eye:` + + + + + `,"eye-slash":` + + + + + + `,eyedropper:` + + + + `,"grip-vertical":` + + + + `,indeterminate:` + + + + + + + + + + `,"person-fill":` + + + + `,"play-fill":` + + + + `,"pause-fill":` + + + + `,radio:` + + + + + + + + `,"star-fill":` + + + + `,"x-lg":` + + + + `,"x-circle-fill":` + + + + `},Ru={name:"system",resolver:e=>e in lo?`data:image/svg+xml,${encodeURIComponent(lo[e])}`:""},Nu=Ru,Ou=[Mu,Nu],Vr=[];function Hu(e){Vr.push(e)}function zu(e){Vr=Vr.filter(t=>t!==e)}function co(e){return Ou.find(t=>t.name===e)}var Vu=ct` + :host { + display: inline-block; + width: 1em; + height: 1em; + box-sizing: content-box !important; + } + + svg { + display: block; + height: 100%; + width: 100%; + } +`;function kn(e,t){const r=_e({waitUntilFirstUpdate:!1},t);return(n,o)=>{const{update:i}=n,s=Array.isArray(e)?e:[e];n.update=function(l){s.forEach(a=>{const c=a;if(l.has(c)){const u=l.get(c),d=this[c];u!==d&&(!r.waitUntilFirstUpdate||this.hasUpdated)&&this[o](u,d)}}),i.call(this,l)}}}/** + * @license + * Copyright 2020 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const Du=(e,t)=>e?._$litType$!==void 0;var be=Symbol(),Ce=Symbol(),xr,Er=new Map,xt=class extends Mt{constructor(){super(...arguments),this.initialRender=!1,this.svg=null,this.label="",this.library="default"}async resolveIcon(e,t){var r;let n;if(t?.spriteSheet)return this.svg=G` + + `,this.svg;try{if(n=await fetch(e,{mode:"cors"}),!n.ok)return n.status===410?be:Ce}catch{return Ce}try{const o=document.createElement("div");o.innerHTML=await n.text();const i=o.firstElementChild;if(((r=i?.tagName)==null?void 0:r.toLowerCase())!=="svg")return be;xr||(xr=new DOMParser);const l=xr.parseFromString(i.outerHTML,"text/html").body.querySelector("svg");return l?(l.part.add("svg"),document.adoptNode(l)):be}catch{return be}}connectedCallback(){super.connectedCallback(),Hu(this)}firstUpdated(){this.initialRender=!0,this.setIcon()}disconnectedCallback(){super.disconnectedCallback(),zu(this)}getIconSource(){const e=co(this.library);return this.name&&e?{url:e.resolver(this.name),fromLibrary:!0}:{url:this.src,fromLibrary:!1}}handleLabelChange(){typeof this.label=="string"&&this.label.length>0?(this.setAttribute("role","img"),this.setAttribute("aria-label",this.label),this.removeAttribute("aria-hidden")):(this.removeAttribute("role"),this.removeAttribute("aria-label"),this.setAttribute("aria-hidden","true"))}async setIcon(){var e;const{url:t,fromLibrary:r}=this.getIconSource(),n=r?co(this.library):void 0;if(!t){this.svg=null;return}let o=Er.get(t);if(o||(o=this.resolveIcon(t,n),Er.set(t,o)),!this.initialRender)return;const i=await o;if(i===Ce&&Er.delete(t),t===this.getIconSource().url){if(Du(i)){if(this.svg=i,n){await this.updateComplete;const s=this.shadowRoot.querySelector("[part='svg']");typeof n.mutator=="function"&&s&&n.mutator(s)}return}switch(i){case Ce:case be:this.svg=null,this.emit("sl-error");break;default:this.svg=i.cloneNode(!0),(e=n?.mutator)==null||e.call(n,this.svg),this.emit("sl-load")}}}render(){return this.svg}};xt.styles=[sr,Vu];T([Zr()],xt.prototype,"svg",2);T([S({reflect:!0})],xt.prototype,"name",2);T([S()],xt.prototype,"src",2);T([S()],xt.prototype,"label",2);T([S({reflect:!0})],xt.prototype,"library",2);T([kn("label")],xt.prototype,"handleLabelChange",1);T([kn(["name","src","library"])],xt.prototype,"setIcon",1);/** + * @license + * Copyright 2020 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */const hs=Symbol.for(""),qu=e=>{if(e?.r===hs)return e?._$litStatic$},uo=(e,...t)=>({_$litStatic$:t.reduce((r,n,o)=>r+(i=>{if(i._$litStatic$!==void 0)return i._$litStatic$;throw Error(`Value passed to 'literal' function must be a 'literal' result: ${i}. Use 'unsafeStatic' to pass non-literal values, but + take care to ensure page security.`)})(n)+e[o+1],e[0]),r:hs}),ho=new Map,ju=e=>(t,...r)=>{const n=r.length;let o,i;const s=[],l=[];let a,c=0,u=!1;for(;ce??F;var N=class extends Mt{constructor(){super(...arguments),this.formControlController=new Uu(this,{assumeInteractionOn:["click"]}),this.hasSlotController=new ns(this,"[default]","prefix","suffix"),this.localize=new ds(this),this.hasFocus=!1,this.invalid=!1,this.title="",this.variant="default",this.size="medium",this.caret=!1,this.disabled=!1,this.loading=!1,this.outline=!1,this.pill=!1,this.circle=!1,this.type="button",this.name="",this.value="",this.href="",this.rel="noreferrer noopener"}get validity(){return this.isButton()?this.button.validity:Sn}get validationMessage(){return this.isButton()?this.button.validationMessage:""}firstUpdated(){this.isButton()&&this.formControlController.updateValidity()}handleBlur(){this.hasFocus=!1,this.emit("sl-blur")}handleFocus(){this.hasFocus=!0,this.emit("sl-focus")}handleClick(){this.type==="submit"&&this.formControlController.submit(this),this.type==="reset"&&this.formControlController.reset(this)}handleInvalid(e){this.formControlController.setValidity(!1),this.formControlController.emitInvalidEvent(e)}isButton(){return!this.href}isLink(){return!!this.href}handleDisabledChange(){this.isButton()&&this.formControlController.setValidity(this.disabled)}click(){this.button.click()}focus(e){this.button.focus(e)}blur(){this.button.blur()}checkValidity(){return this.isButton()?this.button.checkValidity():!0}getForm(){return this.formControlController.getForm()}reportValidity(){return this.isButton()?this.button.reportValidity():!0}setCustomValidity(e){this.isButton()&&(this.button.setCustomValidity(e),this.formControlController.updateValidity())}render(){const e=this.isLink(),t=e?uo`a`:uo`button`;return _r` + <${t} + part="base" + class=${os({button:!0,"button--default":this.variant==="default","button--primary":this.variant==="primary","button--success":this.variant==="success","button--neutral":this.variant==="neutral","button--warning":this.variant==="warning","button--danger":this.variant==="danger","button--text":this.variant==="text","button--small":this.size==="small","button--medium":this.size==="medium","button--large":this.size==="large","button--caret":this.caret,"button--circle":this.circle,"button--disabled":this.disabled,"button--focused":this.hasFocus,"button--loading":this.loading,"button--standard":!this.outline,"button--outline":this.outline,"button--pill":this.pill,"button--rtl":this.localize.dir()==="rtl","button--has-label":this.hasSlotController.test("[default]"),"button--has-prefix":this.hasSlotController.test("prefix"),"button--has-suffix":this.hasSlotController.test("suffix")})} + ?disabled=${ut(e?void 0:this.disabled)} + type=${ut(e?void 0:this.type)} + title=${this.title} + name=${ut(e?void 0:this.name)} + value=${ut(e?void 0:this.value)} + href=${ut(e&&!this.disabled?this.href:void 0)} + target=${ut(e?this.target:void 0)} + download=${ut(e?this.download:void 0)} + rel=${ut(e?this.rel:void 0)} + role=${ut(e?void 0:"button")} + aria-disabled=${this.disabled?"true":"false"} + tabindex=${this.disabled?"-1":"0"} + @blur=${this.handleBlur} + @focus=${this.handleFocus} + @invalid=${this.isButton()?this.handleInvalid:null} + @click=${this.handleClick} + > + + + + ${this.caret?_r` `:""} + ${this.loading?_r``:""} + + `}};N.styles=[sr,Tu];N.dependencies={"sl-icon":xt,"sl-spinner":us};T([Zs(".button")],N.prototype,"button",2);T([Zr()],N.prototype,"hasFocus",2);T([Zr()],N.prototype,"invalid",2);T([S()],N.prototype,"title",2);T([S({reflect:!0})],N.prototype,"variant",2);T([S({reflect:!0})],N.prototype,"size",2);T([S({type:Boolean,reflect:!0})],N.prototype,"caret",2);T([S({type:Boolean,reflect:!0})],N.prototype,"disabled",2);T([S({type:Boolean,reflect:!0})],N.prototype,"loading",2);T([S({type:Boolean,reflect:!0})],N.prototype,"outline",2);T([S({type:Boolean,reflect:!0})],N.prototype,"pill",2);T([S({type:Boolean,reflect:!0})],N.prototype,"circle",2);T([S()],N.prototype,"type",2);T([S()],N.prototype,"name",2);T([S()],N.prototype,"value",2);T([S()],N.prototype,"href",2);T([S()],N.prototype,"target",2);T([S()],N.prototype,"rel",2);T([S()],N.prototype,"download",2);T([S()],N.prototype,"form",2);T([S({attribute:"formaction"})],N.prototype,"formAction",2);T([S({attribute:"formenctype"})],N.prototype,"formEnctype",2);T([S({attribute:"formmethod"})],N.prototype,"formMethod",2);T([S({attribute:"formnovalidate",type:Boolean})],N.prototype,"formNoValidate",2);T([S({attribute:"formtarget"})],N.prototype,"formTarget",2);T([kn("disabled",{waitUntilFirstUpdate:!0})],N.prototype,"handleDisabledChange",1);N.define("sl-button");const fs=ct` + @media(min-width: 1000px) { + sl-card { + max-width: 70vw; + } + } + + main { + margin-top: 70px; + padding: 12px; + } + +.ProseMirror { + position: relative; + word-wrap: break-word; + white-space: pre-wrap; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + padding: 1rem; + line-height: 1.2; + outline: none; + font-family: var( + --markdown-editor-typography-font-family, + var(--mdc-typography-font-family, Montserrat, sans-serif) + ); + font-size: var( + --markdown-editor-typography-font-size, + var(--mdc-typography-subtitle1-font-size, 1rem) + ); + font-weight: var( + --markdown-editor-typography-font-weight, + var(--mdc-typography-subtitle1-font-weight, 400) + ); + letter-spacing: var( + --markdown-editor-typography-letter-spacing, + var(--mdc-typography-subtitle1-letter-spacing, 0.009375em) + ); + } + + .ProseMirror pre { + white-space: pre-wrap; + } + + .ProseMirror li { + position: relative; + } + + .ProseMirror p:first-child, + .ProseMirror h1:first-child, + .ProseMirror h2:first-child, + .ProseMirror h3:first-child, + .ProseMirror h4:first-child, + .ProseMirror h5:first-child, + .ProseMirror h6:first-child { + margin-top: 10px; + } + + .ProseMirror a { + color: var(--markdown-editor-typography-anchor-color, -webkit-link); + text-decoration: var(--markdown-editor-typography-anchor-text-decoration); + } + + .ProseMirror p { + margin-bottom: 1em; + } + + .ProseMirror-hideselection { + caret-color: transparent; + } + + .ProseMirror-hideselection *::selection, + .ProseMirror-hideselection *::-moz-selection { + background: transparent; + } + + .ProseMirror-selectednode { + outline: 2px solid #8cf; + } + + /* Make sure li selections wrap around markers */ + li.ProseMirror-selectednode { + outline: none; + } + + li.ProseMirror-selectednode:after { + content: ''; + position: absolute; + left: -32px; + right: -2px; + top: -2px; + bottom: -2px; + border: 2px solid #8cf; + pointer-events: none; + } + + .ProseMirror-textblock-dropdown { + min-width: 3em; + } + + .ProseMirror-menu { + margin: 0 -4px; + line-height: 1; + } + + .ProseMirror-tooltip .ProseMirror-menu { + width: -webkit-fit-content; + width: fit-content; + white-space: pre; + } + + .ProseMirror-menuitem { + margin: 0.25rem 0.25rem 0.25rem 0; + display: flex; + justify-content: center; + align-items: center; + border-radius: 4px; + overflow: hidden; + } + .ProseMirror-menuitem:hover { + background-color: #f5f5f5; + } + + .ProseMirror-menuseparator { + margin: 0 8px; + } + + .ProseMirror-menu-dropdown, + .ProseMirror-menu-dropdown-menu { + font-size: 90%; + white-space: nowrap; + } + + .ProseMirror-menu-dropdown { + vertical-align: 1px; + cursor: pointer; + position: relative; + padding-right: 15px; + } + + .ProseMirror-menu-dropdown-wrap { + padding: 1px 0 1px 4px; + display: inline-block; + position: relative; + } + + .ProseMirror-menu-dropdown:after { + content: ''; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 4px solid currentColor; + opacity: 0.6; + position: absolute; + right: 4px; + top: calc(50% - 2px); + } + + .ProseMirror-menu-dropdown-menu, + .ProseMirror-menu-submenu { + position: absolute; + background: white; + color: #666; + border: 1px solid #aaa; + padding: 2px; + } + + .ProseMirror-menu-dropdown-menu { + z-index: 1; + min-width: 6em; + } + + .ProseMirror-menu-dropdown-item { + cursor: pointer; + } + + .ProseMirror-menu-dropdown-item:hover { + background: #f2f2f2; + } + + .ProseMirror-menu-dropdown-item > div { + padding: 0.375rem 0.5rem; + } + + .ProseMirror-menu-submenu-wrap { + position: relative; + margin-right: -4px; + } + + .ProseMirror-menu-submenu-label:after { + content: ''; + border-top: 4px solid transparent; + border-bottom: 4px solid transparent; + border-left: 4px solid currentColor; + opacity: 0.6; + position: absolute; + right: 4px; + top: calc(50% - 4px); + } + + .ProseMirror-menu-submenu { + display: none; + min-width: 4em; + left: 100%; + top: -3px; + } + + .ProseMirror-menu-active { + background: #eee; + border-radius: 4px; + color: black; + } + + .ProseMirror-menu-submenu-wrap:hover .ProseMirror-menu-submenu, + .ProseMirror-menu-submenu-wrap-active .ProseMirror-menu-submenu { + display: block; + } + + .ProseMirror-menubar { + display: flex; + flex-wrap: wrap; + position: relative; + background: white; + min-height: 1em; + overflow: visible; + z-index: 2; + top: 0; + left: 0; + right: 0; + color: #666; + padding: 1px 6px; + border-top-left-radius: inherit; + border-top-right-radius: inherit; + border-bottom: 1px solid + var(--markdown-editor-outline-idle-border-color, rgba(0, 0, 0, 0.38)); + box-sizing: border-box; + -moz-box-sizing: border-box; + } + + .ProseMirror-icon { + display: inline-block; + line-height: 0.8; + vertical-align: -2px; + /* Compensate for padding */ + padding: 2px 8px; + cursor: pointer; + } + + .ProseMirror-menu-disabled { + color: rgba(0,0,0,0.37); + background-color: rgba(0,0,0,0.12); + cursor: not-allowed; + } + + .ProseMirror-menu-disabled.ProseMirror-icon { + cursor: not-allowed; + } + + .ProseMirror-icon svg { + fill: currentColor; + height: 1em; + } + + .ProseMirror-icon span { + vertical-align: text-top; + } + + .ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; + } + + .ProseMirror-gapcursor:after { + content: ''; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; + } + + @keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } + } + + .ProseMirror-focused .ProseMirror-gapcursor { + display: block; + } + + /* Add space around the hr to make clicking it easier */ + .ProseMirror-example-setup-style hr { + padding: 2px 10px; + border: none; + margin: 1em 0; + } + + .ProseMirror-example-setup-style hr:after { + content: ''; + display: block; + height: 1px; + background-color: silver; + line-height: 2px; + } + + .ProseMirror ul, + .ProseMirror ol { + padding-left: 30px; + } + + .ProseMirror blockquote { + padding-left: 1em; + border-left: 3px solid #eee; + margin-left: 0; + margin-right: 0; + } + + .ProseMirror-example-setup-style img { + cursor: default; + } + + .ProseMirror-invalid { + background: #ffc; + border: 1px solid #cc7; + border-radius: 4px; + padding: 5px 10px; + position: absolute; + min-width: 10em; + } + + .ProseMirror h1.title.empty-node::before, + .ProseMirror h2.instructional-prompt.empty-node::before, + .ProseMirror h3.mechanical-promp.empty-node::before { + content: 'Enter title here...'; + } + + .ProseMirror div.passage-subtitle.empty-node:first-child::before { + content: 'Enter subtitle here...'; + } + + .ProseMirror div.passage-author.empty-node:first-child::before, + .ProseMirror div.passage-cast-title.empty-node:first-child::before, + .ProseMirror div.passage-act-title.empty-node:first-child::before, + .ProseMirror div.passage-scene-title.empty-node:first-child::before, + .ProseMirror div.passage-verse.empty-node:first-child::before, + .ProseMirror div.passage-footnotes.empty-node:first-child::before, + .ProseMirror div.paragraph.empty-node:first-child::before { + content: 'Enter text here...'; + } + + div[contenteditable]:focus h1.title.empty-node::before, + div[contenteditable]:focus h2.instructional-prompt.empty-node::before, + div[contenteditable]:focus h3.mechanical-promp.empty-node::before, + div[contenteditable]:focus + div.passage-subtitle.empty-node:first-child::before, + div[contenteditable]:focus div.passage-author.empty-node:first-child::before, + div[contenteditable]:focus + div.passage-cast-title.empty-node:first-child::before, + div[contenteditable]:focus + div.passage-act-title.empty-node:first-child::before, + div[contenteditable]:focus + div.passage-scene-title.empty-node:first-child::before, + div[contenteditable]:focus div.passage-verse.empty-node:first-child::before, + div[contenteditable]:focus + div.passage-footnotes.empty-node:first-child::before, + div[contenteditable]:focus div.paragraph.empty-node:first-child::before { + content: ''; + } + + .ProseMirror .empty-node::before { + position: absolute; + color: #aaa; + cursor: text; + font-style: italic; + } + + #editor, .editor { + background: white; + color: black; + background-clip: padding-box; + padding: 5px 0; + } + + #editor[disabled] .ProseMirror-menubar { + display: none!important; + } + + drop-down-editor rich-text .inline-component-button, + expand-collapse rich-text .inline-component-button, + flip-reveal rich-text .inline-component-button, + hint-list rich-text .inline-component-button, + option-list rich-text .inline-component-button, + plankton-passage rich-text .inline-component-button { + pointer-events: none; + color: lightgray; + } + + #ProseMirror-icon-collection path { + fill-rule: evenodd; + } + #welcomeBar { + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; + } + + #welcomeCard, + #infoCard { + padding: 18px; + padding-top: 0px; + } + + sl-card::part(footer) { + display: flex; + justify-content: flex-end; + } + + @media(min-width: 750px) { + sl-card { + width: 70vw; + } + } + + @media (horizontal-viewport-segments: 2) { + #welcomeBar { + flex-direction: row; + align-items: flex-start; + justify-content: space-between; + } + + + + + @media (horizontal-viewport-segments: 2) { + #welcomeBar { + flex-direction: row; + align-items: flex-start; + justify-content: space-between; + } + + + } + .boring { + background: grey; + } + + .plus { + position: absolute; + + padding: 8px; + background-color: #4CAF50; + color: red; + border: none; + cursor: pointer; +} + +.plus:hover { + background-color: #45a049; +} + +.ProseMirror-textblock-dropdown { + min-width: 3em; +} +}`;var Fu=Object.defineProperty,Wu=Object.getOwnPropertyDescriptor,Pn=(e,t,r,n)=>{for(var o=n>1?void 0:n?Wu(t,r):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(o=(n?s(t,r,o):s(o))||o);return n&&o&&Fu(t,r,o),o};let ie=class extends gt{constructor(){super(...arguments),this.notes=[],this.relayName="",this.note=""}getUserLang(){return navigator.language||"en"}async firstUpdated(){console.log("Here are some recent notes from the neighborhood")}async connectedCallback(){super.connectedCallback(),await Promise.all([this.fetchNotes()])}async fetchNotes(){const e=await tr.connect("wss://notes.miguelalmodo.com");console.log(`connected to ${e.url}`),this.relayName=e.url;const t=e.subscribe([{kinds:[30023],limit:5}],{onevent:async r=>{console.log("Event received:",r),this.notes=[...this.notes,{content:r.content,date:new Date(r.created_at*1e3).toLocaleDateString()}],this.requestUpdate(),console.log(e)},oneose:()=>{t.close(),this.requestUpdate()}})}async displayLongNotes(){}share(){navigator.share&&navigator.share({title:"Nostr Micro Client",text:"Share this with your homie!",url:"https://miguelalmodo.com/"})}render(){return G` + +
    + +
    + +
    +

    Recent Notes from ${this.relayName}

    +
    + + + + + + ${this.notes.map(e=>{const t=e.content.match(/https?:\/\/[^\s]+/),r=e.content.replace(t?.[0]||"","").trim(),n=/(?:https?:\/\/(?:www\.)?youtube\.com\/watch\?v=|https?:\/\/youtu\.be\/)([a-zA-Z0-9_-]{11})/,o=t?.[0].match(n),i=o?o[1]:null,s=i?`https://img.youtube.com/vi/${i}/maxresdefault.jpg`:null,l=/(https?:\/\/[^\s]+\.(?:jpg|jpeg|png|gif))/i,a=t?.find(c=>l.test(c));return G` + + + + + `})} +

    ${e.date}

    +

    ${r}

    + ${s?G`YouTube thumbnail`:a?G`Note image`:""} +
    + + + +
    + + `}};ie.styles=[fs,ct` + +.comment-wall .main-section-header { + margin-bottom: 3px; +} + +.comment-wall .main-section-h2 { + margin-bottom: 0; +} + +#comment-counter { + margin-top: 0; + margin-left: 15px; + margin-bottom: 3px; +} + +.comment-wall table { + margin: auto; + margin-bottom: 5px; + color: black; +} + + +.comment-wall th { + width: 158px; + padding: 3px; + vertical-align: top; +} + +.comment-wall td { + vertical-align: top; + width: 269px; + padding: 3px; +} + +.comment-wall figcaption, +.comment-wall figure { + margin: 0; +} + +.comment-wall figcaption { + margin-bottom: 1em; +} + +.comment-wall figure { + margin-bottom: 49.33px; +} + +.comment-wall h3 { + font-size: 10pt; + margin: 0; + margin-bottom: 3em; +} + +.comment-wall p { + font-weight: normal; + text-align: center; + margin: 0; +} + +#add-comment { + text-align: right; + margin-right: 10px; + margin-bottom: 5px; +} + + + `];Pn([S({type:Array})],ie.prototype,"notes",2);Pn([S({type:String})],ie.prototype,"relayName",2);ie=Pn([qe("note-wall")],ie);const Ku=Object.freeze(Object.defineProperty({__proto__:null,get NoteWall(){return ie}},Symbol.toStringTag,{value:"Module"})),Zu="modulepreload",Gu=function(e){return"/"+e},fo={},Te=function(t,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),l=s?.nonce||s?.getAttribute("nonce");o=Promise.allSettled(r.map(a=>{if(a=Gu(a),a in fo)return;fo[a]=!0;const c=a.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${a}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":Zu,c||(d.as="script"),d.crossOrigin="",d.href=a,l&&d.setAttribute("nonce",l),document.head.appendChild(d),c)return new Promise((m,g)=>{d.addEventListener("load",m),d.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${a}`)))})}))}function i(s){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=s,window.dispatchEvent(l),!l.defaultPrevented)throw s}return o.then(s=>{for(const l of s||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})},Cn=Symbol.for("app-tools::log::1.x");globalThis[Cn]={setDebug:Ju,debug:"window"in globalThis?new URL(window.location.href).searchParams.has("app-tools-debug"):!1};function Ju(e){globalThis[Cn].debug=!!e}function Yu(e,t){globalThis[Cn].debug&&(console.groupCollapsed(`[app-tools] ${e}`),t&&console.log(t),console.groupEnd())}function Xu(e){return(t,r)=>{Yu(`${e}: ${t}`,r)}}const Pt=Xu("router");class Qu extends Event{constructor(t){super("route-changed"),this.context=t}}class th extends EventTarget{context={params:{},query:{},title:"",url:new URL(window.location.href)};constructor(t){super(),this.config=t,this.routes=t.routes.map(r=>({...r,urlPattern:new URLPattern({pathname:r.path,baseURL:window.location.href,search:"*",hash:"*"})})),Pt("Initialized routes",this.routes),queueMicrotask(()=>{this.navigate(new URL(window.location.href),{replace:!0})}),window.addEventListener("popstate",this._onPopState),window.addEventListener("click",this._onAnchorClick)}uninstall(){window.removeEventListener("popstate",this._onPopState),window.removeEventListener("click",this._onAnchorClick)}get url(){return new URL(window.location.href)}get fallback(){return new URL(this.config?.fallback||this.baseUrl.href.substring(window.location.origin.length),this.baseUrl)}get baseUrl(){return new URL("./",document.baseURI)}render(){return Pt(`Rendering route ${this.context.url.pathname}${this.context.url.search}${this.context.url.hash}`,{context:this.context,route:this.route}),this.route?.render?.(this.context)}_matchRoute(t){for(const r of this.routes){const n=r.urlPattern.exec(t);if(n){const{title:o}=r,i=Object.fromEntries(new URLSearchParams(t.search)),s=n?.pathname?.groups??{};return this.context={url:t,title:typeof o=="function"?o({params:s,query:i,url:t}):o,params:s,query:i},r}}return Pt(`No route matched for ${t.pathname}${t.search}${t.hash}`,t),null}_notifyUrlChanged(){this.dispatchEvent(new Qu(this.context))}_onPopState=()=>{this.navigate(new URL(window.location.href),{backNav:!0})};_onAnchorClick=t=>{if(t.defaultPrevented||t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey)return;const r=t.composedPath().find(i=>i.tagName==="A");if(!r||!r.href)return;const n=new URL(r.href);if(this.url.href===n.href||n.host!==window.location.host||r.hasAttribute("download")||r.href.includes("mailto:"))return;const o=r.getAttribute("target");o&&o!==""&&o!=="_self"||(t.preventDefault(),this.navigate(n))};_collectPlugins(t){return[...this.config?.plugins??[],...t?.plugins??[]]}async navigate(t,r={}){typeof t=="string"&&(t=new URL(t,this.baseUrl));let n=this._matchRoute(t)||this._matchRoute(this.fallback);Pt(`Navigating to ${t.pathname}${t.search}${t.hash}`,{context:this.context,route:this.route});let o=this._collectPlugins(n);for(const i of o)try{const s=await i?.shouldNavigate?.(this.context);s&&(await s.condition()||(t=new URL(s.redirect,this.baseUrl),n=this._matchRoute(t)||this._matchRoute(this.fallback),o=this._collectPlugins(n),Pt("Redirecting",{context:this.context,route:this.route})))}catch(s){throw Pt(`Plugin "${i.name}" error on shouldNavigate hook`,s),s}if(this.route=n,!this.route)throw new Error(`[ROUTER] No route or fallback matched for url ${t}`);for(const i of o)try{await i?.beforeNavigation?.(this.context)}catch(s){throw Pt(`Plugin "${i.name}" error on beforeNavigation hook`,s),s}r?.replace?window.history.replaceState(null,"",`${t.pathname}${t.search}${t.hash}`):r.backNav||window.history.pushState(null,"",`${t.pathname}${t.search}${t.hash}`),document.title=this.context.title,this._notifyUrlChanged();for(const i of o)try{await i?.afterNavigation?.(this.context)}catch(s){throw Pt(`Plugin "${i.name}" error on afterNavigation hook`,s),s}}}function $r(e){return{name:"lazy",beforeNavigation:()=>{e()}}}globalThis.URLPattern||await Te(()=>import("./index-CBloBB_n.js"),[]);const eh="/",po=new th({routes:[{path:Lt(),title:"Home",render:()=>G``},{path:Lt("about"),title:"About",plugins:[$r(()=>Te(()=>import("./app-about-BGKiJfUr.js"),[]))],render:()=>G``},{path:Lt("note-wall"),title:"Note Wall",plugins:[$r(()=>Te(()=>Promise.resolve().then(()=>Ku),void 0))],render:()=>G``},{path:Lt("write"),title:"Write",plugins:[$r(()=>Te(()=>import("./app-write-DLE2Mxxa.js"),[]))],render:()=>G``}]});function Lt(e){var t=eh;return e&&(t=t+e),t}var rh=Object.defineProperty,nh=Object.getOwnPropertyDescriptor,Wt=(e,t,r,n)=>{for(var o=n>1?void 0:n?nh(t,r):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(o=(n?s(t,r,o):s(o))||o);return n&&o&&rh(t,r,o),o};let mt=class extends gt{constructor(){super(...arguments),this.message="Welcome to my demo!",this.nostrAddy="",this.bio="",this.profilePic="",this.isSignedIn=!1,this.publicKey=""}async firstUpdated(){console.log("Welcome to my home page")}connectedCallback(){super.connectedCallback(),this.addEventListener("user-state-changed",e=>{const t=e.detail;this.nostrAddy=t.nostrAddy,this.bio=t.bio,this.profilePic=t.profilePic,this.isSignedIn=t.isSignedIn})}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("profile-updated",this.updateProfileFromEvent.bind(this)),window.removeEventListener("user-signed-out",this.handlesSignOut.bind(this))}updateProfileFromEvent(e){console.log("Profile updated event received:",e.detail);const t=e.detail;this.nostrAddy=t.nostrAddy,this.bio=t.bio,this.profilePic=t.profilePic,this.isSignedIn=!0,this.requestUpdate()}handlesSignOut(){this.profilePic="",this.bio="",this.nostrAddy="Guest",this.isSignedIn=!1,this.requestUpdate()}async fetchAndDisplayProfile(e){this.nostrAddy=e,this.bio="Loading profile info...",this.profilePic="/assets/img/loading_pfp.png";try{const r=(await tr.connect("wss://notes.miguelalmodo.com")).subscribe([{kinds:[0],authors:[e]}],{onevent:n=>{const o=JSON.parse(n.content);this.nostrAddy=o.nip05||"No address available",this.bio=o.about||"No bio available",this.profilePic=o.picture||"/assets/img/default_pfp.png",this.requestUpdate()},oneose:()=>r.close()})}catch(t){console.error("Error fetching profile:",t),this.displayGuestView()}}displayGuestView(){this.nostrAddy="",this.bio="Welcome, guest! Please sign in with a browser extension to view your profile.",this.profilePic="/assets/img/default_pfp.png",this.isSignedIn=!1}share(){navigator.share&&navigator.share({title:"A MiggyMofongo Project",text:"This is a personal progressive social web app",url:"https://miguelalmodo.com/dist2"})}render(){return G` + + +
    +
    + +
    +

    Welcome to ${this.nostrAddy||"Guest"}'s Profile

    +
    +

    + You can upgrade your website into + a micro blog client with a social protocol to do things + like browse a feed, compose a note, or post to your network. + +

    + + +
    +Profile Picture + +

    ${this.bio||"Welcome, guest! Please sign in to view your profile."}

    + +
    + + ${"share"in navigator?G` + + Share this personal website with a friend! + `:null} +
    + + + +
    +
    + `}};mt.styles=[fs,ct` + + + + @media (horizontal-viewport-segments: 2) { + #welcomeBar { + flex-direction: row; + align-items: flex-start; + justify-content: space-between; + } + + #welcomeCard { + margin-right: 64px; + } + } + + /* +======================================== +Profile Picture Container +======================================== +*/ +.profile-picture-container { + display: grid; + grid-template-columns: 400px 200px; + grid-template-rows: 250px; + grid-column-gap: 15px; + margin-bottom: 12px; + +} + +.profile-picture-container p { + margin: 0; +} + +.profile-pic { + grid-area: 1/1; + margin-top: 25px; + margin-left: 100px; + margin-bottom: 10px; + border-radius: 50%; +} + +.personal-msg { + grid-area: 1/2; + align-content: center; + align-items: center; +} + + + +.nav-button-container { + justify-self: center; + align-self: end; +} + + `];Wt([S()],mt.prototype,"message",2);Wt([S({type:String})],mt.prototype,"nostrAddy",2);Wt([S({type:String})],mt.prototype,"bio",2);Wt([S({type:String})],mt.prototype,"profilePic",2);Wt([S({type:Boolean})],mt.prototype,"isSignedIn",2);Wt([S({type:String})],mt.prototype,"publicKey",2);mt=Wt([qe("app-home")],mt);var oh=Object.defineProperty,ih=Object.getOwnPropertyDescriptor,Rt=(e,t,r,n)=>{for(var o=n>1?void 0:n?ih(t,r):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(o=(n?s(t,r,o):s(o))||o);return n&&o&&oh(t,r,o),o};let lt=class extends gt{constructor(){super(...arguments),this.title="fostr",this.enableBack=!1,this.nostrAddy="",this.bio="",this.profilePic="",this.isSignedIn=!1,this.publicKey=""}connectedCallback(){super.connectedCallback();const e=localStorage.getItem("pubkey");e?(this.isSignedIn=!0,this.fetchProfileMetadata(e)):this.displayGuestView()}displayGuestView(){this.nostrAddy="",this.bio="Welcome, guest! Please sign in with a browser extension to view your profile.",this.profilePic="/public/assets/img/default_pfp.png",this.isSignedIn=!1,this.dispatchUserStateChanged()}async fetchProfileMetadata(e){try{const r=(await tr.connect("wss://notes.miguelalmodo.com")).subscribe([{kinds:[0],authors:[e]}],{onevent:n=>{const o=JSON.parse(n.content);this.profilePic=o.picture||"/assets/img/default_pfp.png",this.nostrAddy=o.nip05||"no addy available",this.bio=o.about||"bio not available",this.dispatchUserStateChanged()},oneose:()=>r.close()})}catch(t){console.error("Failed to fetch profile metadata:",t),this.displayGuestView()}}async signInWithNostr(){if(window.nostr)try{const e=await window.nostr.getPublicKey();this.isSignedIn=!0,localStorage.setItem("pubkey",e),await this.fetchProfileMetadata(e)}catch(e){console.error("Failed to sign in:",e),this.isSignedIn=!1}else alert("Nostr extension not detected. Please install a Nostr extension.")}signOut(){localStorage.removeItem("pubkey"),this.displayGuestView()}dispatchUserStateChanged(){this.dispatchEvent(new CustomEvent("user-state-changed",{detail:{isSignedIn:this.isSignedIn,nostrAddy:this.nostrAddy,bio:this.bio,profilePic:this.profilePic},bubbles:!0,composed:!0}))}render(){return G` +
    + +
    + ${this.enableBack?G` + Back + `:null} + +

    ${this.title}

    +
    + + + ${this.isSignedIn?"Sign out":"Sign in"} + + +
    + `}};lt.styles=ct` + header { + display: flex; + justify-content: space-between; + align-items: center; + background: var(--app-color-primary); + color: white; + padding: 12px; + padding-top: 4px; + + position: fixed; + left: env(titlebar-area-x, 0); + top: env(titlebar-area-y, 0); + height: env(titlebar-area-height, 30px); + width: env(titlebar-area-width, 100%); + -webkit-app-region: drag; + } + + header h1 { + margin-top: 0; + margin-bottom: 0; + font-size: 12px; + font-weight: bold; + } + + nav a { + margin-left: 10px; + } + + #back-button-block { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + } + + @media(prefers-color-scheme: light) { + header { + color: black; + } + + nav a { + color: initial; + } + } + `;Rt([S({type:String})],lt.prototype,"title",2);Rt([S({type:Boolean})],lt.prototype,"enableBack",2);Rt([S({type:String})],lt.prototype,"nostrAddy",2);Rt([S({type:String})],lt.prototype,"bio",2);Rt([S({type:String})],lt.prototype,"profilePic",2);Rt([S({type:Boolean})],lt.prototype,"isSignedIn",2);Rt([S({type:String})],lt.prototype,"publicKey",2);lt=Rt([qe("app-header")],lt);var sh=Object.defineProperty,ah=Object.getOwnPropertyDescriptor,lh=(e,t,r,n)=>{for(var o=n>1?void 0:n?ah(t,r):t,i=e.length-1,s;i>=0;i--)(s=e[i])&&(o=(n?s(t,r,o):s(o))||o);return n&&o&&sh(t,r,o),o};let Dr=class extends gt{firstUpdated(){po.addEventListener("route-changed",()=>{"startViewTransition"in document?document.startViewTransition(()=>this.requestUpdate()):this.requestUpdate()})}render(){return po.render()}};Dr.styles=ct` + main { + padding-left: 16px; + padding-right: 16px; + padding-bottom: 16px; + } + `;Dr=lh([qe("app-index")],Dr);export{Zs as e,ct as i,S as n,gt as r,fs as s,qe as t,G as x}; +//# sourceMappingURL=index-COc6jZBc.js.map diff --git a/dist2/code/index-COc6jZBc.js.map b/dist2/code/index-COc6jZBc.js.map new file mode 100644 index 0000000..7705cd7 --- /dev/null +++ b/dist2/code/index-COc6jZBc.js.map @@ -0,0 +1 @@ +{"version":3,"mappings":"ssBACA,IAAIA,GAAW,GACf,SAASC,GAAYC,EAAM,CACzBF,GAAWE,CACb,CACA,SAASC,GAAYC,EAAU,GAAI,CACjC,GAAI,CAACJ,GAAU,CACb,MAAMK,EAAU,CAAC,GAAG,SAAS,qBAAqB,QAAQ,CAAC,EACrDC,EAAeD,EAAQ,KAAME,GAAWA,EAAO,aAAa,eAAe,CAAC,EAClF,GAAID,EACFL,GAAYK,EAAa,aAAa,eAAe,CAAC,MACjD,CACL,MAAME,EAAiBH,EAAQ,KAAMI,GAC5B,6BAA6B,KAAKA,EAAE,GAAG,GAAK,wCAAwC,KAAKA,EAAE,GAAG,CACtG,EACD,IAAIP,EAAO,GACPM,IACFN,EAAOM,EAAe,aAAa,KAAK,GAE1CP,GAAYC,EAAK,MAAM,GAAG,EAAE,MAAM,EAAG,EAAE,EAAE,KAAK,GAAG,CAAC,CACxD,CACA,CACE,OAAOF,GAAS,QAAQ,MAAO,EAAE,GAAKI,EAAU,IAAIA,EAAQ,QAAQ,MA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CACD,EAGH,QAAS,CAEP,OAAOA,GAAO,OAAO,EAEzB,EAxBaW,GACJ,OAAS7J;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA;AAAAA,IADL6J,GAANlvC,GAAA,CADNutC,GAAc,WAAW,GACb2B,EAAA","names":["basePath","setBasePath","path","getBasePath","subpath","scripts","configScript","script","fallbackScript","s","__defProp","__defProps","__getOwnPropDesc","__getOwnPropDescs","__getOwnPropSymbols","__hasOwnProp","__propIsEnum","__defNormalProp","obj","key","value","__spreadValues","a","b","prop","__spreadProps","__decorateClass","decorators","target","kind","result","decorator","__accessCheck","member","msg","__privateGet","getter","__privateAdd","__privateSet","setter","t","e","o","n$4","r","n","i","S","c","h","l","p","d","u","f","y","v","_","m","g","$","x","T","E","A","C","P","V","N","H","I","L","k","M","R","z","j","B","r$2","number","bytes","lengths","hash","exists","instance","checkFinished","output","out","min","crypto","u8a","createView","arr","rotr","word","shift","isLE","utf8ToBytes","str","toBytes","data","concatBytes","arrays","sum","pad","Hash$1","wrapConstructor","hashCons","hashC","tmp","randomBytes","bytesLength","setBigUint64","view","byteOffset","_32n","_u32_max","wh","wl","Hash","blockLen","outputLen","padOffset","buffer","len","pos","take","dataView","oview","outLen","state","res","to","length","finished","destroyed","Chi","Maj","SHA256_K","IV","SHA256_W","SHA2","D","F","G","offset","W15","W2","s0","s1","sigma1","T1","T2","sha256","SHA256","_0n","_1n","_2n","hexes","bytesToHex","hex","numberToHexUnpadded","num","hexToNumber","hexToBytes","array","hexByte","byte","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","numberToVarBytesBE","ensureBytes","title","expectedLength","equalBytes","b1","b2","bitLen","bitGet","bitSet","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reset","reseed","seed","gen","sl","pred","validatorFns","val","object","validateObject","validators","optValidators","checkField","fieldName","type","isOptional","checkVal","_3n","_4n","_5n","_8n","mod","pow","power","modulo","pow2","invert","q","tonelliShanks","legendreC","Q","Z","p1div4","Fp","root","Q1div2","t2","ge","FpSqrt","c1","n2","nv","FIELD_FIELDS","validateField","field","initial","opts","map","FpPow","FpInvertBatch","nums","lastMultiplied","acc","inverted","nLength","nBitLength","_nBitLength","nByteLength","Field","ORDER","redef","BITS","BYTES","sqrtP","lhs","rhs","lst","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","mapHashToField","fieldLen","minLen","reduced","wNAF","bits","constTimeNegate","condition","item","neg","W","windows","windowSize","elm","points","base","window","precomputes","mask","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","precomputesMap","transform","comp","validateBasic","curve","validatePointOpts","ut.validateObject","endo","b2n","h2b","ut","DER","sBytes","rBytesLeft","sig","slice","shl","rhl","rl","weierstrassPoints","CURVE","_c","point","_isCompressed","ut.concatBytes","fromBytes","tail","weierstrassEquation","x2","x3","isWithinCurveOrder","assertGE","normPrivateKeyToScalar","wrapPrivateKey","ut.bytesToHex","ut.bytesToNumberBE","mod.mod","pointPrecomputes","assertPrjPoint","other","Point","px","py","pz","is0","toInv","privateKey","left","right","X1","Y1","Z1","X2","Y2","Z2","U1","U2","b3","X3","Y3","Z3","t0","t1","t3","t4","t5","wnaf","k1neg","k1","k2neg","k2","k1p","k2p","scalar","fake","f1p","f2p","mul","iz","ax","ay","zz","cofactor","isTorsionFree","clearCofactor","isCompressed","_bits","validateOpts","weierstrass","curveDef","CURVE_ORDER","compressedLen","uncompressedLen","isValidFieldElement","modN","invN","mod.invert","cat","head","y2","isYOdd","numToNByteStr","ut.numberToBytesBE","isBiggerThanHalfOrder","HALF","normalizeS","slcNum","from","Signature","recovery","msgHash","rec","bits2int_modN","radj","prefix","ir","u1","u2","ut.hexToBytes","utils","mod.getMinHashLength","mod.mapHashToField","getPublicKey","isProbPub","getSharedSecret","privateA","publicB","bits2int","delta","ORDER_MASK","ut.bitMask","int2octets","prepSig","defaultSigOpts","lowS","prehash","ent","h1int","seedArgs","k2sig","kBytes","ik","normS","defaultVerOpts","sign","privKey","ut.createHmacDrbg","verify","signature","publicKey","sg","_sig","derError","error","is","_key","assertHash","buf","assertExists","assertBytes","oHash","iHash","hmac","message","HMAC","getHash","msgs","createCurve","defHash","create","secp256k1P","secp256k1N","divNearest","sqrtMod","_6n","_11n","_22n","_23n","_44n","_88n","b6","b9","b11","b22","b44","b88","b176","b220","b223","secp256k1","a1","a2","POW_2_128","c2","fe","TAGGED_HASH_PREFIXES","taggedHash","tag","messages","tagP","tagH","pointToBytes","numTo32b","modP","GmulAdd","schnorrGetExtPubKey","priv","d_","lift_x","xx","challenge","args","schnorrGetPublicKey","schnorrSign","auxRand","rand","k_","rx","schnorrVerify","pub","schnorr","bool","assert","SHA224","assertNumber","chain","wrap","encode","decode","alphabet","digits","input","letter","index","join","separator","padding","chr","end","normalize","fn","convertRadix","carry","done","digit","digitBase","gcd","radix2carry","convertRadix2","radix","radix2","revPadding","unsafeWrapper","base16","base32","base64","base64url","genBase58","abc","base58","XMR_BLOCK_LEN","base58xmr","block","BECH_ALPHABET","POLYMOD_GENERATORS","bech32Polymod","pre","chk","bechChecksum","words","encodingConst","genBech32","encoding","ENCODING_CONST","_words","fromWords","toWords","fromWordsUnsafe","limit","actualLength","lowered","sepIndex","decodeUnsafe","decodeToBytes","bech32","utf8","CODERS","isBytes","u32","checkOpts","defaults","diff","wrapCipher","params","BLOCK_SIZE","POLY","mul2","sbox","box","invSbox","rotr32_8","rotl32_8","genTtable","T0","T3","T01","T23","sbox2","idx","tableEncoding","tableDecoding","xPowers","expandKeyLE","abytes","k32","Nk","subByte","applySbox","xk","expandKeyDecLE","encKey","w","apply0123","s2","s3","encrypt","rounds","decrypt","getDst","dst","validateBlockDecrypt","validateBlockEncrypt","plaintext","pcks5","remaining","validatePCKS","lastByte","padPCKS","tmp32","paddingByte","cbc","iv","_out","n32","ciphertext","ps0","ps1","ps2","ps3","o0","o1","o2","o3","_utf8ToBytes","sigma16","sigma32","sigma16_32","sigma32_32","rotl","isAligned32","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","runCipher","core","sigma","nonce","counter","b32","isAligned","d32","o32","pos32","posj","createCipher","allowShortKeys","extendNonceFn","counterLength","counterRight","anumber","abool","toClean","nonceNcLen","nc","chachaCore","cnt","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","oi","chacha20","extract","ikm","salt","HKDF_COUNTER","EMPTY_BUFFER","expand","prk","info","blocks","okm","HMACTmp","__export","all","name","verifiedSymbol","isRecord","validateEvent","event","i2","utils_exports","Queue","QueueNode","binarySearch","insertEventIntoAscendingList","insertEventIntoDescendingList","normalizeURL","utf8Decoder","utf8Encoder","url","sortedArray","found","compare","start","mid","cmp","newNode","target2","JS","secretKey","getEventHash","valid","serializeEvent","evt","eventHash","generateSecretKey","finalizeEvent","verifyEvent","kinds_exports","Application","BadgeAward","BadgeDefinition","BlockedRelaysList","BookmarkList","Bookmarksets","Calendar","CalendarEventRSVP","ChannelCreation","ChannelHideMessage","ChannelMessage","ChannelMetadata","ChannelMuteUser","ClassifiedListing","ClientAuth","CommunitiesList","CommunityDefinition","CommunityPostApproval","Contacts","CreateOrUpdateProduct","CreateOrUpdateStall","Curationsets","Date2","DirectMessageRelaysList","DraftClassifiedListing","DraftLong","Emojisets","EncryptedDirectMessage","EventDeletion","FileMetadata","FileServerPreference","Followsets","GenericRepost","Genericlists","GiftWrap","HTTPAuth","Handlerinformation","Handlerrecommendation","Highlights","InterestsList","Interestsets","JobFeedback","JobRequest","JobResult","Label","LightningPubRPC","LiveChatMessage","LiveEvent","LongFormArticle","Metadata","Mutelist","NWCWalletInfo","NWCWalletRequest","NWCWalletResponse","NostrConnect","OpenTimestamps","Pinlist","PrivateDirectMessage","ProblemTracker","ProfileBadges","PublicChatsList","Reaction","RecommendRelay","RelayList","Relaysets","Report","Reporting","Repost","Seal","SearchRelaysList","ShortTextNote","Time","UserEmojiList","UserStatuses","Zap","ZapGoal","ZapRequest","classifyKind","isEphemeralKind","isKind","isParameterizedReplaceableKind","isRegularKind","isReplaceableKind","kindAsArray","matchFilter","filter","tagName","values","matchFilters","filters","fakejson_exports","getHex64","getInt","getSubscriptionId","matchEventId","matchEventKind","matchEventPubkey","json","sliced","pstart","pend","id","pubkey","nip42_exports","makeAuthEvent","relayURL","yieldThread","resolve","ch","handler","AbstractRelay","relay","reason","sub","ep","cr","reject","err","ev","subid","so","alreadyHave","payload","ok","signAuthEvent","ret","subscription","Subscription","_WebSocket","Relay","_WebSocket2","nip19_exports","BECH32_REGEX","Bech32MaxSize","NostrTypeGuard","encodeBytes","naddrEncode","neventEncode","noteEncode","nprofileEncode","npubEncode","nsecEncode","integerToUint8Array","uint8Array","nip19","tlv","parseTLV","bytesToHex2","rest","encodeBech32","profile","encodeTLV","kindArray","addr","entries","vs","entry","nip04_exports","text","privkey","bytesToHex3","normalizedKey","getNormalizedX","ctb64","ivb64","nip05_exports","NIP05_REGEX","isNip05","isValid","queryProfile","searchDomain","useFetchImplementation","_fetch","fetchImplementation","domain","query","fullname","match","nip05","nip10_exports","parse","eTags","eTagIndex","eTag","eTagEventId","eTagRelayUrl","eTagMarker","eventPointer","isFirstETag","isLastETag","nip11_exports","fetchRelayInformation","useFetchImplementation2","_fetch2","nip13_exports","fastEventHash","getPow","minePow","count","nibble","unsigned","difficulty","now2","bytesToHex4","sha2562","nip18_exports","finishRepostEvent","getRepostedEvent","getRepostedEventPointer","reposted","relayUrl","lastETag","lastPTag","skipVerification","pointer","repostedEvent","nip21_exports","NOSTR_URI_REGEX","parse2","test","uri","nip25_exports","finishReactionEvent","getReactedEventPointer","reacted","inheritedTags","nip27_exports","matchAll","regex","replaceAll","content","matches","replacer","nip28_exports","channelCreateEvent","channelHideMessageEvent","channelMessageEvent","channelMetadataEvent","channelMuteUserEvent","tags","nip30_exports","EMOJI_SHORTCODE_REGEX","matchAll2","regex2","replaceAll2","shortcode","nip39_exports","useFetchImplementation3","validateGithub","_fetch3","username","proof","nip44_exports","decrypt2","encrypt2","getConversationKey","v2","minPlaintextSize","maxPlaintextSize","privkeyA","pubkeyB","sharedX","secp256k12","hkdf_extract","sha2563","getMessageKeys","conversationKey","keys","hkdf_expand","calcPaddedLen","nextPower","chunk","writeU16BE","unpadded","unpaddedLen","suffix","concatBytes2","unpad","padded","hmacAad","aad","combined","decodePayload","plen","base642","dlen","vers","randomBytes2","chacha_key","chacha_nonce","hmac_key","mac","calculatedMac","nip47_exports","makeNwcRequestEvent","parseConnectionString","connectionString","pathname","searchParams","secret","invoice","encryptedContent","eventTemplate","nip57_exports","getZapEndpoint","makeZapReceipt","makeZapRequest","useFetchImplementation4","validateZapRequest","_fetch4","metadata","lnurl","lud06","lud16","bech322","body","amount","relays","comment","zr","zapRequestString","zapRequest","preimage","bolt11","paidAt","tagsFromZapRequest","zap","nip59_exports","createRumor","createSeal","createWrap","unwrapEvent","unwrapManyEvents","wrapEvent","wrapManyEvents","TWO_DAYS","now","randomNow","nip44ConversationKey","nip44Encrypt","nip44Decrypt","rumor","recipientPublicKey","seal","randomKey","senderPrivateKey","recipientsPublicKeys","senderPublicKey","wrappeds","recipientPrivateKey","unwrappedSeal","wrappedEvents","unwrappedEvents","nip98_exports","getToken","hashPayload","unpackEventFromToken","validateEvent2","validateEventKind","validateEventMethodTag","validateEventPayloadTag","validateEventTimestamp","validateEventUrlTag","validateToken","_authorizationScheme","loginUrl","httpMethod","includeAuthorizationScheme","signedEvent","base643","token","method","eventB64","urlTag","methodTag","sha2564","bytesToHex5","payloadTag","payloadHash","card_styles_default","css","HasSlotController","host","slotNames","slot","node","el","slotName","component_styles_default","_hasRecordedInitialProperties","ShoelaceElement","LitElement","component","options","elementConstructor","currentlyRegisteredConstructor","newVersion","existingVersion","oldValue","newValue","changedProperties","property","i$1","SlCard","html","classMap","spinner_styles_default","connectedElements","translations","fallback","documentDirection","documentLanguage","isClient","documentElementObserver","update","registerTranslation","translation","code","LocalizeController$1","lang","_a","_b","locale","language","region","primary","secondary","term","dateToFormat","numberToFormat","unit","slide","en_default","LocalizeController","DefaultLocalizationController","SlSpinner","formCollections","reportValidityOverloads","checkValidityOverloads","userInteractedControls","interactions","FormControlController","disabled","isButton","reportValidity","control","emittedEvents","elements","element","formId","form","formCollection","hasInteracted","submitter","button","attr","required","originalInvalidEvent","slInvalidEvent","validValidityState","button_styles_default","library","library_default_default","icons","systemLibrary","library_system_default","registry","watchedIcons","watchIcon","icon","unwatchIcon","getIconLibrary","lib","icon_styles_default","watch","propertyName","resolvedOptions","proto","decoratedFnName","watchedProperties","changedProps","CACHEABLE_ERROR","RETRYABLE_ERROR","parser","iconCache","SlIcon","fileData","div","svg","svgEl","fromLibrary","iconResolver","isTemplateResult","shadowSVG","SlButton","isLink","literal","ifDefined","styles","NoteWall","migsRelay","note","urlMatch","textContent","youtubeRegex","youtubeMatch","youtubeVideoId","thumbnailUrl","imgRegex","imgMatch","customElement","KEY","setDebug","log","action","createLogger","RouteEvent","context","Router","config","route","plugins","plugin","lazy","__vitePreload","baseURL","router","resolveRouterPath","noteWall","unresolvedPath","resolvedPath","AppHome","detail","profileData","AppHeader","storedPubkey","userPubkey","AppIndex"],"ignoreList":[0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,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,52,53,54,55,56,57,58,59,60,61,62,63,66,67,68],"sources":["../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.3Y6SB6QS.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.B3BW2AY6.js","../../index.html?html-proxy&index=0.js","../../node_modules/@lit/reactive-element/css-tag.js","../../node_modules/@lit/reactive-element/reactive-element.js","../../node_modules/lit-html/lit-html.js","../../node_modules/lit-element/lit-element.js","../../node_modules/@lit/reactive-element/decorators/custom-element.js","../../node_modules/@lit/reactive-element/decorators/property.js","../../node_modules/@lit/reactive-element/decorators/state.js","../../node_modules/@lit/reactive-element/decorators/base.js","../../node_modules/@lit/reactive-element/decorators/query.js","../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js","../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js","../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js","../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js","../../node_modules/@noble/curves/esm/abstract/utils.js","../../node_modules/@noble/curves/esm/abstract/modular.js","../../node_modules/@noble/curves/esm/abstract/curve.js","../../node_modules/@noble/curves/esm/abstract/weierstrass.js","../../node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js","../../node_modules/@noble/curves/esm/_shortw_utils.js","../../node_modules/@noble/curves/esm/secp256k1.js","../../node_modules/@noble/hashes/esm/crypto.js","../../node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/hashes/esm/_assert.js","../../node_modules/@noble/hashes/esm/_sha2.js","../../node_modules/@noble/hashes/esm/sha256.js","../../node_modules/@scure/base/lib/esm/index.js","../../node_modules/@noble/ciphers/esm/_assert.js","../../node_modules/@noble/ciphers/esm/utils.js","../../node_modules/@noble/ciphers/esm/aes.js","../../node_modules/@noble/ciphers/esm/_arx.js","../../node_modules/@noble/ciphers/esm/chacha.js","../../node_modules/@noble/hashes/esm/hmac.js","../../node_modules/@noble/hashes/esm/hkdf.js","../../node_modules/nostr-tools/lib/esm/index.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.A5D6FTFY.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.NYIIDP5N.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.TUVJKY7S.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.UYAO2JRR.js","../../node_modules/lit-html/directive.js","../../node_modules/lit-html/directives/class-map.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.LJF3QW2H.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.7CVSDULN.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.7DUCI5S4.js","../../node_modules/@shoelace-style/localize/dist/index.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.MAS2SHYD.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.WLV3FVBR.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.TLKDQ5JG.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.2RCF7SLU.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.MAQXLKQ7.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.P7ZG6EMR.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.3TFKS637.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.ZL53POKZ.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.QLXRCYS4.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.CCJUT23E.js","../../node_modules/lit-html/directive-helpers.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.E6QAPUBK.js","../../node_modules/lit-html/static.js","../../node_modules/lit-html/directives/if-defined.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.N2SNE3QN.js","../../node_modules/@shoelace-style/shoelace/dist/chunks/chunk.Q6JS2LBD.js","../../src/styles/shared-styles.ts","../../src/pages/note-wall.ts","../../node_modules/@thepassle/app-tools/utils/log.js","../../node_modules/@thepassle/app-tools/router/index.js","../../node_modules/@thepassle/app-tools/router/plugins/lazy.js","../../src/router.ts","../../src/pages/app-home.ts","../../src/components/header.ts","../../src/app-index.ts"],"sourcesContent":["// src/utilities/base-path.ts\nvar basePath = \"\";\nfunction setBasePath(path) {\n basePath = path;\n}\nfunction getBasePath(subpath = \"\") {\n if (!basePath) {\n const scripts = [...document.getElementsByTagName(\"script\")];\n const configScript = scripts.find((script) => script.hasAttribute(\"data-shoelace\"));\n if (configScript) {\n setBasePath(configScript.getAttribute(\"data-shoelace\"));\n } else {\n const fallbackScript = scripts.find((s) => {\n return /shoelace(\\.min)?\\.js($|\\?)/.test(s.src) || /shoelace-autoloader(\\.min)?\\.js($|\\?)/.test(s.src);\n });\n let path = \"\";\n if (fallbackScript) {\n path = fallbackScript.getAttribute(\"src\");\n }\n setBasePath(path.split(\"/\").slice(0, -1).join(\"/\"));\n }\n }\n return basePath.replace(/\\/$/, \"\") + (subpath ? `/${subpath.replace(/^\\//, \"\")}` : ``);\n}\n\nexport {\n setBasePath,\n getBasePath\n};\n","var __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __knownSymbol = (name, symbol) => {\n return (symbol = Symbol[name]) ? symbol : Symbol.for(\"Symbol.\" + name);\n};\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nvar __decorateClass = (decorators, target, key, kind) => {\n var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;\n for (var i = decorators.length - 1, decorator; i >= 0; i--)\n if (decorator = decorators[i])\n result = (kind ? decorator(target, key, result) : decorator(result)) || result;\n if (kind && result)\n __defProp(target, key, result);\n return result;\n};\nvar __accessCheck = (obj, member, msg) => {\n if (!member.has(obj))\n throw TypeError(\"Cannot \" + msg);\n};\nvar __privateGet = (obj, member, getter) => {\n __accessCheck(obj, member, \"read from private field\");\n return getter ? getter.call(obj) : member.get(obj);\n};\nvar __privateAdd = (obj, member, value) => {\n if (member.has(obj))\n throw TypeError(\"Cannot add the same private member more than once\");\n member instanceof WeakSet ? member.add(obj) : member.set(obj, value);\n};\nvar __privateSet = (obj, member, value, setter) => {\n __accessCheck(obj, member, \"write to private field\");\n setter ? setter.call(obj, value) : member.set(obj, value);\n return value;\n};\nvar __await = function(promise, isYieldStar) {\n this[0] = promise;\n this[1] = isYieldStar;\n};\nvar __yieldStar = (value) => {\n var obj = value[__knownSymbol(\"asyncIterator\")];\n var isAwait = false;\n var method;\n var it = {};\n if (obj == null) {\n obj = value[__knownSymbol(\"iterator\")]();\n method = (k) => it[k] = (x) => obj[k](x);\n } else {\n obj = obj.call(value);\n method = (k) => it[k] = (v) => {\n if (isAwait) {\n isAwait = false;\n if (k === \"throw\")\n throw v;\n return v;\n }\n isAwait = true;\n return {\n done: false,\n value: new __await(new Promise((resolve) => {\n var x = obj[k](v);\n if (!(x instanceof Object))\n throw TypeError(\"Object expected\");\n resolve(x);\n }), 1)\n };\n };\n }\n return it[__knownSymbol(\"iterator\")] = () => it, method(\"next\"), \"throw\" in obj ? method(\"throw\") : it.throw = (x) => {\n throw x;\n }, \"return\" in obj && method(\"return\"), it;\n};\n\nexport {\n __spreadValues,\n __spreadProps,\n __decorateClass,\n __privateGet,\n __privateAdd,\n __privateSet,\n __yieldStar\n};\n","\n import { setBasePath } from '@shoelace-style/shoelace/dist/utilities/base-path.js';\n setBasePath('https://cdn.jsdelivr.net/npm/@shoelace-style/shoelace@2.16.0/cdn/');\n ","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&\"adoptedStyleSheets\"in Document.prototype&&\"replace\"in CSSStyleSheet.prototype,s=Symbol(),o=new WeakMap;class n{constructor(t,e,o){if(this._$cssResult$=!0,o!==s)throw Error(\"CSSResult is not constructable. Use `unsafeCSS` or `css` instead.\");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=o.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&o.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new n(\"string\"==typeof t?t:t+\"\",void 0,s),i=(t,...e)=>{const o=1===t.length?t[0]:e.reduce(((e,s,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if(\"number\"==typeof t)return t;throw Error(\"Value passed to 'css' function must be a 'css' function result: \"+t+\". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.\")})(s)+t[o+1]),t[0]);return new n(o,t,s)},S=(s,o)=>{if(e)s.adoptedStyleSheets=o.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet));else for(const e of o){const o=document.createElement(\"style\"),n=t.litNonce;void 0!==n&&o.setAttribute(\"nonce\",n),o.textContent=e.cssText,s.appendChild(o)}},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e=\"\";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;export{n as CSSResult,S as adoptStyles,i as css,c as getCompatibleStyle,e as supportsAdoptingStyleSheets,r as unsafeCSS};\n//# sourceMappingURL=css-tag.js.map\n","import{getCompatibleStyle as t,adoptStyles as s}from\"./css-tag.js\";export{CSSResult,adoptStyles,css,getCompatibleStyle,supportsAdoptingStyleSheets,unsafeCSS}from\"./css-tag.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{is:i,defineProperty:e,getOwnPropertyDescriptor:r,getOwnPropertyNames:h,getOwnPropertySymbols:o,getPrototypeOf:n}=Object,a=globalThis,c=a.trustedTypes,l=c?c.emptyScript:\"\",p=a.reactiveElementPolyfillSupport,d=(t,s)=>t,u={toAttribute(t,s){switch(s){case Boolean:t=t?l:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,s){let i=t;switch(s){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},f=(t,s)=>!i(t,s),y={attribute:!0,type:String,converter:u,reflect:!1,hasChanged:f};Symbol.metadata??=Symbol(\"metadata\"),a.litPropertyMetadata??=new WeakMap;class b extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,s=y){if(s.state&&(s.attribute=!1),this._$Ei(),this.elementProperties.set(t,s),!s.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(t,i,s);void 0!==r&&e(this.prototype,t,r)}}static getPropertyDescriptor(t,s,i){const{get:e,set:h}=r(this.prototype,t)??{get(){return this[s]},set(t){this[s]=t}};return{get(){return e?.call(this)},set(s){const r=e?.call(this);h.call(this,s),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??y}static _$Ei(){if(this.hasOwnProperty(d(\"elementProperties\")))return;const t=n(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(d(\"finalized\")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(d(\"properties\"))){const t=this.properties,s=[...h(t),...o(t)];for(const i of s)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const s=litPropertyMetadata.get(t);if(void 0!==s)for(const[t,i]of s)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,s]of this.elementProperties){const i=this._$Eu(t,s);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(s){const i=[];if(Array.isArray(s)){const e=new Set(s.flat(1/0).reverse());for(const s of e)i.unshift(t(s))}else void 0!==s&&i.push(t(s));return i}static _$Eu(t,s){const i=s.attribute;return!1===i?void 0:\"string\"==typeof i?i:\"string\"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,s,i){this._$AK(t,i)}_$EC(t,s){const i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(void 0!==e&&!0===i.reflect){const r=(void 0!==i.converter?.toAttribute?i.converter:u).toAttribute(s,i.type);this._$Em=t,null==r?this.removeAttribute(e):this.setAttribute(e,r),this._$Em=null}}_$AK(t,s){const i=this.constructor,e=i._$Eh.get(t);if(void 0!==e&&this._$Em!==e){const t=i.getPropertyOptions(e),r=\"function\"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:u;this._$Em=e,this[e]=r.fromAttribute(s,t.type),this._$Em=null}}requestUpdate(t,s,i){if(void 0!==t){if(i??=this.constructor.getPropertyOptions(t),!(i.hasChanged??f)(this[t],s))return;this.P(t,s,i)}!1===this.isUpdatePending&&(this._$ES=this._$ET())}P(t,s,i){this._$AL.has(t)||this._$AL.set(t,s),!0===i.reflect&&this._$Em!==t&&(this._$Ej??=new Set).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,s]of this._$Ep)this[t]=s;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[s,i]of t)!0!==i.wrapped||this._$AL.has(s)||void 0===this[s]||this.P(s,this[s],i)}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),this._$EO?.forEach((t=>t.hostUpdate?.())),this.update(s)):this._$EU()}catch(s){throw t=!1,this._$EU(),s}t&&this._$AE(s)}willUpdate(t){}_$AE(t){this._$EO?.forEach((t=>t.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&=this._$Ej.forEach((t=>this._$EC(t,this[t]))),this._$EU()}updated(t){}firstUpdated(t){}}b.elementStyles=[],b.shadowRootOptions={mode:\"open\"},b[d(\"elementProperties\")]=new Map,b[d(\"finalized\")]=new Map,p?.({ReactiveElement:b}),(a.reactiveElementVersions??=[]).push(\"2.0.4\");export{b as ReactiveElement,u as defaultConverter,f as notEqual};\n//# sourceMappingURL=reactive-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,i=t.trustedTypes,s=i?i.createPolicy(\"lit-html\",{createHTML:t=>t}):void 0,e=\"$lit$\",h=`lit$${Math.random().toFixed(9).slice(2)}$`,o=\"?\"+h,n=`<${o}>`,r=document,l=()=>r.createComment(\"\"),c=t=>null===t||\"object\"!=typeof t&&\"function\"!=typeof t,a=Array.isArray,u=t=>a(t)||\"function\"==typeof t?.[Symbol.iterator],d=\"[ \\t\\n\\f\\r]\",f=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,v=/-->/g,_=/>/g,m=RegExp(`>|${d}(?:([^\\\\s\"'>=/]+)(${d}*=${d}*(?:[^ \\t\\n\\f\\r\"'\\`<>=]|(\"|')|))|$)`,\"g\"),p=/'/g,g=/\"/g,$=/^(?:script|style|textarea|title)$/i,y=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),x=y(1),b=y(2),w=y(3),T=Symbol.for(\"lit-noChange\"),E=Symbol.for(\"lit-nothing\"),A=new WeakMap,C=r.createTreeWalker(r,129);function P(t,i){if(!a(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==s?s.createHTML(i):i}const V=(t,i)=>{const s=t.length-1,o=[];let r,l=2===i?\"\":3===i?\"\":\"\",c=f;for(let i=0;i\"===u[0]?(c=r??f,d=-1):void 0===u[1]?d=-2:(d=c.lastIndex-u[2].length,a=u[1],c=void 0===u[3]?m:'\"'===u[3]?g:p):c===g||c===p?c=m:c===v||c===_?c=f:(c=m,r=void 0);const x=c===m&&t[i+1].startsWith(\"/>\")?\" \":\"\";l+=c===f?s+n:d>=0?(o.push(a),s.slice(0,d)+e+s.slice(d)+h+x):s+h+(-2===d?i:x)}return[P(t,l+(t[s]||\"\")+(2===i?\"\":3===i?\"\":\"\")),o]};class N{constructor({strings:t,_$litType$:s},n){let r;this.parts=[];let c=0,a=0;const u=t.length-1,d=this.parts,[f,v]=V(t,s);if(this.el=N.createElement(f,n),C.currentNode=this.el.content,2===s||3===s){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(r=C.nextNode())&&d.length0){r.textContent=i?i.emptyScript:\"\";for(let i=0;i2||\"\"!==s[0]||\"\"!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=E}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=S(this,t,i,0),o=!c(t)||t!==this._$AH&&t!==T,o&&(this._$AH=t);else{const e=t;let n,r;for(t=h[0],n=0;n{const e=s?.renderBefore??i;let h=e._$litPart$;if(void 0===h){const t=s?.renderBefore??null;e._$litPart$=h=new R(i.insertBefore(l(),t),t,void 0,s??{})}return h._$AI(t),h};export{Z as _$LH,x as html,w as mathml,T as noChange,E as nothing,B as render,b as svg};\n//# sourceMappingURL=lit-html.js.map\n","import{ReactiveElement as t}from\"@lit/reactive-element\";export*from\"@lit/reactive-element\";import{render as e,noChange as s}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class r extends t{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return s}}r._$litElement$=!0,r[\"finalized\"]=!0,globalThis.litElementHydrateSupport?.({LitElement:r});const i=globalThis.litElementPolyfillSupport;i?.({LitElement:r});const o={_$AK:(t,e,s)=>{t._$AK(e,s)},_$AL:t=>t._$AL};(globalThis.litElementVersions??=[]).push(\"4.1.1\");export{r as LitElement,o as _$LE};\n//# sourceMappingURL=lit-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=t=>(e,o)=>{void 0!==o?o.addInitializer((()=>{customElements.define(t,e)})):customElements.define(t,e)};export{t as customElement};\n//# sourceMappingURL=custom-element.js.map\n","import{defaultConverter as t,notEqual as e}from\"../reactive-element.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o={attribute:!0,type:String,converter:t,reflect:!1,hasChanged:e},r=(t=o,e,r)=>{const{kind:n,metadata:i}=r;let s=globalThis.litPropertyMetadata.get(i);if(void 0===s&&globalThis.litPropertyMetadata.set(i,s=new Map),s.set(r.name,t),\"accessor\"===n){const{name:o}=r;return{set(r){const n=e.get.call(this);e.set.call(this,r),this.requestUpdate(o,n,t)},init(e){return void 0!==e&&this.P(o,void 0,t),e}}}if(\"setter\"===n){const{name:o}=r;return function(r){const n=this[o];e.call(this,r),this.requestUpdate(o,n,t)}}throw Error(\"Unsupported decorator location: \"+n)};function n(t){return(e,o)=>\"object\"==typeof o?r(t,e,o):((t,e,o)=>{const r=e.hasOwnProperty(o);return e.constructor.createProperty(o,r?{...t,wrapped:!0}:t),r?Object.getOwnPropertyDescriptor(e,o):void 0})(t,e,o)}export{n as property,r as standardProperty};\n//# sourceMappingURL=property.js.map\n","import{property as t}from\"./property.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */function r(r){return t({...r,state:!0,attribute:!1})}export{r as state};\n//# sourceMappingURL=state.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst e=(e,t,c)=>(c.configurable=!0,c.enumerable=!0,Reflect.decorate&&\"object\"!=typeof t&&Object.defineProperty(e,t,c),c);export{e as desc};\n//# sourceMappingURL=base.js.map\n","import{desc as t}from\"./base.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */function e(e,r){return(n,s,i)=>{const o=t=>t.renderRoot?.querySelector(e)??null;if(r){const{get:e,set:r}=\"object\"==typeof s?n:i??(()=>{const t=Symbol();return{get(){return this[t]},set(e){this[t]=e}}})();return t(n,s,{get(){let t=e.call(this);return void 0===t&&(t=o(this),(null!==t||this.hasUpdated)&&r.call(this,t)),t}})}return t(n,s,{get(){return o(this)}})}}export{e as query};\n//# sourceMappingURL=query.js.map\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nfunction bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nexport class SHA2 extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map","import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2 {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a) => a instanceof Uint8Array;\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (u8a(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\nexport function equalBytes(b1, b2) {\n // We don't care about timing attacks here\n if (b1.length !== b2.length)\n return false;\n for (let i = 0; i < b1.length; i++)\n if (b1[i] !== b2[i])\n return false;\n return true;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n, pos, value) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array,\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x) => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, precomputesMap, n, transform) {\n // @ts-ignore\n const W = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data) {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02)\n throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len)\n throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000)\n throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!(data instanceof Uint8Array))\n throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30)\n throw new E('Invalid signature tag');\n if (data[1] !== l - 2)\n throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig) {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num) {\n if (!isWithinCurveOrder(num))\n throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (key instanceof Uint8Array)\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n const pointPrecomputes = new Map();\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n) {\n const I = Point.ZERO;\n if (n === _0n)\n return I;\n assertGE(n); // Will throw on 0\n if (n === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, n);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n assertGE(scalar);\n let n = scalar;\n let point, fake; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function isValidFieldElement(num) {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r))\n throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s))\n throw new Error('s must be 0 < s < CURVE.n');\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n if (typeof num !== 'bigint')\n throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || sg instanceof Uint8Array) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\nexport const secp256k1 = createCurve({\n a: BigInt(0),\n b: BigInt(7),\n Fp,\n n: secp256k1N,\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true,\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n if (!fe(x))\n throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r))\n return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\n// Check if object doens't have custom constructor (like Uint8Array/Array)\nconst isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","export function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nexport function bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nexport function bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nexport function hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nexport function exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nexport function output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nconst assert = {\n number,\n bool,\n bytes,\n hash,\n exists,\n output,\n};\nexport default assert;\n//# sourceMappingURL=_assert.js.map","import assert from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nexport class SHA2 extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n assert.exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n assert.exists(this);\n assert.output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map","import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = new Uint32Array(64);\nclass SHA256 extends SHA2 {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = wrapConstructor(() => new SHA256());\nexport const sha224 = wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nexport function assertNumber(n) {\n if (!Number.isSafeInteger(n))\n throw new Error(`Wrong integer: ${n}`);\n}\nfunction chain(...args) {\n const wrap = (a, b) => (c) => a(b(c));\n const encode = Array.from(args)\n .reverse()\n .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);\n const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);\n return { encode, decode };\n}\nfunction alphabet(alphabet) {\n return {\n encode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('alphabet.encode input should be an array of numbers');\n return digits.map((i) => {\n assertNumber(i);\n if (i < 0 || i >= alphabet.length)\n throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);\n return alphabet[i];\n });\n },\n decode: (input) => {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('alphabet.decode input should be array of strings');\n return input.map((letter) => {\n if (typeof letter !== 'string')\n throw new Error(`alphabet.decode: not string element=${letter}`);\n const index = alphabet.indexOf(letter);\n if (index === -1)\n throw new Error(`Unknown letter: \"${letter}\". Allowed: ${alphabet}`);\n return index;\n });\n },\n };\n}\nfunction join(separator = '') {\n if (typeof separator !== 'string')\n throw new Error('join separator should be string');\n return {\n encode: (from) => {\n if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))\n throw new Error('join.encode input should be array of strings');\n for (let i of from)\n if (typeof i !== 'string')\n throw new Error(`join.encode: non-string input=${i}`);\n return from.join(separator);\n },\n decode: (to) => {\n if (typeof to !== 'string')\n throw new Error('join.decode input should be string');\n return to.split(separator);\n },\n };\n}\nfunction padding(bits, chr = '=') {\n assertNumber(bits);\n if (typeof chr !== 'string')\n throw new Error('padding chr should be string');\n return {\n encode(data) {\n if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of data)\n if (typeof i !== 'string')\n throw new Error(`padding.encode: non-string input=${i}`);\n while ((data.length * bits) % 8)\n data.push(chr);\n return data;\n },\n decode(input) {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of input)\n if (typeof i !== 'string')\n throw new Error(`padding.decode: non-string input=${i}`);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('Invalid padding: string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n if (!(((end - 1) * bits) % 8))\n throw new Error('Invalid padding: string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction normalize(fn) {\n if (typeof fn !== 'function')\n throw new Error('normalize fn should be function');\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nfunction convertRadix(data, from, to) {\n if (from < 2)\n throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);\n if (to < 2)\n throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);\n if (!Array.isArray(data))\n throw new Error('convertRadix: data should be array');\n if (!data.length)\n return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data);\n digits.forEach((d) => {\n assertNumber(d);\n if (d < 0 || d >= from)\n throw new Error(`Wrong integer: ${d}`);\n });\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < digits.length; i++) {\n const digit = digits[i];\n const digitBase = from * carry + digit;\n if (!Number.isSafeInteger(digitBase) ||\n (from * carry) / from !== carry ||\n digitBase - digit !== from * carry) {\n throw new Error('convertRadix: carry overflow');\n }\n carry = digitBase % to;\n digits[i] = Math.floor(digitBase / to);\n if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done)\n continue;\n else if (!digits[i])\n pos = i;\n else\n done = false;\n }\n res.push(carry);\n if (done)\n break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n res.push(0);\n return res.reverse();\n}\nconst gcd = (a, b) => (!b ? a : gcd(b, a % b));\nconst radix2carry = (from, to) => from + (to - gcd(from, to));\nfunction convertRadix2(data, from, to, padding) {\n if (!Array.isArray(data))\n throw new Error('convertRadix2: data should be array');\n if (from <= 0 || from > 32)\n throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32)\n throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n }\n let carry = 0;\n let pos = 0;\n const mask = 2 ** to - 1;\n const res = [];\n for (const n of data) {\n assertNumber(n);\n if (n >= 2 ** from)\n throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32)\n throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to)\n res.push(((carry >> (pos - to)) & mask) >>> 0);\n carry &= 2 ** pos - 1;\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from)\n throw new Error('Excess padding');\n if (!padding && carry)\n throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0)\n res.push(carry >>> 0);\n return res;\n}\nfunction radix(num) {\n assertNumber(num);\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), 2 ** 8, num);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix.decode input should be array of strings');\n return Uint8Array.from(convertRadix(digits, num, 2 ** 8));\n },\n };\n}\nfunction radix2(bits, revPadding = false) {\n assertNumber(bits);\n if (bits <= 0 || bits > 32)\n throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix2.decode input should be array of strings');\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\nfunction unsafeWrapper(fn) {\n if (typeof fn !== 'function')\n throw new Error('unsafeWrapper fn should be function');\n return function (...args) {\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n assertNumber(len);\n if (typeof fn !== 'function')\n throw new Error('checksum fn should be function');\n return {\n encode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.encode: input should be Uint8Array');\n const checksum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(checksum, data.length);\n return res;\n },\n decode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const newChecksum = fn(payload).slice(0, len);\n const oldChecksum = data.slice(-len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\nexport const utils = { alphabet, chain, checksum, radix, radix2, join, padding };\nexport const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\nexport const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\nexport const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\nexport const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\nexport const base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\nexport const base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\nconst genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));\nexport const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\nexport const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\nexport const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\nexport const base58xmr = {\n encode(data) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n let res = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\nexport const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));\n}\nfunction genBech32(encoding) {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n if (typeof prefix !== 'string')\n throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);\n if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))\n throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);\n const actualLength = prefix.length + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n prefix = prefix.toLowerCase();\n return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;\n }\n function decode(str, limit = 90) {\n if (typeof str !== 'string')\n throw new Error(`bech32.decode input should be string, not ${typeof str}`);\n if (str.length < 8 || (limit !== false && str.length > limit))\n throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n str = lowered;\n const sepIndex = str.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = str.slice(0, sepIndex);\n const _words = str.slice(sepIndex + 1);\n if (_words.length < 6)\n throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(_words).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!_words.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };\n}\nexport const bech32 = genBech32('bech32');\nexport const bech32m = genBech32('bech32m');\nexport const utf8 = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\nexport const hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n if (typeof s !== 'string' || s.length % 2)\n throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n return s.toLowerCase();\n}));\nconst CODERS = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;\nexport const bytesToString = (type, bytes) => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (!(bytes instanceof Uint8Array))\n throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\nexport const str = bytesToString;\nexport const stringToBytes = (type, str) => {\n if (!CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (typeof str !== 'string')\n throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\nexport const bytes = stringToBytes;\n","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = data.slice();\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n//# sourceMappingURL=utils.js.map","// prettier-ignore\nimport { wrapCipher, createView, setBigUint64, equalBytes, u32, u8, } from './utils.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { bytes as abytes } from './_assert.js';\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// TODO: remove multiplication, binary ops only\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n let t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n return box;\n})();\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// Rotate u32 by 8\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\nexport function expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n return xk;\n}\nexport function expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n encKey.fill(0);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction getDst(len, dst) {\n if (!dst)\n return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n return dst;\n}\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr(key, nonce) {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf, dst) {\n const xk = expandKeyLE(key);\n const n = nonce.slice();\n const out = ctrCounter(xk, n, buf, dst);\n xk.fill(0);\n n.fill(0);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`);\n }\n}\nfunction validateBlockEncrypt(plaintext, pcks5, dst) {\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\nfunction validatePCKS(data, pcks5) {\n if (!pcks5)\n return data;\n const len = data.length;\n if (!len)\n throw new Error(`aes/pcks5: empty ciphertext not allowed`);\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16)\n throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`);\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte)\n throw new Error(`aes/pcks5: wrong padding`);\n return out;\n}\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher({ blockSize: 16 }, function ecb(key, opts = {}) {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext, dst) => {\n abytes(plaintext);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext, dst) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc(key, iv, opts = {}) {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext, dst) => {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext, dst) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const n32 = u32(iv);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n});\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb(key, iv) {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src, isEncrypt, dst) {\n const xk = expandKeyLE(key);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n buf.fill(0);\n }\n xk.fill(0);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(fn, isLE, key, data, AAD) {\n const h = fn.create(key, data.length + (AAD?.length || 0));\n if (AAD)\n h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD)\n setBigUint64(view, 0, BigInt(AAD.length * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n return h.digest();\n}\n/**\n * GCM: Galois/Counter Mode.\n * Good, modern version of CTR, parallel, with MAC.\n * Be careful: MACs can be forged.\n */\nexport const gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm(key, nonce, AAD) {\n abytes(nonce);\n // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure.\n if (nonce.length === 0)\n throw new Error('aes/gcm: empty nonce');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n // Spec (NIST 800-38d) supports variable size nonce.\n // Not supported for now, but can be useful.\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter);\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt: (plaintext) => {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n out.set(tag, plaintext.length);\n xk.fill(0);\n return out;\n },\n decrypt: (ciphertext) => {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n if (!equalBytes(tag, passedTag))\n throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n authKey.fill(0);\n tagMask.fill(0);\n xk.fill(0);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const len = key.length;\n if (len !== 16 && len !== 24 && len !== 32)\n throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`);\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(len);\n const authKey = new Uint8Array(16);\n const n32 = u32(nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n xk.fill(0);\n return { authKey, encKey: expandKeyLE(encKey) };\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = tag.slice();\n block[15] |= 0x80; // Force highest bit\n return ctr32(encKey, true, block, input);\n }\n return {\n encrypt: (plaintext) => {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n encKey.fill(0);\n authKey.fill(0);\n return out;\n },\n decrypt: (ciphertext) => {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n encKey.fill(0);\n authKey.fill(0);\n if (!equalBytes(tag, expectedTag))\n throw new Error('invalid polyval tag');\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n return (a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array'));\n}\nfunction encryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16);\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n// Highly unsafe private functions for implementing new modes or ciphers based on AES\n// Can change at any time, no API guarantees\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n//# sourceMappingURL=aes.js.map","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { checkOpts, u32 } from './utils.js';\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport const sigma = sigma32_32.slice();\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (!output)\n output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length, k, sigma;\n if (l === 32) {\n k = key.slice();\n toClean.push(k);\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) {\n nonce = nonce.slice();\n toClean.push(nonce);\n }\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n while (toClean.length > 0)\n toClean.pop().fill(0);\n return output;\n };\n}\n//# sourceMappingURL=_arx.js.map","// prettier-ignore\nimport { wrapCipher, createView, equalBytes, setBigUint64, } from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(s, k, i, o32) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00;\n o32[oi++] = x01;\n o32[oi++] = x02;\n o32[oi++] = x03;\n o32[oi++] = x12;\n o32[oi++] = x13;\n o32[oi++] = x14;\n o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left)\n h.update(ZEROS16.subarray(left));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, data, AAD) {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n authKey.fill(0);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt: (plaintext, output) => {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n }\n else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n return output;\n },\n decrypt: (ciphertext, output) => {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n }\n else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));\n//# sourceMappingURL=chacha.js.map","import assert from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assert.hash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assert.exists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assert.exists(this);\n assert.bytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","import assert from './_assert.js';\nimport { toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash, ikm, salt) {\n assert.hash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = new Uint8Array([0]);\nconst EMPTY_BUFFER = new Uint8Array();\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nexport function expand(hash, prk, info, length = 32) {\n assert.hash(hash);\n assert.number(length);\n if (length > 255 * hash.outputLen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// pure.ts\nimport { schnorr } from \"@noble/curves/secp256k1\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\n\n// core.ts\nvar verifiedSymbol = Symbol(\"verified\");\nvar isRecord = (obj) => obj instanceof Object;\nfunction validateEvent(event) {\n if (!isRecord(event))\n return false;\n if (typeof event.kind !== \"number\")\n return false;\n if (typeof event.content !== \"string\")\n return false;\n if (typeof event.created_at !== \"number\")\n return false;\n if (typeof event.pubkey !== \"string\")\n return false;\n if (!event.pubkey.match(/^[a-f0-9]{64}$/))\n return false;\n if (!Array.isArray(event.tags))\n return false;\n for (let i2 = 0; i2 < event.tags.length; i2++) {\n let tag = event.tags[i2];\n if (!Array.isArray(tag))\n return false;\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] === \"object\")\n return false;\n }\n }\n return true;\n}\nfunction sortEvents(events) {\n return events.sort((a, b) => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at;\n }\n return a.id.localeCompare(b.id);\n });\n}\n\n// pure.ts\nimport { sha256 } from \"@noble/hashes/sha256\";\n\n// utils.ts\nvar utils_exports = {};\n__export(utils_exports, {\n Queue: () => Queue,\n QueueNode: () => QueueNode,\n binarySearch: () => binarySearch,\n insertEventIntoAscendingList: () => insertEventIntoAscendingList,\n insertEventIntoDescendingList: () => insertEventIntoDescendingList,\n normalizeURL: () => normalizeURL,\n utf8Decoder: () => utf8Decoder,\n utf8Encoder: () => utf8Encoder\n});\nvar utf8Decoder = new TextDecoder(\"utf-8\");\nvar utf8Encoder = new TextEncoder();\nfunction normalizeURL(url) {\n if (url.indexOf(\"://\") === -1)\n url = \"wss://\" + url;\n let p = new URL(url);\n p.pathname = p.pathname.replace(/\\/+/g, \"/\");\n if (p.pathname.endsWith(\"/\"))\n p.pathname = p.pathname.slice(0, -1);\n if (p.port === \"80\" && p.protocol === \"ws:\" || p.port === \"443\" && p.protocol === \"wss:\")\n p.port = \"\";\n p.searchParams.sort();\n p.hash = \"\";\n return p.toString();\n}\nfunction insertEventIntoDescendingList(sortedArray, event) {\n const [idx, found] = binarySearch(sortedArray, (b) => {\n if (event.id === b.id)\n return 0;\n if (event.created_at === b.created_at)\n return -1;\n return b.created_at - event.created_at;\n });\n if (!found) {\n sortedArray.splice(idx, 0, event);\n }\n return sortedArray;\n}\nfunction insertEventIntoAscendingList(sortedArray, event) {\n const [idx, found] = binarySearch(sortedArray, (b) => {\n if (event.id === b.id)\n return 0;\n if (event.created_at === b.created_at)\n return -1;\n return event.created_at - b.created_at;\n });\n if (!found) {\n sortedArray.splice(idx, 0, event);\n }\n return sortedArray;\n}\nfunction binarySearch(arr, compare) {\n let start = 0;\n let end = arr.length - 1;\n while (start <= end) {\n const mid = Math.floor((start + end) / 2);\n const cmp = compare(arr[mid]);\n if (cmp === 0) {\n return [mid, true];\n }\n if (cmp < 0) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n return [start, false];\n}\nvar QueueNode = class {\n value;\n next = null;\n prev = null;\n constructor(message) {\n this.value = message;\n }\n};\nvar Queue = class {\n first;\n last;\n constructor() {\n this.first = null;\n this.last = null;\n }\n enqueue(value) {\n const newNode = new QueueNode(value);\n if (!this.last) {\n this.first = newNode;\n this.last = newNode;\n } else if (this.last === this.first) {\n this.last = newNode;\n this.last.prev = this.first;\n this.first.next = newNode;\n } else {\n newNode.prev = this.last;\n this.last.next = newNode;\n this.last = newNode;\n }\n return true;\n }\n dequeue() {\n if (!this.first)\n return null;\n if (this.first === this.last) {\n const target2 = this.first;\n this.first = null;\n this.last = null;\n return target2.value;\n }\n const target = this.first;\n this.first = target.next;\n return target.value;\n }\n};\n\n// pure.ts\nvar JS = class {\n generateSecretKey() {\n return schnorr.utils.randomPrivateKey();\n }\n getPublicKey(secretKey) {\n return bytesToHex(schnorr.getPublicKey(secretKey));\n }\n finalizeEvent(t, secretKey) {\n const event = t;\n event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey));\n event.id = getEventHash(event);\n event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey));\n event[verifiedSymbol] = true;\n return event;\n }\n verifyEvent(event) {\n if (typeof event[verifiedSymbol] === \"boolean\")\n return event[verifiedSymbol];\n const hash = getEventHash(event);\n if (hash !== event.id) {\n event[verifiedSymbol] = false;\n return false;\n }\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey);\n event[verifiedSymbol] = valid;\n return valid;\n } catch (err) {\n event[verifiedSymbol] = false;\n return false;\n }\n }\n};\nfunction serializeEvent(evt) {\n if (!validateEvent(evt))\n throw new Error(\"can't serialize event with wrong or missing properties\");\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]);\n}\nfunction getEventHash(event) {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)));\n return bytesToHex(eventHash);\n}\nvar i = new JS();\nvar generateSecretKey = i.generateSecretKey;\nvar getPublicKey = i.getPublicKey;\nvar finalizeEvent = i.finalizeEvent;\nvar verifyEvent = i.verifyEvent;\n\n// kinds.ts\nvar kinds_exports = {};\n__export(kinds_exports, {\n Application: () => Application,\n BadgeAward: () => BadgeAward,\n BadgeDefinition: () => BadgeDefinition,\n BlockedRelaysList: () => BlockedRelaysList,\n BookmarkList: () => BookmarkList,\n Bookmarksets: () => Bookmarksets,\n Calendar: () => Calendar,\n CalendarEventRSVP: () => CalendarEventRSVP,\n ChannelCreation: () => ChannelCreation,\n ChannelHideMessage: () => ChannelHideMessage,\n ChannelMessage: () => ChannelMessage,\n ChannelMetadata: () => ChannelMetadata,\n ChannelMuteUser: () => ChannelMuteUser,\n ClassifiedListing: () => ClassifiedListing,\n ClientAuth: () => ClientAuth,\n CommunitiesList: () => CommunitiesList,\n CommunityDefinition: () => CommunityDefinition,\n CommunityPostApproval: () => CommunityPostApproval,\n Contacts: () => Contacts,\n CreateOrUpdateProduct: () => CreateOrUpdateProduct,\n CreateOrUpdateStall: () => CreateOrUpdateStall,\n Curationsets: () => Curationsets,\n Date: () => Date2,\n DirectMessageRelaysList: () => DirectMessageRelaysList,\n DraftClassifiedListing: () => DraftClassifiedListing,\n DraftLong: () => DraftLong,\n Emojisets: () => Emojisets,\n EncryptedDirectMessage: () => EncryptedDirectMessage,\n EventDeletion: () => EventDeletion,\n FileMetadata: () => FileMetadata,\n FileServerPreference: () => FileServerPreference,\n Followsets: () => Followsets,\n GenericRepost: () => GenericRepost,\n Genericlists: () => Genericlists,\n GiftWrap: () => GiftWrap,\n HTTPAuth: () => HTTPAuth,\n Handlerinformation: () => Handlerinformation,\n Handlerrecommendation: () => Handlerrecommendation,\n Highlights: () => Highlights,\n InterestsList: () => InterestsList,\n Interestsets: () => Interestsets,\n JobFeedback: () => JobFeedback,\n JobRequest: () => JobRequest,\n JobResult: () => JobResult,\n Label: () => Label,\n LightningPubRPC: () => LightningPubRPC,\n LiveChatMessage: () => LiveChatMessage,\n LiveEvent: () => LiveEvent,\n LongFormArticle: () => LongFormArticle,\n Metadata: () => Metadata,\n Mutelist: () => Mutelist,\n NWCWalletInfo: () => NWCWalletInfo,\n NWCWalletRequest: () => NWCWalletRequest,\n NWCWalletResponse: () => NWCWalletResponse,\n NostrConnect: () => NostrConnect,\n OpenTimestamps: () => OpenTimestamps,\n Pinlist: () => Pinlist,\n PrivateDirectMessage: () => PrivateDirectMessage,\n ProblemTracker: () => ProblemTracker,\n ProfileBadges: () => ProfileBadges,\n PublicChatsList: () => PublicChatsList,\n Reaction: () => Reaction,\n RecommendRelay: () => RecommendRelay,\n RelayList: () => RelayList,\n Relaysets: () => Relaysets,\n Report: () => Report,\n Reporting: () => Reporting,\n Repost: () => Repost,\n Seal: () => Seal,\n SearchRelaysList: () => SearchRelaysList,\n ShortTextNote: () => ShortTextNote,\n Time: () => Time,\n UserEmojiList: () => UserEmojiList,\n UserStatuses: () => UserStatuses,\n Zap: () => Zap,\n ZapGoal: () => ZapGoal,\n ZapRequest: () => ZapRequest,\n classifyKind: () => classifyKind,\n isEphemeralKind: () => isEphemeralKind,\n isKind: () => isKind,\n isParameterizedReplaceableKind: () => isParameterizedReplaceableKind,\n isRegularKind: () => isRegularKind,\n isReplaceableKind: () => isReplaceableKind\n});\nfunction isRegularKind(kind) {\n return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind);\n}\nfunction isReplaceableKind(kind) {\n return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4;\n}\nfunction isEphemeralKind(kind) {\n return 2e4 <= kind && kind < 3e4;\n}\nfunction isParameterizedReplaceableKind(kind) {\n return 3e4 <= kind && kind < 4e4;\n}\nfunction classifyKind(kind) {\n if (isRegularKind(kind))\n return \"regular\";\n if (isReplaceableKind(kind))\n return \"replaceable\";\n if (isEphemeralKind(kind))\n return \"ephemeral\";\n if (isParameterizedReplaceableKind(kind))\n return \"parameterized\";\n return \"unknown\";\n}\nfunction isKind(event, kind) {\n const kindAsArray = kind instanceof Array ? kind : [kind];\n return validateEvent(event) && kindAsArray.includes(event.kind) || false;\n}\nvar Metadata = 0;\nvar ShortTextNote = 1;\nvar RecommendRelay = 2;\nvar Contacts = 3;\nvar EncryptedDirectMessage = 4;\nvar EventDeletion = 5;\nvar Repost = 6;\nvar Reaction = 7;\nvar BadgeAward = 8;\nvar Seal = 13;\nvar PrivateDirectMessage = 14;\nvar GenericRepost = 16;\nvar ChannelCreation = 40;\nvar ChannelMetadata = 41;\nvar ChannelMessage = 42;\nvar ChannelHideMessage = 43;\nvar ChannelMuteUser = 44;\nvar OpenTimestamps = 1040;\nvar GiftWrap = 1059;\nvar FileMetadata = 1063;\nvar LiveChatMessage = 1311;\nvar ProblemTracker = 1971;\nvar Report = 1984;\nvar Reporting = 1984;\nvar Label = 1985;\nvar CommunityPostApproval = 4550;\nvar JobRequest = 5999;\nvar JobResult = 6999;\nvar JobFeedback = 7e3;\nvar ZapGoal = 9041;\nvar ZapRequest = 9734;\nvar Zap = 9735;\nvar Highlights = 9802;\nvar Mutelist = 1e4;\nvar Pinlist = 10001;\nvar RelayList = 10002;\nvar BookmarkList = 10003;\nvar CommunitiesList = 10004;\nvar PublicChatsList = 10005;\nvar BlockedRelaysList = 10006;\nvar SearchRelaysList = 10007;\nvar InterestsList = 10015;\nvar UserEmojiList = 10030;\nvar DirectMessageRelaysList = 10050;\nvar FileServerPreference = 10096;\nvar NWCWalletInfo = 13194;\nvar LightningPubRPC = 21e3;\nvar ClientAuth = 22242;\nvar NWCWalletRequest = 23194;\nvar NWCWalletResponse = 23195;\nvar NostrConnect = 24133;\nvar HTTPAuth = 27235;\nvar Followsets = 3e4;\nvar Genericlists = 30001;\nvar Relaysets = 30002;\nvar Bookmarksets = 30003;\nvar Curationsets = 30004;\nvar ProfileBadges = 30008;\nvar BadgeDefinition = 30009;\nvar Interestsets = 30015;\nvar CreateOrUpdateStall = 30017;\nvar CreateOrUpdateProduct = 30018;\nvar LongFormArticle = 30023;\nvar DraftLong = 30024;\nvar Emojisets = 30030;\nvar Application = 30078;\nvar LiveEvent = 30311;\nvar UserStatuses = 30315;\nvar ClassifiedListing = 30402;\nvar DraftClassifiedListing = 30403;\nvar Date2 = 31922;\nvar Time = 31923;\nvar Calendar = 31924;\nvar CalendarEventRSVP = 31925;\nvar Handlerrecommendation = 31989;\nvar Handlerinformation = 31990;\nvar CommunityDefinition = 34550;\n\n// filter.ts\nfunction matchFilter(filter, event) {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false;\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false;\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false;\n }\n for (let f in filter) {\n if (f[0] === \"#\") {\n let tagName = f.slice(1);\n let values = filter[`#${tagName}`];\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1))\n return false;\n }\n }\n if (filter.since && event.created_at < filter.since)\n return false;\n if (filter.until && event.created_at > filter.until)\n return false;\n return true;\n}\nfunction matchFilters(filters, event) {\n for (let i2 = 0; i2 < filters.length; i2++) {\n if (matchFilter(filters[i2], event)) {\n return true;\n }\n }\n return false;\n}\nfunction mergeFilters(...filters) {\n let result = {};\n for (let i2 = 0; i2 < filters.length; i2++) {\n let filter = filters[i2];\n Object.entries(filter).forEach(([property, values]) => {\n if (property === \"kinds\" || property === \"ids\" || property === \"authors\" || property[0] === \"#\") {\n result[property] = result[property] || [];\n for (let v = 0; v < values.length; v++) {\n let value = values[v];\n if (!result[property].includes(value))\n result[property].push(value);\n }\n }\n });\n if (filter.limit && (!result.limit || filter.limit > result.limit))\n result.limit = filter.limit;\n if (filter.until && (!result.until || filter.until > result.until))\n result.until = filter.until;\n if (filter.since && (!result.since || filter.since < result.since))\n result.since = filter.since;\n }\n return result;\n}\nfunction getFilterLimit(filter) {\n if (filter.ids && !filter.ids.length)\n return 0;\n if (filter.kinds && !filter.kinds.length)\n return 0;\n if (filter.authors && !filter.authors.length)\n return 0;\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === \"#\" && Array.isArray(value) && !value.length)\n return 0;\n }\n return Math.min(\n Math.max(0, filter.limit ?? Infinity),\n filter.ids?.length ?? Infinity,\n filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity,\n filter.authors?.length && filter.kinds?.every((kind) => isParameterizedReplaceableKind(kind)) && filter[\"#d\"]?.length ? filter.authors.length * filter.kinds.length * filter[\"#d\"].length : Infinity\n );\n}\n\n// fakejson.ts\nvar fakejson_exports = {};\n__export(fakejson_exports, {\n getHex64: () => getHex64,\n getInt: () => getInt,\n getSubscriptionId: () => getSubscriptionId,\n matchEventId: () => matchEventId,\n matchEventKind: () => matchEventKind,\n matchEventPubkey: () => matchEventPubkey\n});\nfunction getHex64(json, field) {\n let len = field.length + 3;\n let idx = json.indexOf(`\"${field}\":`) + len;\n let s = json.slice(idx).indexOf(`\"`) + idx + 1;\n return json.slice(s, s + 64);\n}\nfunction getInt(json, field) {\n let len = field.length;\n let idx = json.indexOf(`\"${field}\":`) + len + 3;\n let sliced = json.slice(idx);\n let end = Math.min(sliced.indexOf(\",\"), sliced.indexOf(\"}\"));\n return parseInt(sliced.slice(0, end), 10);\n}\nfunction getSubscriptionId(json) {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`);\n if (idx === -1)\n return null;\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`);\n if (pstart === -1)\n return null;\n let start = idx + 7 + 1 + pstart;\n let pend = json.slice(start + 1, 80).indexOf(`\"`);\n if (pend === -1)\n return null;\n let end = start + 1 + pend;\n return json.slice(start + 1, end);\n}\nfunction matchEventId(json, id) {\n return id === getHex64(json, \"id\");\n}\nfunction matchEventPubkey(json, pubkey) {\n return pubkey === getHex64(json, \"pubkey\");\n}\nfunction matchEventKind(json, kind) {\n return kind === getInt(json, \"kind\");\n}\n\n// nip42.ts\nvar nip42_exports = {};\n__export(nip42_exports, {\n makeAuthEvent: () => makeAuthEvent\n});\nfunction makeAuthEvent(relayURL, challenge) {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1e3),\n tags: [\n [\"relay\", relayURL],\n [\"challenge\", challenge]\n ],\n content: \"\"\n };\n}\n\n// helpers.ts\nasync function yieldThread() {\n return new Promise((resolve) => {\n const ch = new MessageChannel();\n const handler = () => {\n ch.port1.removeEventListener(\"message\", handler);\n resolve();\n };\n ch.port1.addEventListener(\"message\", handler);\n ch.port2.postMessage(0);\n ch.port1.start();\n });\n}\nvar alwaysTrue = (t) => {\n t[verifiedSymbol] = true;\n return true;\n};\n\n// abstract-relay.ts\nvar AbstractRelay = class {\n url;\n _connected = false;\n onclose = null;\n onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`);\n _onauth = null;\n baseEoseTimeout = 4400;\n connectionTimeout = 4400;\n publishTimeout = 4400;\n openSubs = /* @__PURE__ */ new Map();\n connectionTimeoutHandle;\n connectionPromise;\n openCountRequests = /* @__PURE__ */ new Map();\n openEventPublishes = /* @__PURE__ */ new Map();\n ws;\n incomingMessageQueue = new Queue();\n queueRunning = false;\n challenge;\n serial = 0;\n verifyEvent;\n _WebSocket;\n constructor(url, opts) {\n this.url = normalizeURL(url);\n this.verifyEvent = opts.verifyEvent;\n this._WebSocket = opts.websocketImplementation || WebSocket;\n }\n static async connect(url, opts) {\n const relay = new AbstractRelay(url, opts);\n await relay.connect();\n return relay;\n }\n closeAllSubscriptions(reason) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason);\n }\n this.openSubs.clear();\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason));\n }\n this.openEventPublishes.clear();\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason));\n }\n this.openCountRequests.clear();\n }\n get connected() {\n return this._connected;\n }\n async connect() {\n if (this.connectionPromise)\n return this.connectionPromise;\n this.challenge = void 0;\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject(\"connection timed out\");\n this.connectionPromise = void 0;\n this.onclose?.();\n this.closeAllSubscriptions(\"relay connection timed out\");\n }, this.connectionTimeout);\n try {\n this.ws = new this._WebSocket(this.url);\n } catch (err) {\n reject(err);\n return;\n }\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle);\n this._connected = true;\n resolve();\n };\n this.ws.onerror = (ev) => {\n reject(ev.message || \"websocket error\");\n if (this._connected) {\n this._connected = false;\n this.connectionPromise = void 0;\n this.onclose?.();\n this.closeAllSubscriptions(\"relay connection errored\");\n }\n };\n this.ws.onclose = async () => {\n if (this._connected) {\n this._connected = false;\n this.connectionPromise = void 0;\n this.onclose?.();\n this.closeAllSubscriptions(\"relay connection closed\");\n }\n };\n this.ws.onmessage = this._onmessage.bind(this);\n });\n return this.connectionPromise;\n }\n async runQueue() {\n this.queueRunning = true;\n while (true) {\n if (false === this.handleNext()) {\n break;\n }\n await yieldThread();\n }\n this.queueRunning = false;\n }\n handleNext() {\n const json = this.incomingMessageQueue.dequeue();\n if (!json) {\n return false;\n }\n const subid = getSubscriptionId(json);\n if (subid) {\n const so = this.openSubs.get(subid);\n if (!so) {\n return;\n }\n const id = getHex64(json, \"id\");\n const alreadyHave = so.alreadyHaveEvent?.(id);\n so.receivedEvent?.(this, id);\n if (alreadyHave) {\n return;\n }\n }\n try {\n let data = JSON.parse(json);\n switch (data[0]) {\n case \"EVENT\": {\n const so = this.openSubs.get(data[1]);\n const event = data[2];\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event);\n }\n return;\n }\n case \"COUNT\": {\n const id = data[1];\n const payload = data[2];\n const cr = this.openCountRequests.get(id);\n if (cr) {\n cr.resolve(payload.count);\n this.openCountRequests.delete(id);\n }\n return;\n }\n case \"EOSE\": {\n const so = this.openSubs.get(data[1]);\n if (!so)\n return;\n so.receivedEose();\n return;\n }\n case \"OK\": {\n const id = data[1];\n const ok = data[2];\n const reason = data[3];\n const ep = this.openEventPublishes.get(id);\n if (ep) {\n if (ok)\n ep.resolve(reason);\n else\n ep.reject(new Error(reason));\n this.openEventPublishes.delete(id);\n }\n return;\n }\n case \"CLOSED\": {\n const id = data[1];\n const so = this.openSubs.get(id);\n if (!so)\n return;\n so.closed = true;\n so.close(data[2]);\n return;\n }\n case \"NOTICE\":\n this.onnotice(data[1]);\n return;\n case \"AUTH\": {\n this.challenge = data[1];\n this._onauth?.(data[1]);\n return;\n }\n }\n } catch (err) {\n return;\n }\n }\n async send(message) {\n if (!this.connectionPromise)\n throw new Error(\"sending on closed connection\");\n this.connectionPromise.then(() => {\n this.ws?.send(message);\n });\n }\n async auth(signAuthEvent) {\n if (!this.challenge)\n throw new Error(\"can't perform auth, no challenge was received\");\n const evt = await signAuthEvent(makeAuthEvent(this.url, this.challenge));\n const ret = new Promise((resolve, reject) => {\n this.openEventPublishes.set(evt.id, { resolve, reject });\n });\n this.send('[\"AUTH\",' + JSON.stringify(evt) + \"]\");\n return ret;\n }\n async publish(event) {\n const ret = new Promise((resolve, reject) => {\n this.openEventPublishes.set(event.id, { resolve, reject });\n });\n this.send('[\"EVENT\",' + JSON.stringify(event) + \"]\");\n setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id);\n if (ep) {\n ep.reject(new Error(\"publish timed out\"));\n this.openEventPublishes.delete(event.id);\n }\n }, this.publishTimeout);\n return ret;\n }\n async count(filters, params) {\n this.serial++;\n const id = params?.id || \"count:\" + this.serial;\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject });\n });\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1));\n return ret;\n }\n subscribe(filters, params) {\n const subscription = this.prepareSubscription(filters, params);\n subscription.fire();\n return subscription;\n }\n prepareSubscription(filters, params) {\n this.serial++;\n const id = params.id || \"sub:\" + this.serial;\n const subscription = new Subscription(this, id, filters, params);\n this.openSubs.set(id, subscription);\n return subscription;\n }\n close() {\n this.closeAllSubscriptions(\"relay connection closed by us\");\n this._connected = false;\n this.ws?.close();\n }\n _onmessage(ev) {\n this.incomingMessageQueue.enqueue(ev.data);\n if (!this.queueRunning) {\n this.runQueue();\n }\n }\n};\nvar Subscription = class {\n relay;\n id;\n closed = false;\n eosed = false;\n filters;\n alreadyHaveEvent;\n receivedEvent;\n onevent;\n oneose;\n onclose;\n eoseTimeout;\n eoseTimeoutHandle;\n constructor(relay, id, filters, params) {\n this.relay = relay;\n this.filters = filters;\n this.id = id;\n this.alreadyHaveEvent = params.alreadyHaveEvent;\n this.receivedEvent = params.receivedEvent;\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout;\n this.oneose = params.oneose;\n this.onclose = params.onclose;\n this.onevent = params.onevent || ((event) => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event\n );\n });\n }\n fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1));\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout);\n }\n receivedEose() {\n if (this.eosed)\n return;\n clearTimeout(this.eoseTimeoutHandle);\n this.eosed = true;\n this.oneose?.();\n }\n close(reason = \"closed by caller\") {\n if (!this.closed && this.relay.connected) {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + \"]\");\n this.closed = true;\n }\n this.relay.openSubs.delete(this.id);\n this.onclose?.(reason);\n }\n};\n\n// relay.ts\nvar _WebSocket;\ntry {\n _WebSocket = WebSocket;\n} catch {\n}\nvar Relay = class extends AbstractRelay {\n constructor(url) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket });\n }\n static async connect(url) {\n const relay = new Relay(url);\n await relay.connect();\n return relay;\n }\n};\n\n// abstract-pool.ts\nvar AbstractSimplePool = class {\n relays = /* @__PURE__ */ new Map();\n seenOn = /* @__PURE__ */ new Map();\n trackRelays = false;\n verifyEvent;\n trustedRelayURLs = /* @__PURE__ */ new Set();\n _WebSocket;\n constructor(opts) {\n this.verifyEvent = opts.verifyEvent;\n this._WebSocket = opts.websocketImplementation;\n }\n async ensureRelay(url, params) {\n url = normalizeURL(url);\n let relay = this.relays.get(url);\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket\n });\n if (params?.connectionTimeout)\n relay.connectionTimeout = params.connectionTimeout;\n this.relays.set(url, relay);\n }\n await relay.connect();\n return relay;\n }\n close(relays) {\n relays.map(normalizeURL).forEach((url) => {\n this.relays.get(url)?.close();\n });\n }\n subscribeMany(relays, filters, params) {\n return this.subscribeManyMap(Object.fromEntries(relays.map((url) => [url, filters])), params);\n }\n subscribeManyMap(requests, params) {\n if (this.trackRelays) {\n params.receivedEvent = (relay, id) => {\n let set = this.seenOn.get(id);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this.seenOn.set(id, set);\n }\n set.add(relay);\n };\n }\n const _knownIds = /* @__PURE__ */ new Set();\n const subs = [];\n const relaysLength = Object.keys(requests).length;\n const eosesReceived = [];\n let handleEose = (i2) => {\n eosesReceived[i2] = true;\n if (eosesReceived.filter((a) => a).length === relaysLength) {\n params.oneose?.();\n handleEose = () => {\n };\n }\n };\n const closesReceived = [];\n let handleClose = (i2, reason) => {\n handleEose(i2);\n closesReceived[i2] = reason;\n if (closesReceived.filter((a) => a).length === relaysLength) {\n params.onclose?.(closesReceived);\n handleClose = () => {\n };\n }\n };\n const localAlreadyHaveEventHandler = (id) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true;\n }\n const have = _knownIds.has(id);\n _knownIds.add(id);\n return have;\n };\n const allOpened = Promise.all(\n Object.entries(requests).map(async (req, i2, arr) => {\n if (arr.indexOf(req) !== i2) {\n handleClose(i2, \"duplicate url\");\n return;\n }\n let [url, filters] = req;\n url = normalizeURL(url);\n let relay;\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0\n });\n } catch (err) {\n handleClose(i2, err?.message || String(err));\n return;\n }\n let subscription = relay.subscribe(filters, {\n ...params,\n oneose: () => handleEose(i2),\n onclose: (reason) => handleClose(i2, reason),\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait\n });\n subs.push(subscription);\n })\n );\n return {\n async close() {\n await allOpened;\n subs.forEach((sub) => {\n sub.close();\n });\n }\n };\n }\n subscribeManyEose(relays, filters, params) {\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close();\n }\n });\n return subcloser;\n }\n async querySync(relays, filter, params) {\n return new Promise(async (resolve) => {\n const events = [];\n this.subscribeManyEose(relays, [filter], {\n ...params,\n onevent(event) {\n events.push(event);\n },\n onclose(_) {\n resolve(events);\n }\n });\n });\n }\n async get(relays, filter, params) {\n filter.limit = 1;\n const events = await this.querySync(relays, filter, params);\n events.sort((a, b) => b.created_at - a.created_at);\n return events[0] || null;\n }\n publish(relays, event) {\n return relays.map(normalizeURL).map(async (url, i2, arr) => {\n if (arr.indexOf(url) !== i2) {\n return Promise.reject(\"duplicate url\");\n }\n let r = await this.ensureRelay(url);\n return r.publish(event).then((reason) => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this.seenOn.set(event.id, set);\n }\n set.add(r);\n }\n return reason;\n });\n });\n }\n listConnectionStatus() {\n const map = /* @__PURE__ */ new Map();\n this.relays.forEach((relay, url) => map.set(url, relay.connected));\n return map;\n }\n destroy() {\n this.relays.forEach((conn) => conn.close());\n this.relays = /* @__PURE__ */ new Map();\n }\n};\n\n// pool.ts\nvar _WebSocket2;\ntry {\n _WebSocket2 = WebSocket;\n} catch {\n}\nvar SimplePool = class extends AbstractSimplePool {\n constructor() {\n super({ verifyEvent, websocketImplementation: _WebSocket2 });\n }\n};\n\n// nip19.ts\nvar nip19_exports = {};\n__export(nip19_exports, {\n BECH32_REGEX: () => BECH32_REGEX,\n Bech32MaxSize: () => Bech32MaxSize,\n NostrTypeGuard: () => NostrTypeGuard,\n decode: () => decode,\n encodeBytes: () => encodeBytes,\n naddrEncode: () => naddrEncode,\n neventEncode: () => neventEncode,\n noteEncode: () => noteEncode,\n nprofileEncode: () => nprofileEncode,\n npubEncode: () => npubEncode,\n nsecEncode: () => nsecEncode\n});\nimport { bytesToHex as bytesToHex2, concatBytes, hexToBytes } from \"@noble/hashes/utils\";\nimport { bech32 } from \"@scure/base\";\nvar NostrTypeGuard = {\n isNProfile: (value) => /^nprofile1[a-z\\d]+$/.test(value || \"\"),\n isNEvent: (value) => /^nevent1[a-z\\d]+$/.test(value || \"\"),\n isNAddr: (value) => /^naddr1[a-z\\d]+$/.test(value || \"\"),\n isNSec: (value) => /^nsec1[a-z\\d]{58}$/.test(value || \"\"),\n isNPub: (value) => /^npub1[a-z\\d]{58}$/.test(value || \"\"),\n isNote: (value) => /^note1[a-z\\d]+$/.test(value || \"\"),\n isNcryptsec: (value) => /^ncryptsec1[a-z\\d]+$/.test(value || \"\")\n};\nvar Bech32MaxSize = 5e3;\nvar BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;\nfunction integerToUint8Array(number) {\n const uint8Array = new Uint8Array(4);\n uint8Array[0] = number >> 24 & 255;\n uint8Array[1] = number >> 16 & 255;\n uint8Array[2] = number >> 8 & 255;\n uint8Array[3] = number & 255;\n return uint8Array;\n}\nfunction decode(nip19) {\n let { prefix, words } = bech32.decode(nip19, Bech32MaxSize);\n let data = new Uint8Array(bech32.fromWords(words));\n switch (prefix) {\n case \"nprofile\": {\n let tlv = parseTLV(data);\n if (!tlv[0]?.[0])\n throw new Error(\"missing TLV 0 for nprofile\");\n if (tlv[0][0].length !== 32)\n throw new Error(\"TLV 0 should be 32 bytes\");\n return {\n type: \"nprofile\",\n data: {\n pubkey: bytesToHex2(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : []\n }\n };\n }\n case \"nevent\": {\n let tlv = parseTLV(data);\n if (!tlv[0]?.[0])\n throw new Error(\"missing TLV 0 for nevent\");\n if (tlv[0][0].length !== 32)\n throw new Error(\"TLV 0 should be 32 bytes\");\n if (tlv[2] && tlv[2][0].length !== 32)\n throw new Error(\"TLV 2 should be 32 bytes\");\n if (tlv[3] && tlv[3][0].length !== 4)\n throw new Error(\"TLV 3 should be 4 bytes\");\n return {\n type: \"nevent\",\n data: {\n id: bytesToHex2(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0\n }\n };\n }\n case \"naddr\": {\n let tlv = parseTLV(data);\n if (!tlv[0]?.[0])\n throw new Error(\"missing TLV 0 for naddr\");\n if (!tlv[2]?.[0])\n throw new Error(\"missing TLV 2 for naddr\");\n if (tlv[2][0].length !== 32)\n throw new Error(\"TLV 2 should be 32 bytes\");\n if (!tlv[3]?.[0])\n throw new Error(\"missing TLV 3 for naddr\");\n if (tlv[3][0].length !== 4)\n throw new Error(\"TLV 3 should be 4 bytes\");\n return {\n type: \"naddr\",\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex2(tlv[2][0]),\n kind: parseInt(bytesToHex2(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : []\n }\n };\n }\n case \"nsec\":\n return { type: prefix, data };\n case \"npub\":\n case \"note\":\n return { type: prefix, data: bytesToHex2(data) };\n default:\n throw new Error(`unknown prefix ${prefix}`);\n }\n}\nfunction parseTLV(data) {\n let result = {};\n let rest = data;\n while (rest.length > 0) {\n let t = rest[0];\n let l = rest[1];\n let v = rest.slice(2, 2 + l);\n rest = rest.slice(2 + l);\n if (v.length < l)\n throw new Error(`not enough data to read on TLV ${t}`);\n result[t] = result[t] || [];\n result[t].push(v);\n }\n return result;\n}\nfunction nsecEncode(key) {\n return encodeBytes(\"nsec\", key);\n}\nfunction npubEncode(hex) {\n return encodeBytes(\"npub\", hexToBytes(hex));\n}\nfunction noteEncode(hex) {\n return encodeBytes(\"note\", hexToBytes(hex));\n}\nfunction encodeBech32(prefix, data) {\n let words = bech32.toWords(data);\n return bech32.encode(prefix, words, Bech32MaxSize);\n}\nfunction encodeBytes(prefix, bytes) {\n return encodeBech32(prefix, bytes);\n}\nfunction nprofileEncode(profile) {\n let data = encodeTLV({\n 0: [hexToBytes(profile.pubkey)],\n 1: (profile.relays || []).map((url) => utf8Encoder.encode(url))\n });\n return encodeBech32(\"nprofile\", data);\n}\nfunction neventEncode(event) {\n let kindArray;\n if (event.kind !== void 0) {\n kindArray = integerToUint8Array(event.kind);\n }\n let data = encodeTLV({\n 0: [hexToBytes(event.id)],\n 1: (event.relays || []).map((url) => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : []\n });\n return encodeBech32(\"nevent\", data);\n}\nfunction naddrEncode(addr) {\n let kind = new ArrayBuffer(4);\n new DataView(kind).setUint32(0, addr.kind, false);\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)),\n 2: [hexToBytes(addr.pubkey)],\n 3: [new Uint8Array(kind)]\n });\n return encodeBech32(\"naddr\", data);\n}\nfunction encodeTLV(tlv) {\n let entries = [];\n Object.entries(tlv).reverse().forEach(([t, vs]) => {\n vs.forEach((v) => {\n let entry = new Uint8Array(v.length + 2);\n entry.set([parseInt(t)], 0);\n entry.set([v.length], 1);\n entry.set(v, 2);\n entries.push(entry);\n });\n });\n return concatBytes(...entries);\n}\n\n// references.ts\nvar mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g;\nfunction parseReferences(evt) {\n let references = [];\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n try {\n let { type, data } = decode(ref[1]);\n switch (type) {\n case \"npub\": {\n references.push({\n text: ref[0],\n profile: { pubkey: data, relays: [] }\n });\n break;\n }\n case \"nprofile\": {\n references.push({\n text: ref[0],\n profile: data\n });\n break;\n }\n case \"note\": {\n references.push({\n text: ref[0],\n event: { id: data, relays: [] }\n });\n break;\n }\n case \"nevent\": {\n references.push({\n text: ref[0],\n event: data\n });\n break;\n }\n case \"naddr\": {\n references.push({\n text: ref[0],\n address: data\n });\n break;\n }\n }\n } catch (err) {\n }\n } else if (ref[3]) {\n let idx = parseInt(ref[3], 10);\n let tag = evt.tags[idx];\n if (!tag)\n continue;\n switch (tag[0]) {\n case \"p\": {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] }\n });\n break;\n }\n case \"e\": {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] }\n });\n break;\n }\n case \"a\": {\n try {\n let [kind, pubkey, identifier] = tag[1].split(\":\");\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : []\n }\n });\n } catch (err) {\n }\n break;\n }\n }\n }\n }\n return references;\n}\n\n// nip04.ts\nvar nip04_exports = {};\n__export(nip04_exports, {\n decrypt: () => decrypt,\n encrypt: () => encrypt\n});\nimport { bytesToHex as bytesToHex3, randomBytes } from \"@noble/hashes/utils\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { cbc } from \"@noble/ciphers/aes\";\nimport { base64 } from \"@scure/base\";\nasync function encrypt(secretKey, pubkey, text) {\n const privkey = secretKey instanceof Uint8Array ? bytesToHex3(secretKey) : secretKey;\n const key = secp256k1.getSharedSecret(privkey, \"02\" + pubkey);\n const normalizedKey = getNormalizedX(key);\n let iv = Uint8Array.from(randomBytes(16));\n let plaintext = utf8Encoder.encode(text);\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext);\n let ctb64 = base64.encode(new Uint8Array(ciphertext));\n let ivb64 = base64.encode(new Uint8Array(iv.buffer));\n return `${ctb64}?iv=${ivb64}`;\n}\nasync function decrypt(secretKey, pubkey, data) {\n const privkey = secretKey instanceof Uint8Array ? bytesToHex3(secretKey) : secretKey;\n let [ctb64, ivb64] = data.split(\"?iv=\");\n let key = secp256k1.getSharedSecret(privkey, \"02\" + pubkey);\n let normalizedKey = getNormalizedX(key);\n let iv = base64.decode(ivb64);\n let ciphertext = base64.decode(ctb64);\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext);\n return utf8Decoder.decode(plaintext);\n}\nfunction getNormalizedX(key) {\n return key.slice(1, 33);\n}\n\n// nip05.ts\nvar nip05_exports = {};\n__export(nip05_exports, {\n NIP05_REGEX: () => NIP05_REGEX,\n isNip05: () => isNip05,\n isValid: () => isValid,\n queryProfile: () => queryProfile,\n searchDomain: () => searchDomain,\n useFetchImplementation: () => useFetchImplementation\n});\nvar NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/;\nvar isNip05 = (value) => NIP05_REGEX.test(value || \"\");\nvar _fetch;\ntry {\n _fetch = fetch;\n} catch (_) {\n null;\n}\nfunction useFetchImplementation(fetchImplementation) {\n _fetch = fetchImplementation;\n}\nasync function searchDomain(domain, query = \"\") {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`;\n const res = await _fetch(url, { redirect: \"manual\" });\n if (res.status !== 200) {\n throw Error(\"Wrong response code\");\n }\n const json = await res.json();\n return json.names;\n } catch (_) {\n return {};\n }\n}\nasync function queryProfile(fullname) {\n const match = fullname.match(NIP05_REGEX);\n if (!match)\n return null;\n const [, name = \"_\", domain] = match;\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`;\n const res = await _fetch(url, { redirect: \"manual\" });\n if (res.status !== 200) {\n throw Error(\"Wrong response code\");\n }\n const json = await res.json();\n const pubkey = json.names[name];\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null;\n } catch (_e) {\n return null;\n }\n}\nasync function isValid(pubkey, nip05) {\n const res = await queryProfile(nip05);\n return res ? res.pubkey === pubkey : false;\n}\n\n// nip10.ts\nvar nip10_exports = {};\n__export(nip10_exports, {\n parse: () => parse\n});\nfunction parse(event) {\n const result = {\n reply: void 0,\n root: void 0,\n mentions: [],\n profiles: []\n };\n const eTags = [];\n for (const tag of event.tags) {\n if (tag[0] === \"e\" && tag[1]) {\n eTags.push(tag);\n }\n if (tag[0] === \"p\" && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : []\n });\n }\n }\n for (let eTagIndex = 0; eTagIndex < eTags.length; eTagIndex++) {\n const eTag = eTags[eTagIndex];\n const [_, eTagEventId, eTagRelayUrl, eTagMarker] = eTag;\n const eventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : []\n };\n const isFirstETag = eTagIndex === 0;\n const isLastETag = eTagIndex === eTags.length - 1;\n if (eTagMarker === \"root\") {\n result.root = eventPointer;\n continue;\n }\n if (eTagMarker === \"reply\") {\n result.reply = eventPointer;\n continue;\n }\n if (eTagMarker === \"mention\") {\n result.mentions.push(eventPointer);\n continue;\n }\n if (isFirstETag) {\n result.root = eventPointer;\n continue;\n }\n if (isLastETag) {\n result.reply = eventPointer;\n continue;\n }\n result.mentions.push(eventPointer);\n }\n return result;\n}\n\n// nip11.ts\nvar nip11_exports = {};\n__export(nip11_exports, {\n fetchRelayInformation: () => fetchRelayInformation,\n useFetchImplementation: () => useFetchImplementation2\n});\nvar _fetch2;\ntry {\n _fetch2 = fetch;\n} catch {\n}\nfunction useFetchImplementation2(fetchImplementation) {\n _fetch2 = fetchImplementation;\n}\nasync function fetchRelayInformation(url) {\n return await (await fetch(url.replace(\"ws://\", \"http://\").replace(\"wss://\", \"https://\"), {\n headers: { Accept: \"application/nostr+json\" }\n })).json();\n}\n\n// nip13.ts\nvar nip13_exports = {};\n__export(nip13_exports, {\n fastEventHash: () => fastEventHash,\n getPow: () => getPow,\n minePow: () => minePow\n});\nimport { bytesToHex as bytesToHex4 } from \"@noble/hashes/utils\";\nimport { sha256 as sha2562 } from \"@noble/hashes/sha256\";\nfunction getPow(hex) {\n let count = 0;\n for (let i2 = 0; i2 < 64; i2 += 8) {\n const nibble = parseInt(hex.substring(i2, i2 + 8), 16);\n if (nibble === 0) {\n count += 32;\n } else {\n count += Math.clz32(nibble);\n break;\n }\n }\n return count;\n}\nfunction minePow(unsigned, difficulty) {\n let count = 0;\n const event = unsigned;\n const tag = [\"nonce\", count.toString(), difficulty.toString()];\n event.tags.push(tag);\n while (true) {\n const now2 = Math.floor(new Date().getTime() / 1e3);\n if (now2 !== event.created_at) {\n count = 0;\n event.created_at = now2;\n }\n tag[1] = (++count).toString();\n event.id = fastEventHash(event);\n if (getPow(event.id) >= difficulty) {\n break;\n }\n }\n return event;\n}\nfunction fastEventHash(evt) {\n return bytesToHex4(\n sha2562(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])))\n );\n}\n\n// nip18.ts\nvar nip18_exports = {};\n__export(nip18_exports, {\n finishRepostEvent: () => finishRepostEvent,\n getRepostedEvent: () => getRepostedEvent,\n getRepostedEventPointer: () => getRepostedEventPointer\n});\nfunction finishRepostEvent(t, reposted, relayUrl, privateKey) {\n return finalizeEvent(\n {\n kind: Repost,\n tags: [...t.tags ?? [], [\"e\", reposted.id, relayUrl], [\"p\", reposted.pubkey]],\n content: t.content === \"\" ? \"\" : JSON.stringify(reposted),\n created_at: t.created_at\n },\n privateKey\n );\n}\nfunction getRepostedEventPointer(event) {\n if (event.kind !== Repost) {\n return void 0;\n }\n let lastETag;\n let lastPTag;\n for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) {\n const tag = event.tags[i2];\n if (tag.length >= 2) {\n if (tag[0] === \"e\" && lastETag === void 0) {\n lastETag = tag;\n } else if (tag[0] === \"p\" && lastPTag === void 0) {\n lastPTag = tag;\n }\n }\n }\n if (lastETag === void 0) {\n return void 0;\n }\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === \"string\"),\n author: lastPTag?.[1]\n };\n}\nfunction getRepostedEvent(event, { skipVerification } = {}) {\n const pointer = getRepostedEventPointer(event);\n if (pointer === void 0 || event.content === \"\") {\n return void 0;\n }\n let repostedEvent;\n try {\n repostedEvent = JSON.parse(event.content);\n } catch (error) {\n return void 0;\n }\n if (repostedEvent.id !== pointer.id) {\n return void 0;\n }\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return void 0;\n }\n return repostedEvent;\n}\n\n// nip21.ts\nvar nip21_exports = {};\n__export(nip21_exports, {\n NOSTR_URI_REGEX: () => NOSTR_URI_REGEX,\n parse: () => parse2,\n test: () => test\n});\nvar NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`);\nfunction test(value) {\n return typeof value === \"string\" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value);\n}\nfunction parse2(uri) {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));\n if (!match)\n throw new Error(`Invalid Nostr URI: ${uri}`);\n return {\n uri: match[0],\n value: match[1],\n decoded: decode(match[1])\n };\n}\n\n// nip25.ts\nvar nip25_exports = {};\n__export(nip25_exports, {\n finishReactionEvent: () => finishReactionEvent,\n getReactedEventPointer: () => getReactedEventPointer\n});\nfunction finishReactionEvent(t, reacted, privateKey) {\n const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === \"e\" || tag[0] === \"p\"));\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...t.tags ?? [], ...inheritedTags, [\"e\", reacted.id], [\"p\", reacted.pubkey]],\n content: t.content ?? \"+\"\n },\n privateKey\n );\n}\nfunction getReactedEventPointer(event) {\n if (event.kind !== Reaction) {\n return void 0;\n }\n let lastETag;\n let lastPTag;\n for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) {\n const tag = event.tags[i2];\n if (tag.length >= 2) {\n if (tag[0] === \"e\" && lastETag === void 0) {\n lastETag = tag;\n } else if (tag[0] === \"p\" && lastPTag === void 0) {\n lastPTag = tag;\n }\n }\n }\n if (lastETag === void 0 || lastPTag === void 0) {\n return void 0;\n }\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0),\n author: lastPTag[1]\n };\n}\n\n// nip27.ts\nvar nip27_exports = {};\n__export(nip27_exports, {\n matchAll: () => matchAll,\n regex: () => regex,\n replaceAll: () => replaceAll\n});\nvar regex = () => new RegExp(`\\\\b${NOSTR_URI_REGEX.source}\\\\b`, \"g\");\nfunction* matchAll(content) {\n const matches = content.matchAll(regex());\n for (const match of matches) {\n try {\n const [uri, value] = match;\n yield {\n uri,\n value,\n decoded: decode(value),\n start: match.index,\n end: match.index + uri.length\n };\n } catch (_e) {\n }\n }\n}\nfunction replaceAll(content, replacer) {\n return content.replaceAll(regex(), (uri, value) => {\n return replacer({\n uri,\n value,\n decoded: decode(value)\n });\n });\n}\n\n// nip28.ts\nvar nip28_exports = {};\n__export(nip28_exports, {\n channelCreateEvent: () => channelCreateEvent,\n channelHideMessageEvent: () => channelHideMessageEvent,\n channelMessageEvent: () => channelMessageEvent,\n channelMetadataEvent: () => channelMetadataEvent,\n channelMuteUserEvent: () => channelMuteUserEvent\n});\nvar channelCreateEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelMetadataEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelMetadata,\n tags: [[\"e\", t.channel_create_event_id], ...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelMessageEvent = (t, privateKey) => {\n const tags = [[\"e\", t.channel_create_event_id, t.relay_url, \"root\"]];\n if (t.reply_to_channel_message_event_id) {\n tags.push([\"e\", t.reply_to_channel_message_event_id, t.relay_url, \"reply\"]);\n }\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...t.tags ?? []],\n content: t.content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelHideMessageEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [[\"e\", t.channel_message_event_id], ...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelMuteUserEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [[\"p\", t.pubkey_to_mute], ...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\n\n// nip30.ts\nvar nip30_exports = {};\n__export(nip30_exports, {\n EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX,\n matchAll: () => matchAll2,\n regex: () => regex2,\n replaceAll: () => replaceAll2\n});\nvar EMOJI_SHORTCODE_REGEX = /:(\\w+):/;\nvar regex2 = () => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, \"g\");\nfunction* matchAll2(content) {\n const matches = content.matchAll(regex2());\n for (const match of matches) {\n try {\n const [shortcode, name] = match;\n yield {\n shortcode,\n name,\n start: match.index,\n end: match.index + shortcode.length\n };\n } catch (_e) {\n }\n }\n}\nfunction replaceAll2(content, replacer) {\n return content.replaceAll(regex2(), (shortcode, name) => {\n return replacer({\n shortcode,\n name\n });\n });\n}\n\n// nip39.ts\nvar nip39_exports = {};\n__export(nip39_exports, {\n useFetchImplementation: () => useFetchImplementation3,\n validateGithub: () => validateGithub\n});\nvar _fetch3;\ntry {\n _fetch3 = fetch;\n} catch {\n}\nfunction useFetchImplementation3(fetchImplementation) {\n _fetch3 = fetchImplementation;\n}\nasync function validateGithub(pubkey, username, proof) {\n try {\n let res = await (await _fetch3(`https://gist.github.com/${username}/${proof}/raw`)).text();\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`;\n } catch (_) {\n return false;\n }\n}\n\n// nip44.ts\nvar nip44_exports = {};\n__export(nip44_exports, {\n decrypt: () => decrypt2,\n encrypt: () => encrypt2,\n getConversationKey: () => getConversationKey,\n v2: () => v2\n});\nimport { chacha20 } from \"@noble/ciphers/chacha\";\nimport { equalBytes } from \"@noble/ciphers/utils\";\nimport { secp256k1 as secp256k12 } from \"@noble/curves/secp256k1\";\nimport { extract as hkdf_extract, expand as hkdf_expand } from \"@noble/hashes/hkdf\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 as sha2563 } from \"@noble/hashes/sha256\";\nimport { concatBytes as concatBytes2, randomBytes as randomBytes2 } from \"@noble/hashes/utils\";\nimport { base64 as base642 } from \"@scure/base\";\nvar minPlaintextSize = 1;\nvar maxPlaintextSize = 65535;\nfunction getConversationKey(privkeyA, pubkeyB) {\n const sharedX = secp256k12.getSharedSecret(privkeyA, \"02\" + pubkeyB).subarray(1, 33);\n return hkdf_extract(sha2563, sharedX, \"nip44-v2\");\n}\nfunction getMessageKeys(conversationKey, nonce) {\n const keys = hkdf_expand(sha2563, conversationKey, nonce, 76);\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76)\n };\n}\nfunction calcPaddedLen(len) {\n if (!Number.isSafeInteger(len) || len < 1)\n throw new Error(\"expected positive integer\");\n if (len <= 32)\n return 32;\n const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1;\n const chunk = nextPower <= 256 ? 32 : nextPower / 8;\n return chunk * (Math.floor((len - 1) / chunk) + 1);\n}\nfunction writeU16BE(num) {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error(\"invalid plaintext size: must be between 1 and 65535 bytes\");\n const arr = new Uint8Array(2);\n new DataView(arr.buffer).setUint16(0, num, false);\n return arr;\n}\nfunction pad(plaintext) {\n const unpadded = utf8Encoder.encode(plaintext);\n const unpaddedLen = unpadded.length;\n const prefix = writeU16BE(unpaddedLen);\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen);\n return concatBytes2(prefix, unpadded, suffix);\n}\nfunction unpad(padded) {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0);\n const unpadded = padded.subarray(2, 2 + unpaddedLen);\n if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen))\n throw new Error(\"invalid padding\");\n return utf8Decoder.decode(unpadded);\n}\nfunction hmacAad(key, message, aad) {\n if (aad.length !== 32)\n throw new Error(\"AAD associated data must be 32 bytes\");\n const combined = concatBytes2(aad, message);\n return hmac(sha2563, key, combined);\n}\nfunction decodePayload(payload) {\n if (typeof payload !== \"string\")\n throw new Error(\"payload must be a valid string\");\n const plen = payload.length;\n if (plen < 132 || plen > 87472)\n throw new Error(\"invalid payload length: \" + plen);\n if (payload[0] === \"#\")\n throw new Error(\"unknown encryption version\");\n let data;\n try {\n data = base642.decode(payload);\n } catch (error) {\n throw new Error(\"invalid base64: \" + error.message);\n }\n const dlen = data.length;\n if (dlen < 99 || dlen > 65603)\n throw new Error(\"invalid data length: \" + dlen);\n const vers = data[0];\n if (vers !== 2)\n throw new Error(\"unknown encryption version \" + vers);\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32)\n };\n}\nfunction encrypt2(plaintext, conversationKey, nonce = randomBytes2(32)) {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);\n const padded = pad(plaintext);\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded);\n const mac = hmacAad(hmac_key, ciphertext, nonce);\n return base642.encode(concatBytes2(new Uint8Array([2]), nonce, ciphertext, mac));\n}\nfunction decrypt2(payload, conversationKey) {\n const { nonce, ciphertext, mac } = decodePayload(payload);\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce);\n if (!equalBytes(calculatedMac, mac))\n throw new Error(\"invalid MAC\");\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext);\n return unpad(padded);\n}\nvar v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen\n },\n encrypt: encrypt2,\n decrypt: decrypt2\n};\n\n// nip47.ts\nvar nip47_exports = {};\n__export(nip47_exports, {\n makeNwcRequestEvent: () => makeNwcRequestEvent,\n parseConnectionString: () => parseConnectionString\n});\nfunction parseConnectionString(connectionString) {\n const { pathname, searchParams } = new URL(connectionString);\n const pubkey = pathname;\n const relay = searchParams.get(\"relay\");\n const secret = searchParams.get(\"secret\");\n if (!pubkey || !relay || !secret) {\n throw new Error(\"invalid connection string\");\n }\n return { pubkey, relay, secret };\n}\nasync function makeNwcRequestEvent(pubkey, secretKey, invoice) {\n const content = {\n method: \"pay_invoice\",\n params: {\n invoice\n }\n };\n const encryptedContent = await encrypt(secretKey, pubkey, JSON.stringify(content));\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1e3),\n content: encryptedContent,\n tags: [[\"p\", pubkey]]\n };\n return finalizeEvent(eventTemplate, secretKey);\n}\n\n// nip57.ts\nvar nip57_exports = {};\n__export(nip57_exports, {\n getZapEndpoint: () => getZapEndpoint,\n makeZapReceipt: () => makeZapReceipt,\n makeZapRequest: () => makeZapRequest,\n useFetchImplementation: () => useFetchImplementation4,\n validateZapRequest: () => validateZapRequest\n});\nimport { bech32 as bech322 } from \"@scure/base\";\nvar _fetch4;\ntry {\n _fetch4 = fetch;\n} catch {\n}\nfunction useFetchImplementation4(fetchImplementation) {\n _fetch4 = fetchImplementation;\n}\nasync function getZapEndpoint(metadata) {\n try {\n let lnurl = \"\";\n let { lud06, lud16 } = JSON.parse(metadata.content);\n if (lud06) {\n let { words } = bech322.decode(lud06, 1e3);\n let data = bech322.fromWords(words);\n lnurl = utf8Decoder.decode(data);\n } else if (lud16) {\n let [name, domain] = lud16.split(\"@\");\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString();\n } else {\n return null;\n }\n let res = await _fetch4(lnurl);\n let body = await res.json();\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback;\n }\n } catch (err) {\n }\n return null;\n}\nfunction makeZapRequest({\n profile,\n event,\n amount,\n relays,\n comment = \"\"\n}) {\n if (!amount)\n throw new Error(\"amount not given\");\n if (!profile)\n throw new Error(\"profile not given\");\n let zr = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1e3),\n content: comment,\n tags: [\n [\"p\", profile],\n [\"amount\", amount.toString()],\n [\"relays\", ...relays]\n ]\n };\n if (event) {\n zr.tags.push([\"e\", event]);\n }\n return zr;\n}\nfunction validateZapRequest(zapRequestString) {\n let zapRequest;\n try {\n zapRequest = JSON.parse(zapRequestString);\n } catch (err) {\n return \"Invalid zap request JSON.\";\n }\n if (!validateEvent(zapRequest))\n return \"Zap request is not a valid Nostr event.\";\n if (!verifyEvent(zapRequest))\n return \"Invalid signature on zap request.\";\n let p = zapRequest.tags.find(([t, v]) => t === \"p\" && v);\n if (!p)\n return \"Zap request doesn't have a 'p' tag.\";\n if (!p[1].match(/^[a-f0-9]{64}$/))\n return \"Zap request 'p' tag is not valid hex.\";\n let e = zapRequest.tags.find(([t, v]) => t === \"e\" && v);\n if (e && !e[1].match(/^[a-f0-9]{64}$/))\n return \"Zap request 'e' tag is not valid hex.\";\n let relays = zapRequest.tags.find(([t, v]) => t === \"relays\" && v);\n if (!relays)\n return \"Zap request doesn't have a 'relays' tag.\";\n return null;\n}\nfunction makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt\n}) {\n let zr = JSON.parse(zapRequest);\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === \"e\" || t === \"p\" || t === \"a\");\n let zap = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1e3),\n content: \"\",\n tags: [...tagsFromZapRequest, [\"P\", zr.pubkey], [\"bolt11\", bolt11], [\"description\", zapRequest]]\n };\n if (preimage) {\n zap.tags.push([\"preimage\", preimage]);\n }\n return zap;\n}\n\n// nip59.ts\nvar nip59_exports = {};\n__export(nip59_exports, {\n createRumor: () => createRumor,\n createSeal: () => createSeal,\n createWrap: () => createWrap,\n unwrapEvent: () => unwrapEvent,\n unwrapManyEvents: () => unwrapManyEvents,\n wrapEvent: () => wrapEvent,\n wrapManyEvents: () => wrapManyEvents\n});\nvar TWO_DAYS = 2 * 24 * 60 * 60;\nvar now = () => Math.round(Date.now() / 1e3);\nvar randomNow = () => Math.round(now() - Math.random() * TWO_DAYS);\nvar nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey);\nvar nip44Encrypt = (data, privateKey, publicKey) => encrypt2(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey));\nvar nip44Decrypt = (data, privateKey) => JSON.parse(decrypt2(data.content, nip44ConversationKey(privateKey, data.pubkey)));\nfunction createRumor(event, privateKey) {\n const rumor = {\n created_at: now(),\n content: \"\",\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey)\n };\n rumor.id = getEventHash(rumor);\n return rumor;\n}\nfunction createSeal(rumor, privateKey, recipientPublicKey) {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: []\n },\n privateKey\n );\n}\nfunction createWrap(seal, recipientPublicKey) {\n const randomKey = generateSecretKey();\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [[\"p\", recipientPublicKey]]\n },\n randomKey\n );\n}\nfunction wrapEvent(event, senderPrivateKey, recipientPublicKey) {\n const rumor = createRumor(event, senderPrivateKey);\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey);\n return createWrap(seal, recipientPublicKey);\n}\nfunction wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error(\"At least one recipient is required.\");\n }\n const senderPublicKey = getPublicKey(senderPrivateKey);\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)];\n recipientsPublicKeys.forEach((recipientPublicKey) => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey));\n });\n return wrappeds;\n}\nfunction unwrapEvent(wrap, recipientPrivateKey) {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey);\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey);\n}\nfunction unwrapManyEvents(wrappedEvents, recipientPrivateKey) {\n let unwrappedEvents = [];\n wrappedEvents.forEach((e) => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey));\n });\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at);\n return unwrappedEvents;\n}\n\n// nip98.ts\nvar nip98_exports = {};\n__export(nip98_exports, {\n getToken: () => getToken,\n hashPayload: () => hashPayload,\n unpackEventFromToken: () => unpackEventFromToken,\n validateEvent: () => validateEvent2,\n validateEventKind: () => validateEventKind,\n validateEventMethodTag: () => validateEventMethodTag,\n validateEventPayloadTag: () => validateEventPayloadTag,\n validateEventTimestamp: () => validateEventTimestamp,\n validateEventUrlTag: () => validateEventUrlTag,\n validateToken: () => validateToken\n});\nimport { sha256 as sha2564 } from \"@noble/hashes/sha256\";\nimport { bytesToHex as bytesToHex5 } from \"@noble/hashes/utils\";\nimport { base64 as base643 } from \"@scure/base\";\nvar _authorizationScheme = \"Nostr \";\nasync function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) {\n const event = {\n kind: HTTPAuth,\n tags: [\n [\"u\", loginUrl],\n [\"method\", httpMethod]\n ],\n created_at: Math.round(new Date().getTime() / 1e3),\n content: \"\"\n };\n if (payload) {\n event.tags.push([\"payload\", hashPayload(payload)]);\n }\n const signedEvent = await sign(event);\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : \"\";\n return authorizationScheme + base643.encode(utf8Encoder.encode(JSON.stringify(signedEvent)));\n}\nasync function validateToken(token, url, method) {\n const event = await unpackEventFromToken(token).catch((error) => {\n throw error;\n });\n const valid = await validateEvent2(event, url, method).catch((error) => {\n throw error;\n });\n return valid;\n}\nasync function unpackEventFromToken(token) {\n if (!token) {\n throw new Error(\"Missing token\");\n }\n token = token.replace(_authorizationScheme, \"\");\n const eventB64 = utf8Decoder.decode(base643.decode(token));\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith(\"{\")) {\n throw new Error(\"Invalid token\");\n }\n const event = JSON.parse(eventB64);\n return event;\n}\nfunction validateEventTimestamp(event) {\n if (!event.created_at) {\n return false;\n }\n return Math.round(new Date().getTime() / 1e3) - event.created_at < 60;\n}\nfunction validateEventKind(event) {\n return event.kind === HTTPAuth;\n}\nfunction validateEventUrlTag(event, url) {\n const urlTag = event.tags.find((t) => t[0] === \"u\");\n if (!urlTag) {\n return false;\n }\n return urlTag.length > 0 && urlTag[1] === url;\n}\nfunction validateEventMethodTag(event, method) {\n const methodTag = event.tags.find((t) => t[0] === \"method\");\n if (!methodTag) {\n return false;\n }\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase();\n}\nfunction hashPayload(payload) {\n const hash = sha2564(utf8Encoder.encode(JSON.stringify(payload)));\n return bytesToHex5(hash);\n}\nfunction validateEventPayloadTag(event, payload) {\n const payloadTag = event.tags.find((t) => t[0] === \"payload\");\n if (!payloadTag) {\n return false;\n }\n const payloadHash = hashPayload(payload);\n return payloadTag.length > 0 && payloadTag[1] === payloadHash;\n}\nasync function validateEvent2(event, url, method, body) {\n if (!verifyEvent(event)) {\n throw new Error(\"Invalid nostr event, signature invalid\");\n }\n if (!validateEventKind(event)) {\n throw new Error(\"Invalid nostr event, kind invalid\");\n }\n if (!validateEventTimestamp(event)) {\n throw new Error(\"Invalid nostr event, created_at timestamp invalid\");\n }\n if (!validateEventUrlTag(event, url)) {\n throw new Error(\"Invalid nostr event, url tag invalid\");\n }\n if (!validateEventMethodTag(event, method)) {\n throw new Error(\"Invalid nostr event, method tag invalid\");\n }\n if (Boolean(body) && typeof body === \"object\" && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error(\"Invalid nostr event, payload tag does not match request body hash\");\n }\n }\n return true;\n}\nexport {\n Relay,\n SimplePool,\n finalizeEvent,\n fakejson_exports as fj,\n generateSecretKey,\n getEventHash,\n getFilterLimit,\n getPublicKey,\n kinds_exports as kinds,\n matchFilter,\n matchFilters,\n mergeFilters,\n nip04_exports as nip04,\n nip05_exports as nip05,\n nip10_exports as nip10,\n nip11_exports as nip11,\n nip13_exports as nip13,\n nip18_exports as nip18,\n nip19_exports as nip19,\n nip21_exports as nip21,\n nip25_exports as nip25,\n nip27_exports as nip27,\n nip28_exports as nip28,\n nip30_exports as nip30,\n nip39_exports as nip39,\n nip42_exports as nip42,\n nip44_exports as nip44,\n nip47_exports as nip47,\n nip57_exports as nip57,\n nip59_exports as nip59,\n nip98_exports as nip98,\n parseReferences,\n serializeEvent,\n sortEvents,\n utils_exports as utils,\n validateEvent,\n verifiedSymbol,\n verifyEvent\n};\n","// src/components/card/card.styles.ts\nimport { css } from \"lit\";\nvar card_styles_default = css`\n :host {\n --border-color: var(--sl-color-neutral-200);\n --border-radius: var(--sl-border-radius-medium);\n --border-width: 1px;\n --padding: var(--sl-spacing-large);\n\n display: inline-block;\n }\n\n .card {\n display: flex;\n flex-direction: column;\n background-color: var(--sl-panel-background-color);\n box-shadow: var(--sl-shadow-x-small);\n border: solid var(--border-width) var(--border-color);\n border-radius: var(--border-radius);\n }\n\n .card__image {\n display: flex;\n border-top-left-radius: var(--border-radius);\n border-top-right-radius: var(--border-radius);\n margin: calc(-1 * var(--border-width));\n overflow: hidden;\n }\n\n .card__image::slotted(img) {\n display: block;\n width: 100%;\n }\n\n .card:not(.card--has-image) .card__image {\n display: none;\n }\n\n .card__header {\n display: block;\n border-bottom: solid var(--border-width) var(--border-color);\n padding: calc(var(--padding) / 2) var(--padding);\n }\n\n .card:not(.card--has-header) .card__header {\n display: none;\n }\n\n .card:not(.card--has-image) .card__header {\n border-top-left-radius: var(--border-radius);\n border-top-right-radius: var(--border-radius);\n }\n\n .card__body {\n display: block;\n padding: var(--padding);\n }\n\n .card--has-footer .card__footer {\n display: block;\n border-top: solid var(--border-width) var(--border-color);\n padding: var(--padding);\n }\n\n .card:not(.card--has-footer) .card__footer {\n display: none;\n }\n`;\n\nexport {\n card_styles_default\n};\n","// src/internal/slot.ts\nvar HasSlotController = class {\n constructor(host, ...slotNames) {\n this.slotNames = [];\n this.handleSlotChange = (event) => {\n const slot = event.target;\n if (this.slotNames.includes(\"[default]\") && !slot.name || slot.name && this.slotNames.includes(slot.name)) {\n this.host.requestUpdate();\n }\n };\n (this.host = host).addController(this);\n this.slotNames = slotNames;\n }\n hasDefaultSlot() {\n return [...this.host.childNodes].some((node) => {\n if (node.nodeType === node.TEXT_NODE && node.textContent.trim() !== \"\") {\n return true;\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n const el = node;\n const tagName = el.tagName.toLowerCase();\n if (tagName === \"sl-visually-hidden\") {\n return false;\n }\n if (!el.hasAttribute(\"slot\")) {\n return true;\n }\n }\n return false;\n });\n }\n hasNamedSlot(name) {\n return this.host.querySelector(`:scope > [slot=\"${name}\"]`) !== null;\n }\n test(slotName) {\n return slotName === \"[default]\" ? this.hasDefaultSlot() : this.hasNamedSlot(slotName);\n }\n hostConnected() {\n this.host.shadowRoot.addEventListener(\"slotchange\", this.handleSlotChange);\n }\n hostDisconnected() {\n this.host.shadowRoot.removeEventListener(\"slotchange\", this.handleSlotChange);\n }\n};\nfunction getTextContent(slot) {\n if (!slot) {\n return \"\";\n }\n const nodes = slot.assignedNodes({ flatten: true });\n let text = \"\";\n [...nodes].forEach((node) => {\n if (node.nodeType === Node.TEXT_NODE) {\n text += node.textContent;\n }\n });\n return text;\n}\n\nexport {\n HasSlotController,\n getTextContent\n};\n","// src/styles/component.styles.ts\nimport { css } from \"lit\";\nvar component_styles_default = css`\n :host {\n box-sizing: border-box;\n }\n\n :host *,\n :host *::before,\n :host *::after {\n box-sizing: inherit;\n }\n\n [hidden] {\n display: none !important;\n }\n`;\n\nexport {\n component_styles_default\n};\n","import {\n __decorateClass,\n __privateAdd,\n __privateGet,\n __privateSet,\n __spreadValues\n} from \"./chunk.B3BW2AY6.js\";\n\n// src/internal/shoelace-element.ts\nimport { LitElement } from \"lit\";\nimport { property } from \"lit/decorators.js\";\nvar _hasRecordedInitialProperties;\nvar ShoelaceElement = class extends LitElement {\n constructor() {\n super();\n __privateAdd(this, _hasRecordedInitialProperties, false);\n // Store the constructor value of all `static properties = {}`\n this.initialReflectedProperties = /* @__PURE__ */ new Map();\n Object.entries(this.constructor.dependencies).forEach(([name, component]) => {\n this.constructor.define(name, component);\n });\n }\n emit(name, options) {\n const event = new CustomEvent(name, __spreadValues({\n bubbles: true,\n cancelable: false,\n composed: true,\n detail: {}\n }, options));\n this.dispatchEvent(event);\n return event;\n }\n /* eslint-enable */\n static define(name, elementConstructor = this, options = {}) {\n const currentlyRegisteredConstructor = customElements.get(name);\n if (!currentlyRegisteredConstructor) {\n try {\n customElements.define(name, elementConstructor, options);\n } catch (_err) {\n customElements.define(name, class extends elementConstructor {\n }, options);\n }\n return;\n }\n let newVersion = \" (unknown version)\";\n let existingVersion = newVersion;\n if (\"version\" in elementConstructor && elementConstructor.version) {\n newVersion = \" v\" + elementConstructor.version;\n }\n if (\"version\" in currentlyRegisteredConstructor && currentlyRegisteredConstructor.version) {\n existingVersion = \" v\" + currentlyRegisteredConstructor.version;\n }\n if (newVersion && existingVersion && newVersion === existingVersion) {\n return;\n }\n console.warn(\n `Attempted to register <${name}>${newVersion}, but <${name}>${existingVersion} has already been registered.`\n );\n }\n attributeChangedCallback(name, oldValue, newValue) {\n if (!__privateGet(this, _hasRecordedInitialProperties)) {\n this.constructor.elementProperties.forEach(\n (obj, prop) => {\n if (obj.reflect && this[prop] != null) {\n this.initialReflectedProperties.set(prop, this[prop]);\n }\n }\n );\n __privateSet(this, _hasRecordedInitialProperties, true);\n }\n super.attributeChangedCallback(name, oldValue, newValue);\n }\n willUpdate(changedProperties) {\n super.willUpdate(changedProperties);\n this.initialReflectedProperties.forEach((value, prop) => {\n if (changedProperties.has(prop) && this[prop] == null) {\n this[prop] = value;\n }\n });\n }\n};\n_hasRecordedInitialProperties = new WeakMap();\n/* eslint-disable */\n// @ts-expect-error This is auto-injected at build time.\nShoelaceElement.version = \"2.18.0\";\nShoelaceElement.dependencies = {};\n__decorateClass([\n property()\n], ShoelaceElement.prototype, \"dir\", 2);\n__decorateClass([\n property()\n], ShoelaceElement.prototype, \"lang\", 2);\n\nexport {\n ShoelaceElement\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}export{i as Directive,t as PartType,e as directive};\n//# sourceMappingURL=directive.js.map\n","import{noChange as t}from\"../lit-html.js\";import{directive as s,Directive as i,PartType as r}from\"../directive.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const e=s(class extends i{constructor(t){if(super(t),t.type!==r.ATTRIBUTE||\"class\"!==t.name||t.strings?.length>2)throw Error(\"`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.\")}render(t){return\" \"+Object.keys(t).filter((s=>t[s])).join(\" \")+\" \"}update(s,[i]){if(void 0===this.st){this.st=new Set,void 0!==s.strings&&(this.nt=new Set(s.strings.join(\" \").split(/\\s/).filter((t=>\"\"!==t))));for(const t in i)i[t]&&!this.nt?.has(t)&&this.st.add(t);return this.render(i)}const r=s.element.classList;for(const t of this.st)t in i||(r.remove(t),this.st.delete(t));for(const t in i){const s=!!i[t];s===this.st.has(t)||this.nt?.has(t)||(s?(r.add(t),this.st.add(t)):(r.remove(t),this.st.delete(t)))}return t}});export{e as classMap};\n//# sourceMappingURL=class-map.js.map\n","import {\n card_styles_default\n} from \"./chunk.A5D6FTFY.js\";\nimport {\n HasSlotController\n} from \"./chunk.NYIIDP5N.js\";\nimport {\n component_styles_default\n} from \"./chunk.TUVJKY7S.js\";\nimport {\n ShoelaceElement\n} from \"./chunk.UYAO2JRR.js\";\n\n// src/components/card/card.component.ts\nimport { classMap } from \"lit/directives/class-map.js\";\nimport { html } from \"lit\";\nvar SlCard = class extends ShoelaceElement {\n constructor() {\n super(...arguments);\n this.hasSlotController = new HasSlotController(this, \"footer\", \"header\", \"image\");\n }\n render() {\n return html`\n \n \n \n \n \n
    \n `;\n }\n};\nSlCard.styles = [component_styles_default, card_styles_default];\n\nexport {\n SlCard\n};\n","import {\n SlCard\n} from \"./chunk.LJF3QW2H.js\";\n\n// src/components/card/card.ts\nvar card_default = SlCard;\nSlCard.define(\"sl-card\");\n\nexport {\n card_default\n};\n","// src/components/spinner/spinner.styles.ts\nimport { css } from \"lit\";\nvar spinner_styles_default = css`\n :host {\n --track-width: 2px;\n --track-color: rgb(128 128 128 / 25%);\n --indicator-color: var(--sl-color-primary-600);\n --speed: 2s;\n\n display: inline-flex;\n width: 1em;\n height: 1em;\n flex: none;\n }\n\n .spinner {\n flex: 1 1 auto;\n height: 100%;\n width: 100%;\n }\n\n .spinner__track,\n .spinner__indicator {\n fill: none;\n stroke-width: var(--track-width);\n r: calc(0.5em - var(--track-width) / 2);\n cx: 0.5em;\n cy: 0.5em;\n transform-origin: 50% 50%;\n }\n\n .spinner__track {\n stroke: var(--track-color);\n transform-origin: 0% 0%;\n }\n\n .spinner__indicator {\n stroke: var(--indicator-color);\n stroke-linecap: round;\n stroke-dasharray: 150% 75%;\n animation: spin var(--speed) linear infinite;\n }\n\n @keyframes spin {\n 0% {\n transform: rotate(0deg);\n stroke-dasharray: 0.05em, 3em;\n }\n\n 50% {\n transform: rotate(450deg);\n stroke-dasharray: 1.375em, 1.375em;\n }\n\n 100% {\n transform: rotate(1080deg);\n stroke-dasharray: 0.05em, 3em;\n }\n }\n`;\n\nexport {\n spinner_styles_default\n};\n","const connectedElements = new Set();\nconst translations = new Map();\nlet fallback;\nlet documentDirection = 'ltr';\nlet documentLanguage = 'en';\nconst isClient = (typeof MutationObserver !== \"undefined\" && typeof document !== \"undefined\" && typeof document.documentElement !== \"undefined\");\nif (isClient) {\n const documentElementObserver = new MutationObserver(update);\n documentDirection = document.documentElement.dir || 'ltr';\n documentLanguage = document.documentElement.lang || navigator.language;\n documentElementObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: ['dir', 'lang']\n });\n}\nexport function registerTranslation(...translation) {\n translation.map(t => {\n const code = t.$code.toLowerCase();\n if (translations.has(code)) {\n translations.set(code, Object.assign(Object.assign({}, translations.get(code)), t));\n }\n else {\n translations.set(code, t);\n }\n if (!fallback) {\n fallback = t;\n }\n });\n update();\n}\nexport function update() {\n if (isClient) {\n documentDirection = document.documentElement.dir || 'ltr';\n documentLanguage = document.documentElement.lang || navigator.language;\n }\n [...connectedElements.keys()].map((el) => {\n if (typeof el.requestUpdate === 'function') {\n el.requestUpdate();\n }\n });\n}\nexport class LocalizeController {\n constructor(host) {\n this.host = host;\n this.host.addController(this);\n }\n hostConnected() {\n connectedElements.add(this.host);\n }\n hostDisconnected() {\n connectedElements.delete(this.host);\n }\n dir() {\n return `${this.host.dir || documentDirection}`.toLowerCase();\n }\n lang() {\n return `${this.host.lang || documentLanguage}`.toLowerCase();\n }\n getTranslationData(lang) {\n var _a, _b;\n const locale = new Intl.Locale(lang.replace(/_/g, '-'));\n const language = locale === null || locale === void 0 ? void 0 : locale.language.toLowerCase();\n const region = (_b = (_a = locale === null || locale === void 0 ? void 0 : locale.region) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : '';\n const primary = translations.get(`${language}-${region}`);\n const secondary = translations.get(language);\n return { locale, language, region, primary, secondary };\n }\n exists(key, options) {\n var _a;\n const { primary, secondary } = this.getTranslationData((_a = options.lang) !== null && _a !== void 0 ? _a : this.lang());\n options = Object.assign({ includeFallback: false }, options);\n if ((primary && primary[key]) ||\n (secondary && secondary[key]) ||\n (options.includeFallback && fallback && fallback[key])) {\n return true;\n }\n return false;\n }\n term(key, ...args) {\n const { primary, secondary } = this.getTranslationData(this.lang());\n let term;\n if (primary && primary[key]) {\n term = primary[key];\n }\n else if (secondary && secondary[key]) {\n term = secondary[key];\n }\n else if (fallback && fallback[key]) {\n term = fallback[key];\n }\n else {\n console.error(`No translation found for: ${String(key)}`);\n return String(key);\n }\n if (typeof term === 'function') {\n return term(...args);\n }\n return term;\n }\n date(dateToFormat, options) {\n dateToFormat = new Date(dateToFormat);\n return new Intl.DateTimeFormat(this.lang(), options).format(dateToFormat);\n }\n number(numberToFormat, options) {\n numberToFormat = Number(numberToFormat);\n return isNaN(numberToFormat) ? '' : new Intl.NumberFormat(this.lang(), options).format(numberToFormat);\n }\n relativeTime(value, unit, options) {\n return new Intl.RelativeTimeFormat(this.lang(), options).format(value, unit);\n }\n}\n","// src/translations/en.ts\nimport { registerTranslation } from \"@shoelace-style/localize\";\nvar translation = {\n $code: \"en\",\n $name: \"English\",\n $dir: \"ltr\",\n carousel: \"Carousel\",\n clearEntry: \"Clear entry\",\n close: \"Close\",\n copied: \"Copied\",\n copy: \"Copy\",\n currentValue: \"Current value\",\n error: \"Error\",\n goToSlide: (slide, count) => `Go to slide ${slide} of ${count}`,\n hidePassword: \"Hide password\",\n loading: \"Loading\",\n nextSlide: \"Next slide\",\n numOptionsSelected: (num) => {\n if (num === 0)\n return \"No options selected\";\n if (num === 1)\n return \"1 option selected\";\n return `${num} options selected`;\n },\n previousSlide: \"Previous slide\",\n progress: \"Progress\",\n remove: \"Remove\",\n resize: \"Resize\",\n scrollToEnd: \"Scroll to end\",\n scrollToStart: \"Scroll to start\",\n selectAColorFromTheScreen: \"Select a color from the screen\",\n showPassword: \"Show password\",\n slideNum: (slide) => `Slide ${slide}`,\n toggleColorFormat: \"Toggle color format\"\n};\nregisterTranslation(translation);\nvar en_default = translation;\n\nexport {\n en_default\n};\n","import {\n en_default\n} from \"./chunk.MAS2SHYD.js\";\n\n// src/utilities/localize.ts\nimport { LocalizeController as DefaultLocalizationController, registerTranslation } from \"@shoelace-style/localize\";\nimport { registerTranslation as registerTranslation2 } from \"@shoelace-style/localize\";\nvar LocalizeController = class extends DefaultLocalizationController {\n};\nregisterTranslation(en_default);\n\nexport {\n LocalizeController,\n registerTranslation2 as registerTranslation\n};\n","import {\n spinner_styles_default\n} from \"./chunk.7DUCI5S4.js\";\nimport {\n LocalizeController\n} from \"./chunk.WLV3FVBR.js\";\nimport {\n component_styles_default\n} from \"./chunk.TUVJKY7S.js\";\nimport {\n ShoelaceElement\n} from \"./chunk.UYAO2JRR.js\";\n\n// src/components/spinner/spinner.component.ts\nimport { html } from \"lit\";\nvar SlSpinner = class extends ShoelaceElement {\n constructor() {\n super(...arguments);\n this.localize = new LocalizeController(this);\n }\n render() {\n return html`\n \n \n \n \n `;\n }\n};\nSlSpinner.styles = [component_styles_default, spinner_styles_default];\n\nexport {\n SlSpinner\n};\n","import {\n __spreadProps,\n __spreadValues\n} from \"./chunk.B3BW2AY6.js\";\n\n// src/internal/form.ts\nvar formCollections = /* @__PURE__ */ new WeakMap();\nvar reportValidityOverloads = /* @__PURE__ */ new WeakMap();\nvar checkValidityOverloads = /* @__PURE__ */ new WeakMap();\nvar userInteractedControls = /* @__PURE__ */ new WeakSet();\nvar interactions = /* @__PURE__ */ new WeakMap();\nvar FormControlController = class {\n constructor(host, options) {\n this.handleFormData = (event) => {\n const disabled = this.options.disabled(this.host);\n const name = this.options.name(this.host);\n const value = this.options.value(this.host);\n const isButton = this.host.tagName.toLowerCase() === \"sl-button\";\n if (this.host.isConnected && !disabled && !isButton && typeof name === \"string\" && name.length > 0 && typeof value !== \"undefined\") {\n if (Array.isArray(value)) {\n value.forEach((val) => {\n event.formData.append(name, val.toString());\n });\n } else {\n event.formData.append(name, value.toString());\n }\n }\n };\n this.handleFormSubmit = (event) => {\n var _a;\n const disabled = this.options.disabled(this.host);\n const reportValidity = this.options.reportValidity;\n if (this.form && !this.form.noValidate) {\n (_a = formCollections.get(this.form)) == null ? void 0 : _a.forEach((control) => {\n this.setUserInteracted(control, true);\n });\n }\n if (this.form && !this.form.noValidate && !disabled && !reportValidity(this.host)) {\n event.preventDefault();\n event.stopImmediatePropagation();\n }\n };\n this.handleFormReset = () => {\n this.options.setValue(this.host, this.options.defaultValue(this.host));\n this.setUserInteracted(this.host, false);\n interactions.set(this.host, []);\n };\n this.handleInteraction = (event) => {\n const emittedEvents = interactions.get(this.host);\n if (!emittedEvents.includes(event.type)) {\n emittedEvents.push(event.type);\n }\n if (emittedEvents.length === this.options.assumeInteractionOn.length) {\n this.setUserInteracted(this.host, true);\n }\n };\n this.checkFormValidity = () => {\n if (this.form && !this.form.noValidate) {\n const elements = this.form.querySelectorAll(\"*\");\n for (const element of elements) {\n if (typeof element.checkValidity === \"function\") {\n if (!element.checkValidity()) {\n return false;\n }\n }\n }\n }\n return true;\n };\n this.reportFormValidity = () => {\n if (this.form && !this.form.noValidate) {\n const elements = this.form.querySelectorAll(\"*\");\n for (const element of elements) {\n if (typeof element.reportValidity === \"function\") {\n if (!element.reportValidity()) {\n return false;\n }\n }\n }\n }\n return true;\n };\n (this.host = host).addController(this);\n this.options = __spreadValues({\n form: (input) => {\n const formId = input.form;\n if (formId) {\n const root = input.getRootNode();\n const form = root.querySelector(`#${formId}`);\n if (form) {\n return form;\n }\n }\n return input.closest(\"form\");\n },\n name: (input) => input.name,\n value: (input) => input.value,\n defaultValue: (input) => input.defaultValue,\n disabled: (input) => {\n var _a;\n return (_a = input.disabled) != null ? _a : false;\n },\n reportValidity: (input) => typeof input.reportValidity === \"function\" ? input.reportValidity() : true,\n checkValidity: (input) => typeof input.checkValidity === \"function\" ? input.checkValidity() : true,\n setValue: (input, value) => input.value = value,\n assumeInteractionOn: [\"sl-input\"]\n }, options);\n }\n hostConnected() {\n const form = this.options.form(this.host);\n if (form) {\n this.attachForm(form);\n }\n interactions.set(this.host, []);\n this.options.assumeInteractionOn.forEach((event) => {\n this.host.addEventListener(event, this.handleInteraction);\n });\n }\n hostDisconnected() {\n this.detachForm();\n interactions.delete(this.host);\n this.options.assumeInteractionOn.forEach((event) => {\n this.host.removeEventListener(event, this.handleInteraction);\n });\n }\n hostUpdated() {\n const form = this.options.form(this.host);\n if (!form) {\n this.detachForm();\n }\n if (form && this.form !== form) {\n this.detachForm();\n this.attachForm(form);\n }\n if (this.host.hasUpdated) {\n this.setValidity(this.host.validity.valid);\n }\n }\n attachForm(form) {\n if (form) {\n this.form = form;\n if (formCollections.has(this.form)) {\n formCollections.get(this.form).add(this.host);\n } else {\n formCollections.set(this.form, /* @__PURE__ */ new Set([this.host]));\n }\n this.form.addEventListener(\"formdata\", this.handleFormData);\n this.form.addEventListener(\"submit\", this.handleFormSubmit);\n this.form.addEventListener(\"reset\", this.handleFormReset);\n if (!reportValidityOverloads.has(this.form)) {\n reportValidityOverloads.set(this.form, this.form.reportValidity);\n this.form.reportValidity = () => this.reportFormValidity();\n }\n if (!checkValidityOverloads.has(this.form)) {\n checkValidityOverloads.set(this.form, this.form.checkValidity);\n this.form.checkValidity = () => this.checkFormValidity();\n }\n } else {\n this.form = void 0;\n }\n }\n detachForm() {\n if (!this.form)\n return;\n const formCollection = formCollections.get(this.form);\n if (!formCollection) {\n return;\n }\n formCollection.delete(this.host);\n if (formCollection.size <= 0) {\n this.form.removeEventListener(\"formdata\", this.handleFormData);\n this.form.removeEventListener(\"submit\", this.handleFormSubmit);\n this.form.removeEventListener(\"reset\", this.handleFormReset);\n if (reportValidityOverloads.has(this.form)) {\n this.form.reportValidity = reportValidityOverloads.get(this.form);\n reportValidityOverloads.delete(this.form);\n }\n if (checkValidityOverloads.has(this.form)) {\n this.form.checkValidity = checkValidityOverloads.get(this.form);\n checkValidityOverloads.delete(this.form);\n }\n this.form = void 0;\n }\n }\n setUserInteracted(el, hasInteracted) {\n if (hasInteracted) {\n userInteractedControls.add(el);\n } else {\n userInteractedControls.delete(el);\n }\n el.requestUpdate();\n }\n doAction(type, submitter) {\n if (this.form) {\n const button = document.createElement(\"button\");\n button.type = type;\n button.style.position = \"absolute\";\n button.style.width = \"0\";\n button.style.height = \"0\";\n button.style.clipPath = \"inset(50%)\";\n button.style.overflow = \"hidden\";\n button.style.whiteSpace = \"nowrap\";\n if (submitter) {\n button.name = submitter.name;\n button.value = submitter.value;\n [\"formaction\", \"formenctype\", \"formmethod\", \"formnovalidate\", \"formtarget\"].forEach((attr) => {\n if (submitter.hasAttribute(attr)) {\n button.setAttribute(attr, submitter.getAttribute(attr));\n }\n });\n }\n this.form.append(button);\n button.click();\n button.remove();\n }\n }\n /** Returns the associated `
    ` element, if one exists. */\n getForm() {\n var _a;\n return (_a = this.form) != null ? _a : null;\n }\n /** Resets the form, restoring all the control to their default value */\n reset(submitter) {\n this.doAction(\"reset\", submitter);\n }\n /** Submits the form, triggering validation and form data injection. */\n submit(submitter) {\n this.doAction(\"submit\", submitter);\n }\n /**\n * Synchronously sets the form control's validity. Call this when you know the future validity but need to update\n * the host element immediately, i.e. before Lit updates the component in the next update.\n */\n setValidity(isValid) {\n const host = this.host;\n const hasInteracted = Boolean(userInteractedControls.has(host));\n const required = Boolean(host.required);\n host.toggleAttribute(\"data-required\", required);\n host.toggleAttribute(\"data-optional\", !required);\n host.toggleAttribute(\"data-invalid\", !isValid);\n host.toggleAttribute(\"data-valid\", isValid);\n host.toggleAttribute(\"data-user-invalid\", !isValid && hasInteracted);\n host.toggleAttribute(\"data-user-valid\", isValid && hasInteracted);\n }\n /**\n * Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything\n * that affects constraint validation changes so the component receives the correct validity states.\n */\n updateValidity() {\n const host = this.host;\n this.setValidity(host.validity.valid);\n }\n /**\n * Dispatches a non-bubbling, cancelable custom event of type `sl-invalid`.\n * If the `sl-invalid` event will be cancelled then the original `invalid`\n * event (which may have been passed as argument) will also be cancelled.\n * If no original `invalid` event has been passed then the `sl-invalid`\n * event will be cancelled before being dispatched.\n */\n emitInvalidEvent(originalInvalidEvent) {\n const slInvalidEvent = new CustomEvent(\"sl-invalid\", {\n bubbles: false,\n composed: false,\n cancelable: true,\n detail: {}\n });\n if (!originalInvalidEvent) {\n slInvalidEvent.preventDefault();\n }\n if (!this.host.dispatchEvent(slInvalidEvent)) {\n originalInvalidEvent == null ? void 0 : originalInvalidEvent.preventDefault();\n }\n }\n};\nvar validValidityState = Object.freeze({\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: true,\n valueMissing: false\n});\nvar valueMissingValidityState = Object.freeze(__spreadProps(__spreadValues({}, validValidityState), {\n valid: false,\n valueMissing: true\n}));\nvar customErrorValidityState = Object.freeze(__spreadProps(__spreadValues({}, validValidityState), {\n valid: false,\n customError: true\n}));\n\nexport {\n formCollections,\n FormControlController,\n validValidityState,\n valueMissingValidityState,\n customErrorValidityState\n};\n","// src/components/button/button.styles.ts\nimport { css } from \"lit\";\nvar button_styles_default = css`\n :host {\n display: inline-block;\n position: relative;\n width: auto;\n cursor: pointer;\n }\n\n .button {\n display: inline-flex;\n align-items: stretch;\n justify-content: center;\n width: 100%;\n border-style: solid;\n border-width: var(--sl-input-border-width);\n font-family: var(--sl-input-font-family);\n font-weight: var(--sl-font-weight-semibold);\n text-decoration: none;\n user-select: none;\n -webkit-user-select: none;\n white-space: nowrap;\n vertical-align: middle;\n padding: 0;\n transition:\n var(--sl-transition-x-fast) background-color,\n var(--sl-transition-x-fast) color,\n var(--sl-transition-x-fast) border,\n var(--sl-transition-x-fast) box-shadow;\n cursor: inherit;\n }\n\n .button::-moz-focus-inner {\n border: 0;\n }\n\n .button:focus {\n outline: none;\n }\n\n .button:focus-visible {\n outline: var(--sl-focus-ring);\n outline-offset: var(--sl-focus-ring-offset);\n }\n\n .button--disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n /* When disabled, prevent mouse events from bubbling up from children */\n .button--disabled * {\n pointer-events: none;\n }\n\n .button__prefix,\n .button__suffix {\n flex: 0 0 auto;\n display: flex;\n align-items: center;\n pointer-events: none;\n }\n\n .button__label {\n display: inline-block;\n }\n\n .button__label::slotted(sl-icon) {\n vertical-align: -2px;\n }\n\n /*\n * Standard buttons\n */\n\n /* Default */\n .button--standard.button--default {\n background-color: var(--sl-color-neutral-0);\n border-color: var(--sl-input-border-color);\n color: var(--sl-color-neutral-700);\n }\n\n .button--standard.button--default:hover:not(.button--disabled) {\n background-color: var(--sl-color-primary-50);\n border-color: var(--sl-color-primary-300);\n color: var(--sl-color-primary-700);\n }\n\n .button--standard.button--default:active:not(.button--disabled) {\n background-color: var(--sl-color-primary-100);\n border-color: var(--sl-color-primary-400);\n color: var(--sl-color-primary-700);\n }\n\n /* Primary */\n .button--standard.button--primary {\n background-color: var(--sl-color-primary-600);\n border-color: var(--sl-color-primary-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--primary:hover:not(.button--disabled) {\n background-color: var(--sl-color-primary-500);\n border-color: var(--sl-color-primary-500);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--primary:active:not(.button--disabled) {\n background-color: var(--sl-color-primary-600);\n border-color: var(--sl-color-primary-600);\n color: var(--sl-color-neutral-0);\n }\n\n /* Success */\n .button--standard.button--success {\n background-color: var(--sl-color-success-600);\n border-color: var(--sl-color-success-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--success:hover:not(.button--disabled) {\n background-color: var(--sl-color-success-500);\n border-color: var(--sl-color-success-500);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--success:active:not(.button--disabled) {\n background-color: var(--sl-color-success-600);\n border-color: var(--sl-color-success-600);\n color: var(--sl-color-neutral-0);\n }\n\n /* Neutral */\n .button--standard.button--neutral {\n background-color: var(--sl-color-neutral-600);\n border-color: var(--sl-color-neutral-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--neutral:hover:not(.button--disabled) {\n background-color: var(--sl-color-neutral-500);\n border-color: var(--sl-color-neutral-500);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--neutral:active:not(.button--disabled) {\n background-color: var(--sl-color-neutral-600);\n border-color: var(--sl-color-neutral-600);\n color: var(--sl-color-neutral-0);\n }\n\n /* Warning */\n .button--standard.button--warning {\n background-color: var(--sl-color-warning-600);\n border-color: var(--sl-color-warning-600);\n color: var(--sl-color-neutral-0);\n }\n .button--standard.button--warning:hover:not(.button--disabled) {\n background-color: var(--sl-color-warning-500);\n border-color: var(--sl-color-warning-500);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--warning:active:not(.button--disabled) {\n background-color: var(--sl-color-warning-600);\n border-color: var(--sl-color-warning-600);\n color: var(--sl-color-neutral-0);\n }\n\n /* Danger */\n .button--standard.button--danger {\n background-color: var(--sl-color-danger-600);\n border-color: var(--sl-color-danger-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--danger:hover:not(.button--disabled) {\n background-color: var(--sl-color-danger-500);\n border-color: var(--sl-color-danger-500);\n color: var(--sl-color-neutral-0);\n }\n\n .button--standard.button--danger:active:not(.button--disabled) {\n background-color: var(--sl-color-danger-600);\n border-color: var(--sl-color-danger-600);\n color: var(--sl-color-neutral-0);\n }\n\n /*\n * Outline buttons\n */\n\n .button--outline {\n background: none;\n border: solid 1px;\n }\n\n /* Default */\n .button--outline.button--default {\n border-color: var(--sl-input-border-color);\n color: var(--sl-color-neutral-700);\n }\n\n .button--outline.button--default:hover:not(.button--disabled),\n .button--outline.button--default.button--checked:not(.button--disabled) {\n border-color: var(--sl-color-primary-600);\n background-color: var(--sl-color-primary-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--outline.button--default:active:not(.button--disabled) {\n border-color: var(--sl-color-primary-700);\n background-color: var(--sl-color-primary-700);\n color: var(--sl-color-neutral-0);\n }\n\n /* Primary */\n .button--outline.button--primary {\n border-color: var(--sl-color-primary-600);\n color: var(--sl-color-primary-600);\n }\n\n .button--outline.button--primary:hover:not(.button--disabled),\n .button--outline.button--primary.button--checked:not(.button--disabled) {\n background-color: var(--sl-color-primary-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--outline.button--primary:active:not(.button--disabled) {\n border-color: var(--sl-color-primary-700);\n background-color: var(--sl-color-primary-700);\n color: var(--sl-color-neutral-0);\n }\n\n /* Success */\n .button--outline.button--success {\n border-color: var(--sl-color-success-600);\n color: var(--sl-color-success-600);\n }\n\n .button--outline.button--success:hover:not(.button--disabled),\n .button--outline.button--success.button--checked:not(.button--disabled) {\n background-color: var(--sl-color-success-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--outline.button--success:active:not(.button--disabled) {\n border-color: var(--sl-color-success-700);\n background-color: var(--sl-color-success-700);\n color: var(--sl-color-neutral-0);\n }\n\n /* Neutral */\n .button--outline.button--neutral {\n border-color: var(--sl-color-neutral-600);\n color: var(--sl-color-neutral-600);\n }\n\n .button--outline.button--neutral:hover:not(.button--disabled),\n .button--outline.button--neutral.button--checked:not(.button--disabled) {\n background-color: var(--sl-color-neutral-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--outline.button--neutral:active:not(.button--disabled) {\n border-color: var(--sl-color-neutral-700);\n background-color: var(--sl-color-neutral-700);\n color: var(--sl-color-neutral-0);\n }\n\n /* Warning */\n .button--outline.button--warning {\n border-color: var(--sl-color-warning-600);\n color: var(--sl-color-warning-600);\n }\n\n .button--outline.button--warning:hover:not(.button--disabled),\n .button--outline.button--warning.button--checked:not(.button--disabled) {\n background-color: var(--sl-color-warning-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--outline.button--warning:active:not(.button--disabled) {\n border-color: var(--sl-color-warning-700);\n background-color: var(--sl-color-warning-700);\n color: var(--sl-color-neutral-0);\n }\n\n /* Danger */\n .button--outline.button--danger {\n border-color: var(--sl-color-danger-600);\n color: var(--sl-color-danger-600);\n }\n\n .button--outline.button--danger:hover:not(.button--disabled),\n .button--outline.button--danger.button--checked:not(.button--disabled) {\n background-color: var(--sl-color-danger-600);\n color: var(--sl-color-neutral-0);\n }\n\n .button--outline.button--danger:active:not(.button--disabled) {\n border-color: var(--sl-color-danger-700);\n background-color: var(--sl-color-danger-700);\n color: var(--sl-color-neutral-0);\n }\n\n @media (forced-colors: active) {\n .button.button--outline.button--checked:not(.button--disabled) {\n outline: solid 2px transparent;\n }\n }\n\n /*\n * Text buttons\n */\n\n .button--text {\n background-color: transparent;\n border-color: transparent;\n color: var(--sl-color-primary-600);\n }\n\n .button--text:hover:not(.button--disabled) {\n background-color: transparent;\n border-color: transparent;\n color: var(--sl-color-primary-500);\n }\n\n .button--text:focus-visible:not(.button--disabled) {\n background-color: transparent;\n border-color: transparent;\n color: var(--sl-color-primary-500);\n }\n\n .button--text:active:not(.button--disabled) {\n background-color: transparent;\n border-color: transparent;\n color: var(--sl-color-primary-700);\n }\n\n /*\n * Size modifiers\n */\n\n .button--small {\n height: auto;\n min-height: var(--sl-input-height-small);\n font-size: var(--sl-button-font-size-small);\n line-height: calc(var(--sl-input-height-small) - var(--sl-input-border-width) * 2);\n border-radius: var(--sl-input-border-radius-small);\n }\n\n .button--medium {\n height: auto;\n min-height: var(--sl-input-height-medium);\n font-size: var(--sl-button-font-size-medium);\n line-height: calc(var(--sl-input-height-medium) - var(--sl-input-border-width) * 2);\n border-radius: var(--sl-input-border-radius-medium);\n }\n\n .button--large {\n height: auto;\n min-height: var(--sl-input-height-large);\n font-size: var(--sl-button-font-size-large);\n line-height: calc(var(--sl-input-height-large) - var(--sl-input-border-width) * 2);\n border-radius: var(--sl-input-border-radius-large);\n }\n\n /*\n * Pill modifier\n */\n\n .button--pill.button--small {\n border-radius: var(--sl-input-height-small);\n }\n\n .button--pill.button--medium {\n border-radius: var(--sl-input-height-medium);\n }\n\n .button--pill.button--large {\n border-radius: var(--sl-input-height-large);\n }\n\n /*\n * Circle modifier\n */\n\n .button--circle {\n padding-left: 0;\n padding-right: 0;\n }\n\n .button--circle.button--small {\n width: var(--sl-input-height-small);\n border-radius: 50%;\n }\n\n .button--circle.button--medium {\n width: var(--sl-input-height-medium);\n border-radius: 50%;\n }\n\n .button--circle.button--large {\n width: var(--sl-input-height-large);\n border-radius: 50%;\n }\n\n .button--circle .button__prefix,\n .button--circle .button__suffix,\n .button--circle .button__caret {\n display: none;\n }\n\n /*\n * Caret modifier\n */\n\n .button--caret .button__suffix {\n display: none;\n }\n\n .button--caret .button__caret {\n height: auto;\n }\n\n /*\n * Loading modifier\n */\n\n .button--loading {\n position: relative;\n cursor: wait;\n }\n\n .button--loading .button__prefix,\n .button--loading .button__label,\n .button--loading .button__suffix,\n .button--loading .button__caret {\n visibility: hidden;\n }\n\n .button--loading sl-spinner {\n --indicator-color: currentColor;\n position: absolute;\n font-size: 1em;\n height: 1em;\n width: 1em;\n top: calc(50% - 0.5em);\n left: calc(50% - 0.5em);\n }\n\n /*\n * Badges\n */\n\n .button ::slotted(sl-badge) {\n position: absolute;\n top: 0;\n right: 0;\n translate: 50% -50%;\n pointer-events: none;\n }\n\n .button--rtl ::slotted(sl-badge) {\n right: auto;\n left: 0;\n translate: -50% -50%;\n }\n\n /*\n * Button spacing\n */\n\n .button--has-label.button--small .button__label {\n padding: 0 var(--sl-spacing-small);\n }\n\n .button--has-label.button--medium .button__label {\n padding: 0 var(--sl-spacing-medium);\n }\n\n .button--has-label.button--large .button__label {\n padding: 0 var(--sl-spacing-large);\n }\n\n .button--has-prefix.button--small {\n padding-inline-start: var(--sl-spacing-x-small);\n }\n\n .button--has-prefix.button--small .button__label {\n padding-inline-start: var(--sl-spacing-x-small);\n }\n\n .button--has-prefix.button--medium {\n padding-inline-start: var(--sl-spacing-small);\n }\n\n .button--has-prefix.button--medium .button__label {\n padding-inline-start: var(--sl-spacing-small);\n }\n\n .button--has-prefix.button--large {\n padding-inline-start: var(--sl-spacing-small);\n }\n\n .button--has-prefix.button--large .button__label {\n padding-inline-start: var(--sl-spacing-small);\n }\n\n .button--has-suffix.button--small,\n .button--caret.button--small {\n padding-inline-end: var(--sl-spacing-x-small);\n }\n\n .button--has-suffix.button--small .button__label,\n .button--caret.button--small .button__label {\n padding-inline-end: var(--sl-spacing-x-small);\n }\n\n .button--has-suffix.button--medium,\n .button--caret.button--medium {\n padding-inline-end: var(--sl-spacing-small);\n }\n\n .button--has-suffix.button--medium .button__label,\n .button--caret.button--medium .button__label {\n padding-inline-end: var(--sl-spacing-small);\n }\n\n .button--has-suffix.button--large,\n .button--caret.button--large {\n padding-inline-end: var(--sl-spacing-small);\n }\n\n .button--has-suffix.button--large .button__label,\n .button--caret.button--large .button__label {\n padding-inline-end: var(--sl-spacing-small);\n }\n\n /*\n * Button groups support a variety of button types (e.g. buttons with tooltips, buttons as dropdown triggers, etc.).\n * This means buttons aren't always direct descendants of the button group, thus we can't target them with the\n * ::slotted selector. To work around this, the button group component does some magic to add these special classes to\n * buttons and we style them here instead.\n */\n\n :host([data-sl-button-group__button--first]:not([data-sl-button-group__button--last])) .button {\n border-start-end-radius: 0;\n border-end-end-radius: 0;\n }\n\n :host([data-sl-button-group__button--inner]) .button {\n border-radius: 0;\n }\n\n :host([data-sl-button-group__button--last]:not([data-sl-button-group__button--first])) .button {\n border-start-start-radius: 0;\n border-end-start-radius: 0;\n }\n\n /* All except the first */\n :host([data-sl-button-group__button]:not([data-sl-button-group__button--first])) {\n margin-inline-start: calc(-1 * var(--sl-input-border-width));\n }\n\n /* Add a visual separator between solid buttons */\n :host(\n [data-sl-button-group__button]:not(\n [data-sl-button-group__button--first],\n [data-sl-button-group__button--radio],\n [variant='default']\n ):not(:hover)\n )\n .button:after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-start: 0;\n bottom: 0;\n border-left: solid 1px rgb(128 128 128 / 33%);\n mix-blend-mode: multiply;\n }\n\n /* Bump hovered, focused, and checked buttons up so their focus ring isn't clipped */\n :host([data-sl-button-group__button--hover]) {\n z-index: 1;\n }\n\n /* Focus and checked are always on top */\n :host([data-sl-button-group__button--focus]),\n :host([data-sl-button-group__button][checked]) {\n z-index: 2;\n }\n`;\n\nexport {\n button_styles_default\n};\n","import {\n getBasePath\n} from \"./chunk.3Y6SB6QS.js\";\n\n// src/components/icon/library.default.ts\nvar library = {\n name: \"default\",\n resolver: (name) => getBasePath(`assets/icons/${name}.svg`)\n};\nvar library_default_default = library;\n\nexport {\n library_default_default\n};\n","// src/components/icon/library.system.ts\nvar icons = {\n caret: `\n \n \n \n `,\n check: `\n \n \n \n \n \n \n \n \n \n \n `,\n \"chevron-down\": `\n \n \n \n `,\n \"chevron-left\": `\n \n \n \n `,\n \"chevron-right\": `\n \n \n \n `,\n copy: `\n \n \n \n `,\n eye: `\n \n \n \n \n `,\n \"eye-slash\": `\n \n \n \n \n \n `,\n eyedropper: `\n \n \n \n `,\n \"grip-vertical\": `\n \n \n \n `,\n indeterminate: `\n \n \n \n \n \n \n \n \n \n `,\n \"person-fill\": `\n \n \n \n `,\n \"play-fill\": `\n \n \n \n `,\n \"pause-fill\": `\n \n \n \n `,\n radio: `\n \n \n \n \n \n \n \n `,\n \"star-fill\": `\n \n \n \n `,\n \"x-lg\": `\n \n \n \n `,\n \"x-circle-fill\": `\n \n \n \n `\n};\nvar systemLibrary = {\n name: \"system\",\n resolver: (name) => {\n if (name in icons) {\n return `data:image/svg+xml,${encodeURIComponent(icons[name])}`;\n }\n return \"\";\n }\n};\nvar library_system_default = systemLibrary;\n\nexport {\n library_system_default\n};\n","import {\n library_default_default\n} from \"./chunk.P7ZG6EMR.js\";\nimport {\n library_system_default\n} from \"./chunk.3TFKS637.js\";\n\n// src/components/icon/library.ts\nvar registry = [library_default_default, library_system_default];\nvar watchedIcons = [];\nfunction watchIcon(icon) {\n watchedIcons.push(icon);\n}\nfunction unwatchIcon(icon) {\n watchedIcons = watchedIcons.filter((el) => el !== icon);\n}\nfunction getIconLibrary(name) {\n return registry.find((lib) => lib.name === name);\n}\nfunction registerIconLibrary(name, options) {\n unregisterIconLibrary(name);\n registry.push({\n name,\n resolver: options.resolver,\n mutator: options.mutator,\n spriteSheet: options.spriteSheet\n });\n watchedIcons.forEach((icon) => {\n if (icon.library === name) {\n icon.setIcon();\n }\n });\n}\nfunction unregisterIconLibrary(name) {\n registry = registry.filter((lib) => lib.name !== name);\n}\n\nexport {\n watchIcon,\n unwatchIcon,\n getIconLibrary,\n registerIconLibrary,\n unregisterIconLibrary\n};\n","// src/components/icon/icon.styles.ts\nimport { css } from \"lit\";\nvar icon_styles_default = css`\n :host {\n display: inline-block;\n width: 1em;\n height: 1em;\n box-sizing: content-box !important;\n }\n\n svg {\n display: block;\n height: 100%;\n width: 100%;\n }\n`;\n\nexport {\n icon_styles_default\n};\n","import {\n __spreadValues\n} from \"./chunk.B3BW2AY6.js\";\n\n// src/internal/watch.ts\nfunction watch(propertyName, options) {\n const resolvedOptions = __spreadValues({\n waitUntilFirstUpdate: false\n }, options);\n return (proto, decoratedFnName) => {\n const { update } = proto;\n const watchedProperties = Array.isArray(propertyName) ? propertyName : [propertyName];\n proto.update = function(changedProps) {\n watchedProperties.forEach((property) => {\n const key = property;\n if (changedProps.has(key)) {\n const oldValue = changedProps.get(key);\n const newValue = this[key];\n if (oldValue !== newValue) {\n if (!resolvedOptions.waitUntilFirstUpdate || this.hasUpdated) {\n this[decoratedFnName](oldValue, newValue);\n }\n }\n }\n });\n update.call(this, changedProps);\n };\n };\n}\n\nexport {\n watch\n};\n","import{_$LH as o}from\"./lit-html.js\";\n/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{I:t}=o,i=o=>null===o||\"object\"!=typeof o&&\"function\"!=typeof o,n={HTML:1,SVG:2,MATHML:3},e=(o,t)=>void 0===t?void 0!==o?._$litType$:o?._$litType$===t,l=o=>null!=o?._$litType$?.h,c=o=>void 0!==o?._$litDirective$,d=o=>o?._$litDirective$,f=o=>void 0===o.strings,s=()=>document.createComment(\"\"),r=(o,i,n)=>{const e=o._$AA.parentNode,l=void 0===i?o._$AB:i._$AA;if(void 0===n){const i=e.insertBefore(s(),l),c=e.insertBefore(s(),l);n=new t(i,c,o,o.options)}else{const t=n._$AB.nextSibling,i=n._$AM,c=i!==o;if(c){let t;n._$AQ?.(o),n._$AM=o,void 0!==n._$AP&&(t=o._$AU)!==i._$AU&&n._$AP(t)}if(t!==l||c){let o=n._$AA;for(;o!==t;){const t=o.nextSibling;e.insertBefore(o,l),o=t}}}return n},v=(o,t,i=o)=>(o._$AI(t,i),o),u={},m=(o,t=u)=>o._$AH=t,p=o=>o._$AH,M=o=>{o._$AP?.(!1,!0);let t=o._$AA;const i=o._$AB.nextSibling;for(;t!==i;){const o=t.nextSibling;t.remove(),t=o}},h=o=>{o._$AR()};export{n as TemplateResultType,h as clearPart,p as getCommittedValue,d as getDirectiveClass,r as insertPart,l as isCompiledTemplateResult,c as isDirectiveResult,i as isPrimitive,f as isSingleExpression,e as isTemplateResult,M as removePart,v as setChildPartValue,m as setCommittedValue};\n//# sourceMappingURL=directive-helpers.js.map\n","import {\n getIconLibrary,\n unwatchIcon,\n watchIcon\n} from \"./chunk.ZL53POKZ.js\";\nimport {\n icon_styles_default\n} from \"./chunk.QLXRCYS4.js\";\nimport {\n watch\n} from \"./chunk.CCJUT23E.js\";\nimport {\n component_styles_default\n} from \"./chunk.TUVJKY7S.js\";\nimport {\n ShoelaceElement\n} from \"./chunk.UYAO2JRR.js\";\nimport {\n __decorateClass\n} from \"./chunk.B3BW2AY6.js\";\n\n// src/components/icon/icon.component.ts\nimport { html } from \"lit\";\nimport { isTemplateResult } from \"lit/directive-helpers.js\";\nimport { property, state } from \"lit/decorators.js\";\nvar CACHEABLE_ERROR = Symbol();\nvar RETRYABLE_ERROR = Symbol();\nvar parser;\nvar iconCache = /* @__PURE__ */ new Map();\nvar SlIcon = class extends ShoelaceElement {\n constructor() {\n super(...arguments);\n this.initialRender = false;\n this.svg = null;\n this.label = \"\";\n this.library = \"default\";\n }\n /** Given a URL, this function returns the resulting SVG element or an appropriate error symbol. */\n async resolveIcon(url, library) {\n var _a;\n let fileData;\n if (library == null ? void 0 : library.spriteSheet) {\n this.svg = html`\n \n `;\n return this.svg;\n }\n try {\n fileData = await fetch(url, { mode: \"cors\" });\n if (!fileData.ok)\n return fileData.status === 410 ? CACHEABLE_ERROR : RETRYABLE_ERROR;\n } catch (e) {\n return RETRYABLE_ERROR;\n }\n try {\n const div = document.createElement(\"div\");\n div.innerHTML = await fileData.text();\n const svg = div.firstElementChild;\n if (((_a = svg == null ? void 0 : svg.tagName) == null ? void 0 : _a.toLowerCase()) !== \"svg\")\n return CACHEABLE_ERROR;\n if (!parser)\n parser = new DOMParser();\n const doc = parser.parseFromString(svg.outerHTML, \"text/html\");\n const svgEl = doc.body.querySelector(\"svg\");\n if (!svgEl)\n return CACHEABLE_ERROR;\n svgEl.part.add(\"svg\");\n return document.adoptNode(svgEl);\n } catch (e) {\n return CACHEABLE_ERROR;\n }\n }\n connectedCallback() {\n super.connectedCallback();\n watchIcon(this);\n }\n firstUpdated() {\n this.initialRender = true;\n this.setIcon();\n }\n disconnectedCallback() {\n super.disconnectedCallback();\n unwatchIcon(this);\n }\n getIconSource() {\n const library = getIconLibrary(this.library);\n if (this.name && library) {\n return {\n url: library.resolver(this.name),\n fromLibrary: true\n };\n }\n return {\n url: this.src,\n fromLibrary: false\n };\n }\n handleLabelChange() {\n const hasLabel = typeof this.label === \"string\" && this.label.length > 0;\n if (hasLabel) {\n this.setAttribute(\"role\", \"img\");\n this.setAttribute(\"aria-label\", this.label);\n this.removeAttribute(\"aria-hidden\");\n } else {\n this.removeAttribute(\"role\");\n this.removeAttribute(\"aria-label\");\n this.setAttribute(\"aria-hidden\", \"true\");\n }\n }\n async setIcon() {\n var _a;\n const { url, fromLibrary } = this.getIconSource();\n const library = fromLibrary ? getIconLibrary(this.library) : void 0;\n if (!url) {\n this.svg = null;\n return;\n }\n let iconResolver = iconCache.get(url);\n if (!iconResolver) {\n iconResolver = this.resolveIcon(url, library);\n iconCache.set(url, iconResolver);\n }\n if (!this.initialRender) {\n return;\n }\n const svg = await iconResolver;\n if (svg === RETRYABLE_ERROR) {\n iconCache.delete(url);\n }\n if (url !== this.getIconSource().url) {\n return;\n }\n if (isTemplateResult(svg)) {\n this.svg = svg;\n if (library) {\n await this.updateComplete;\n const shadowSVG = this.shadowRoot.querySelector(\"[part='svg']\");\n if (typeof library.mutator === \"function\" && shadowSVG) {\n library.mutator(shadowSVG);\n }\n }\n return;\n }\n switch (svg) {\n case RETRYABLE_ERROR:\n case CACHEABLE_ERROR:\n this.svg = null;\n this.emit(\"sl-error\");\n break;\n default:\n this.svg = svg.cloneNode(true);\n (_a = library == null ? void 0 : library.mutator) == null ? void 0 : _a.call(library, this.svg);\n this.emit(\"sl-load\");\n }\n }\n render() {\n return this.svg;\n }\n};\nSlIcon.styles = [component_styles_default, icon_styles_default];\n__decorateClass([\n state()\n], SlIcon.prototype, \"svg\", 2);\n__decorateClass([\n property({ reflect: true })\n], SlIcon.prototype, \"name\", 2);\n__decorateClass([\n property()\n], SlIcon.prototype, \"src\", 2);\n__decorateClass([\n property()\n], SlIcon.prototype, \"label\", 2);\n__decorateClass([\n property({ reflect: true })\n], SlIcon.prototype, \"library\", 2);\n__decorateClass([\n watch(\"label\")\n], SlIcon.prototype, \"handleLabelChange\", 1);\n__decorateClass([\n watch([\"name\", \"src\", \"library\"])\n], SlIcon.prototype, \"setIcon\", 1);\n\nexport {\n SlIcon\n};\n","import{html as t,svg as r,mathml as e}from\"./lit-html.js\";\n/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst a=Symbol.for(\"\"),o=t=>{if(t?.r===a)return t?._$litStatic$},s=t=>({_$litStatic$:t,r:a}),i=(t,...r)=>({_$litStatic$:r.reduce(((r,e,a)=>r+(t=>{if(void 0!==t._$litStatic$)return t._$litStatic$;throw Error(`Value passed to 'literal' function must be a 'literal' result: ${t}. Use 'unsafeStatic' to pass non-literal values, but\\n take care to ensure page security.`)})(e)+t[a+1]),t[0]),r:a}),l=new Map,n=t=>(r,...e)=>{const a=e.length;let s,i;const n=[],u=[];let c,$=0,f=!1;for(;$o??t;export{o as ifDefined};\n//# sourceMappingURL=if-defined.js.map\n","import {\n SlSpinner\n} from \"./chunk.TLKDQ5JG.js\";\nimport {\n FormControlController,\n validValidityState\n} from \"./chunk.2RCF7SLU.js\";\nimport {\n button_styles_default\n} from \"./chunk.MAQXLKQ7.js\";\nimport {\n LocalizeController\n} from \"./chunk.WLV3FVBR.js\";\nimport {\n HasSlotController\n} from \"./chunk.NYIIDP5N.js\";\nimport {\n SlIcon\n} from \"./chunk.E6QAPUBK.js\";\nimport {\n watch\n} from \"./chunk.CCJUT23E.js\";\nimport {\n component_styles_default\n} from \"./chunk.TUVJKY7S.js\";\nimport {\n ShoelaceElement\n} from \"./chunk.UYAO2JRR.js\";\nimport {\n __decorateClass\n} from \"./chunk.B3BW2AY6.js\";\n\n// src/components/button/button.component.ts\nimport { classMap } from \"lit/directives/class-map.js\";\nimport { html, literal } from \"lit/static-html.js\";\nimport { ifDefined } from \"lit/directives/if-defined.js\";\nimport { property, query, state } from \"lit/decorators.js\";\nvar SlButton = class extends ShoelaceElement {\n constructor() {\n super(...arguments);\n this.formControlController = new FormControlController(this, {\n assumeInteractionOn: [\"click\"]\n });\n this.hasSlotController = new HasSlotController(this, \"[default]\", \"prefix\", \"suffix\");\n this.localize = new LocalizeController(this);\n this.hasFocus = false;\n this.invalid = false;\n this.title = \"\";\n this.variant = \"default\";\n this.size = \"medium\";\n this.caret = false;\n this.disabled = false;\n this.loading = false;\n this.outline = false;\n this.pill = false;\n this.circle = false;\n this.type = \"button\";\n this.name = \"\";\n this.value = \"\";\n this.href = \"\";\n this.rel = \"noreferrer noopener\";\n }\n /** Gets the validity state object */\n get validity() {\n if (this.isButton()) {\n return this.button.validity;\n }\n return validValidityState;\n }\n /** Gets the validation message */\n get validationMessage() {\n if (this.isButton()) {\n return this.button.validationMessage;\n }\n return \"\";\n }\n firstUpdated() {\n if (this.isButton()) {\n this.formControlController.updateValidity();\n }\n }\n handleBlur() {\n this.hasFocus = false;\n this.emit(\"sl-blur\");\n }\n handleFocus() {\n this.hasFocus = true;\n this.emit(\"sl-focus\");\n }\n handleClick() {\n if (this.type === \"submit\") {\n this.formControlController.submit(this);\n }\n if (this.type === \"reset\") {\n this.formControlController.reset(this);\n }\n }\n handleInvalid(event) {\n this.formControlController.setValidity(false);\n this.formControlController.emitInvalidEvent(event);\n }\n isButton() {\n return this.href ? false : true;\n }\n isLink() {\n return this.href ? true : false;\n }\n handleDisabledChange() {\n if (this.isButton()) {\n this.formControlController.setValidity(this.disabled);\n }\n }\n /** Simulates a click on the button. */\n click() {\n this.button.click();\n }\n /** Sets focus on the button. */\n focus(options) {\n this.button.focus(options);\n }\n /** Removes focus from the button. */\n blur() {\n this.button.blur();\n }\n /** Checks for validity but does not show a validation message. Returns `true` when valid and `false` when invalid. */\n checkValidity() {\n if (this.isButton()) {\n return this.button.checkValidity();\n }\n return true;\n }\n /** Gets the associated form, if one exists. */\n getForm() {\n return this.formControlController.getForm();\n }\n /** Checks for validity and shows the browser's validation message if the control is invalid. */\n reportValidity() {\n if (this.isButton()) {\n return this.button.reportValidity();\n }\n return true;\n }\n /** Sets a custom validation message. Pass an empty string to restore validity. */\n setCustomValidity(message) {\n if (this.isButton()) {\n this.button.setCustomValidity(message);\n this.formControlController.updateValidity();\n }\n }\n render() {\n const isLink = this.isLink();\n const tag = isLink ? literal`a` : literal`button`;\n return html`\n <${tag}\n part=\"base\"\n class=${classMap({\n button: true,\n \"button--default\": this.variant === \"default\",\n \"button--primary\": this.variant === \"primary\",\n \"button--success\": this.variant === \"success\",\n \"button--neutral\": this.variant === \"neutral\",\n \"button--warning\": this.variant === \"warning\",\n \"button--danger\": this.variant === \"danger\",\n \"button--text\": this.variant === \"text\",\n \"button--small\": this.size === \"small\",\n \"button--medium\": this.size === \"medium\",\n \"button--large\": this.size === \"large\",\n \"button--caret\": this.caret,\n \"button--circle\": this.circle,\n \"button--disabled\": this.disabled,\n \"button--focused\": this.hasFocus,\n \"button--loading\": this.loading,\n \"button--standard\": !this.outline,\n \"button--outline\": this.outline,\n \"button--pill\": this.pill,\n \"button--rtl\": this.localize.dir() === \"rtl\",\n \"button--has-label\": this.hasSlotController.test(\"[default]\"),\n \"button--has-prefix\": this.hasSlotController.test(\"prefix\"),\n \"button--has-suffix\": this.hasSlotController.test(\"suffix\")\n })}\n ?disabled=${ifDefined(isLink ? void 0 : this.disabled)}\n type=${ifDefined(isLink ? void 0 : this.type)}\n title=${this.title}\n name=${ifDefined(isLink ? void 0 : this.name)}\n value=${ifDefined(isLink ? void 0 : this.value)}\n href=${ifDefined(isLink && !this.disabled ? this.href : void 0)}\n target=${ifDefined(isLink ? this.target : void 0)}\n download=${ifDefined(isLink ? this.download : void 0)}\n rel=${ifDefined(isLink ? this.rel : void 0)}\n role=${ifDefined(isLink ? void 0 : \"button\")}\n aria-disabled=${this.disabled ? \"true\" : \"false\"}\n tabindex=${this.disabled ? \"-1\" : \"0\"}\n @blur=${this.handleBlur}\n @focus=${this.handleFocus}\n @invalid=${this.isButton() ? this.handleInvalid : null}\n @click=${this.handleClick}\n >\n \n \n \n ${this.caret ? html` ` : \"\"}\n ${this.loading ? html`` : \"\"}\n \n `;\n }\n};\nSlButton.styles = [component_styles_default, button_styles_default];\nSlButton.dependencies = {\n \"sl-icon\": SlIcon,\n \"sl-spinner\": SlSpinner\n};\n__decorateClass([\n query(\".button\")\n], SlButton.prototype, \"button\", 2);\n__decorateClass([\n state()\n], SlButton.prototype, \"hasFocus\", 2);\n__decorateClass([\n state()\n], SlButton.prototype, \"invalid\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"title\", 2);\n__decorateClass([\n property({ reflect: true })\n], SlButton.prototype, \"variant\", 2);\n__decorateClass([\n property({ reflect: true })\n], SlButton.prototype, \"size\", 2);\n__decorateClass([\n property({ type: Boolean, reflect: true })\n], SlButton.prototype, \"caret\", 2);\n__decorateClass([\n property({ type: Boolean, reflect: true })\n], SlButton.prototype, \"disabled\", 2);\n__decorateClass([\n property({ type: Boolean, reflect: true })\n], SlButton.prototype, \"loading\", 2);\n__decorateClass([\n property({ type: Boolean, reflect: true })\n], SlButton.prototype, \"outline\", 2);\n__decorateClass([\n property({ type: Boolean, reflect: true })\n], SlButton.prototype, \"pill\", 2);\n__decorateClass([\n property({ type: Boolean, reflect: true })\n], SlButton.prototype, \"circle\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"type\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"name\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"value\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"href\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"target\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"rel\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"download\", 2);\n__decorateClass([\n property()\n], SlButton.prototype, \"form\", 2);\n__decorateClass([\n property({ attribute: \"formaction\" })\n], SlButton.prototype, \"formAction\", 2);\n__decorateClass([\n property({ attribute: \"formenctype\" })\n], SlButton.prototype, \"formEnctype\", 2);\n__decorateClass([\n property({ attribute: \"formmethod\" })\n], SlButton.prototype, \"formMethod\", 2);\n__decorateClass([\n property({ attribute: \"formnovalidate\", type: Boolean })\n], SlButton.prototype, \"formNoValidate\", 2);\n__decorateClass([\n property({ attribute: \"formtarget\" })\n], SlButton.prototype, \"formTarget\", 2);\n__decorateClass([\n watch(\"disabled\", { waitUntilFirstUpdate: true })\n], SlButton.prototype, \"handleDisabledChange\", 1);\n\nexport {\n SlButton\n};\n","import {\n SlButton\n} from \"./chunk.N2SNE3QN.js\";\n\n// src/components/button/button.ts\nvar button_default = SlButton;\nSlButton.define(\"sl-button\");\n\nexport {\n button_default\n};\n","import { css } from 'lit';\n\n// these styles can be imported from any component\n// for an example of how to use this, check /pages/about-about.ts\nexport const styles = css`\n @media(min-width: 1000px) {\n sl-card {\n max-width: 70vw;\n }\n }\n\n main {\n margin-top: 70px;\n padding: 12px;\n }\n\n.ProseMirror {\n position: relative;\n word-wrap: break-word;\n white-space: pre-wrap;\n -webkit-font-variant-ligatures: none;\n font-variant-ligatures: none;\n padding: 1rem;\n line-height: 1.2;\n outline: none;\n font-family: var(\n --markdown-editor-typography-font-family,\n var(--mdc-typography-font-family, Montserrat, sans-serif)\n );\n font-size: var(\n --markdown-editor-typography-font-size,\n var(--mdc-typography-subtitle1-font-size, 1rem)\n );\n font-weight: var(\n --markdown-editor-typography-font-weight,\n var(--mdc-typography-subtitle1-font-weight, 400)\n );\n letter-spacing: var(\n --markdown-editor-typography-letter-spacing,\n var(--mdc-typography-subtitle1-letter-spacing, 0.009375em)\n );\n }\n\n .ProseMirror pre {\n white-space: pre-wrap;\n }\n\n .ProseMirror li {\n position: relative;\n }\n\n .ProseMirror p:first-child,\n .ProseMirror h1:first-child,\n .ProseMirror h2:first-child,\n .ProseMirror h3:first-child,\n .ProseMirror h4:first-child,\n .ProseMirror h5:first-child,\n .ProseMirror h6:first-child {\n margin-top: 10px;\n }\n\n .ProseMirror a {\n color: var(--markdown-editor-typography-anchor-color, -webkit-link);\n text-decoration: var(--markdown-editor-typography-anchor-text-decoration);\n }\n\n .ProseMirror p {\n margin-bottom: 1em;\n }\n\n .ProseMirror-hideselection {\n caret-color: transparent;\n }\n\n .ProseMirror-hideselection *::selection,\n .ProseMirror-hideselection *::-moz-selection {\n background: transparent;\n }\n\n .ProseMirror-selectednode {\n outline: 2px solid #8cf;\n }\n\n /* Make sure li selections wrap around markers */\n li.ProseMirror-selectednode {\n outline: none;\n }\n\n li.ProseMirror-selectednode:after {\n content: '';\n position: absolute;\n left: -32px;\n right: -2px;\n top: -2px;\n bottom: -2px;\n border: 2px solid #8cf;\n pointer-events: none;\n }\n\n .ProseMirror-textblock-dropdown {\n min-width: 3em;\n }\n\n .ProseMirror-menu {\n margin: 0 -4px;\n line-height: 1;\n }\n\n .ProseMirror-tooltip .ProseMirror-menu {\n width: -webkit-fit-content;\n width: fit-content;\n white-space: pre;\n }\n\n .ProseMirror-menuitem {\n margin: 0.25rem 0.25rem 0.25rem 0;\n display: flex;\n justify-content: center;\n align-items: center;\n border-radius: 4px;\n overflow: hidden;\n }\n .ProseMirror-menuitem:hover {\n background-color: #f5f5f5;\n }\n\n .ProseMirror-menuseparator {\n margin: 0 8px;\n }\n\n .ProseMirror-menu-dropdown,\n .ProseMirror-menu-dropdown-menu {\n font-size: 90%;\n white-space: nowrap;\n }\n\n .ProseMirror-menu-dropdown {\n vertical-align: 1px;\n cursor: pointer;\n position: relative;\n padding-right: 15px;\n }\n\n .ProseMirror-menu-dropdown-wrap {\n padding: 1px 0 1px 4px;\n display: inline-block;\n position: relative;\n }\n\n .ProseMirror-menu-dropdown:after {\n content: '';\n border-left: 4px solid transparent;\n border-right: 4px solid transparent;\n border-top: 4px solid currentColor;\n opacity: 0.6;\n position: absolute;\n right: 4px;\n top: calc(50% - 2px);\n }\n\n .ProseMirror-menu-dropdown-menu,\n .ProseMirror-menu-submenu {\n position: absolute;\n background: white;\n color: #666;\n border: 1px solid #aaa;\n padding: 2px;\n }\n\n .ProseMirror-menu-dropdown-menu {\n z-index: 1;\n min-width: 6em;\n }\n\n .ProseMirror-menu-dropdown-item {\n cursor: pointer;\n }\n\n .ProseMirror-menu-dropdown-item:hover {\n background: #f2f2f2;\n }\n\n .ProseMirror-menu-dropdown-item > div {\n padding: 0.375rem 0.5rem;\n }\n\n .ProseMirror-menu-submenu-wrap {\n position: relative;\n margin-right: -4px;\n }\n\n .ProseMirror-menu-submenu-label:after {\n content: '';\n border-top: 4px solid transparent;\n border-bottom: 4px solid transparent;\n border-left: 4px solid currentColor;\n opacity: 0.6;\n position: absolute;\n right: 4px;\n top: calc(50% - 4px);\n }\n\n .ProseMirror-menu-submenu {\n display: none;\n min-width: 4em;\n left: 100%;\n top: -3px;\n }\n\n .ProseMirror-menu-active {\n background: #eee;\n border-radius: 4px;\n color: black;\n }\n\n .ProseMirror-menu-submenu-wrap:hover .ProseMirror-menu-submenu,\n .ProseMirror-menu-submenu-wrap-active .ProseMirror-menu-submenu {\n display: block;\n }\n\n .ProseMirror-menubar {\n display: flex;\n flex-wrap: wrap;\n position: relative;\n background: white;\n min-height: 1em;\n overflow: visible;\n z-index: 2;\n top: 0;\n left: 0;\n right: 0;\n color: #666;\n padding: 1px 6px;\n border-top-left-radius: inherit;\n border-top-right-radius: inherit;\n border-bottom: 1px solid\n var(--markdown-editor-outline-idle-border-color, rgba(0, 0, 0, 0.38));\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n }\n\n .ProseMirror-icon {\n display: inline-block;\n line-height: 0.8;\n vertical-align: -2px;\n /* Compensate for padding */\n padding: 2px 8px;\n cursor: pointer;\n }\n\n .ProseMirror-menu-disabled {\n color: rgba(0,0,0,0.37);\n background-color: rgba(0,0,0,0.12);\n cursor: not-allowed;\n }\n\n .ProseMirror-menu-disabled.ProseMirror-icon {\n cursor: not-allowed;\n }\n\n .ProseMirror-icon svg {\n fill: currentColor;\n height: 1em;\n }\n\n .ProseMirror-icon span {\n vertical-align: text-top;\n }\n\n .ProseMirror-gapcursor {\n display: none;\n pointer-events: none;\n position: absolute;\n }\n\n .ProseMirror-gapcursor:after {\n content: '';\n display: block;\n position: absolute;\n top: -2px;\n width: 20px;\n border-top: 1px solid black;\n animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n }\n\n @keyframes ProseMirror-cursor-blink {\n to {\n visibility: hidden;\n }\n }\n\n .ProseMirror-focused .ProseMirror-gapcursor {\n display: block;\n }\n\n /* Add space around the hr to make clicking it easier */\n .ProseMirror-example-setup-style hr {\n padding: 2px 10px;\n border: none;\n margin: 1em 0;\n }\n\n .ProseMirror-example-setup-style hr:after {\n content: '';\n display: block;\n height: 1px;\n background-color: silver;\n line-height: 2px;\n }\n\n .ProseMirror ul,\n .ProseMirror ol {\n padding-left: 30px;\n }\n\n .ProseMirror blockquote {\n padding-left: 1em;\n border-left: 3px solid #eee;\n margin-left: 0;\n margin-right: 0;\n }\n\n .ProseMirror-example-setup-style img {\n cursor: default;\n }\n\n .ProseMirror-invalid {\n background: #ffc;\n border: 1px solid #cc7;\n border-radius: 4px;\n padding: 5px 10px;\n position: absolute;\n min-width: 10em;\n }\n\n .ProseMirror h1.title.empty-node::before,\n .ProseMirror h2.instructional-prompt.empty-node::before,\n .ProseMirror h3.mechanical-promp.empty-node::before {\n content: 'Enter title here...';\n }\n\n .ProseMirror div.passage-subtitle.empty-node:first-child::before {\n content: 'Enter subtitle here...';\n }\n\n .ProseMirror div.passage-author.empty-node:first-child::before,\n .ProseMirror div.passage-cast-title.empty-node:first-child::before,\n .ProseMirror div.passage-act-title.empty-node:first-child::before,\n .ProseMirror div.passage-scene-title.empty-node:first-child::before,\n .ProseMirror div.passage-verse.empty-node:first-child::before,\n .ProseMirror div.passage-footnotes.empty-node:first-child::before,\n .ProseMirror div.paragraph.empty-node:first-child::before {\n content: 'Enter text here...';\n }\n\n div[contenteditable]:focus h1.title.empty-node::before,\n div[contenteditable]:focus h2.instructional-prompt.empty-node::before,\n div[contenteditable]:focus h3.mechanical-promp.empty-node::before,\n div[contenteditable]:focus\n div.passage-subtitle.empty-node:first-child::before,\n div[contenteditable]:focus div.passage-author.empty-node:first-child::before,\n div[contenteditable]:focus\n div.passage-cast-title.empty-node:first-child::before,\n div[contenteditable]:focus\n div.passage-act-title.empty-node:first-child::before,\n div[contenteditable]:focus\n div.passage-scene-title.empty-node:first-child::before,\n div[contenteditable]:focus div.passage-verse.empty-node:first-child::before,\n div[contenteditable]:focus\n div.passage-footnotes.empty-node:first-child::before,\n div[contenteditable]:focus div.paragraph.empty-node:first-child::before {\n content: '';\n }\n\n .ProseMirror .empty-node::before {\n position: absolute;\n color: #aaa;\n cursor: text;\n font-style: italic;\n }\n\n #editor, .editor {\n background: white;\n color: black;\n background-clip: padding-box;\n padding: 5px 0;\n }\n\n #editor[disabled] .ProseMirror-menubar {\n display: none!important;\n }\n\n drop-down-editor rich-text .inline-component-button,\n expand-collapse rich-text .inline-component-button,\n flip-reveal rich-text .inline-component-button,\n hint-list rich-text .inline-component-button,\n option-list rich-text .inline-component-button,\n plankton-passage rich-text .inline-component-button {\n pointer-events: none;\n color: lightgray;\n }\n\n #ProseMirror-icon-collection path {\n fill-rule: evenodd;\n }\n #welcomeBar {\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n }\n\n #welcomeCard,\n #infoCard {\n padding: 18px;\n padding-top: 0px;\n }\n\n sl-card::part(footer) {\n display: flex;\n justify-content: flex-end;\n }\n\n @media(min-width: 750px) {\n sl-card {\n width: 70vw;\n }\n }\n\n @media (horizontal-viewport-segments: 2) {\n #welcomeBar {\n flex-direction: row;\n align-items: flex-start;\n justify-content: space-between;\n }\n\n\n\n\n @media (horizontal-viewport-segments: 2) {\n #welcomeBar {\n flex-direction: row;\n align-items: flex-start;\n justify-content: space-between;\n }\n\n\n }\n .boring {\n background: grey;\n }\n\n .plus {\n position: absolute;\n\n padding: 8px;\n background-color: #4CAF50;\n color: red;\n border: none;\n cursor: pointer;\n}\n\n.plus:hover {\n background-color: #45a049;\n}\n\n.ProseMirror-textblock-dropdown {\n min-width: 3em;\n}\n}`","import { LitElement, css, html } from 'lit';\nimport { property, customElement } from 'lit/decorators.js';\nimport { Relay } from 'nostr-tools';\n\nimport '@shoelace-style/shoelace/dist/components/card/card.js';\nimport '@shoelace-style/shoelace/dist/components/button/button.js';\n\nimport { styles } from '../styles/shared-styles';\n\n\n\n\n@customElement('note-wall')\nexport class NoteWall extends LitElement {\n\n@property({ type: Array }) notes: { content: string; date: string }[] = [];\n@property({ type: String }) relayName: string = '';\n\n\nnote = ''; // store notes\n\n static styles = [\n styles,\n css`\n\n.comment-wall .main-section-header {\n margin-bottom: 3px;\n}\n\n.comment-wall .main-section-h2 {\n margin-bottom: 0;\n}\n\n#comment-counter {\n margin-top: 0;\n margin-left: 15px;\n margin-bottom: 3px;\n}\n\n.comment-wall table {\n margin: auto;\n margin-bottom: 5px;\n color: black;\n}\n\n\n.comment-wall th {\n width: 158px;\n padding: 3px;\n vertical-align: top;\n}\n\n.comment-wall td {\n vertical-align: top;\n width: 269px;\n padding: 3px;\n}\n\n.comment-wall figcaption,\n.comment-wall figure {\n margin: 0;\n}\n\n.comment-wall figcaption {\n margin-bottom: 1em;\n}\n\n.comment-wall figure {\n margin-bottom: 49.33px;\n}\n\n.comment-wall h3 {\n font-size: 10pt;\n margin: 0;\n margin-bottom: 3em;\n}\n\n.comment-wall p {\n font-weight: normal;\n text-align: center;\n margin: 0;\n}\n\n#add-comment {\n text-align: right;\n margin-right: 10px;\n margin-bottom: 5px;\n}\n\n\n `];\n\n\n\n getUserLang() {\n\n return navigator.language || 'en';\n\n }\n\n async firstUpdated() {\n // this method is a lifecycle even in lit\n // for more info check out the lit docs https://lit.dev/docs/components/lifecycle/\n console.log('Here are some recent notes from the neighborhood');\n }\n\n async connectedCallback(): Promise {\n super.connectedCallback();\n await Promise.all([\n this.fetchNotes(),\n\n ]);\n\n}\n\n\n/* async translateText(text: string, targetLang: string) {\n try {\n const response = await axios.post('https://api-free.deepl.com/v2/translate', {\n text, target_lang: targetLang });\n\n return response.data.translations[0].text; // Assuming DeepL's API structure\n } catch (error: any) {\n console.error('Error during translation:', error.response?.data || error.message);\n return '';\n }\n} */\n\n\n\n\nasync fetchNotes() {\n // const ifcaRelay = await Relay.connect('wss://hi.myvoiceourstory.org');\n\n const migsRelay = await Relay.connect('wss://notes.miguelalmodo.com');\n console.log(`connected to ${migsRelay.url}`);\n\n\n// store the relay name\n this.relayName = migsRelay.url;\n\n\n const sub = migsRelay.subscribe([\n {\n kinds: [30023], // short and long form notes\n limit: 5,\n }\n ], {\n onevent: async (event) => {\n console.log('Event received:', event);\n this.notes = [...this.notes, {\n content: event.content,\n date: new Date(event.created_at * 1000).toLocaleDateString(),\n }];\n this.requestUpdate();\n console.log(migsRelay)\n\n },\n oneose: () => {\n sub.close();\n this.requestUpdate();\n },\n });\n\n}\n\nasync displayLongNotes() {\n\n}\n\n\n\n\n share() {\n if ((navigator as any).share) {\n (navigator as any).share({\n title: 'Nostr Micro Client',\n text: 'Share this with your homie!',\n url: 'https://miguelalmodo.com/',\n });\n }\n }\n\n render() {\n return html`\n \n
    \n\n
    \n\n
    \n

    Recent Notes from ${this.relayName}

    \n
    \n\n\n\n\n \n ${this.notes.map(note => {\n // extract URL from note content\n const urlMatch = note.content.match(/https?:\\/\\/[^\\s]+/);\n const textContent = note.content.replace(urlMatch?.[0] || '', '').trim();\n\n\n // Check for yt links and extract video ID\n const youtubeRegex = /(?:https?:\\/\\/(?:www\\.)?youtube\\.com\\/watch\\?v=|https?:\\/\\/youtu\\.be\\/)([a-zA-Z0-9_-]{11})/;\n const youtubeMatch = urlMatch?.[0].match(youtubeRegex);\n const youtubeVideoId = youtubeMatch ? youtubeMatch[1] : null;\n\n // build yt thumbnail URL if applicable\n const thumbnailUrl = youtubeVideoId\n ? `https://img.youtube.com/vi/${youtubeVideoId}/maxresdefault.jpg`\n : null;\n\n //check for image links\n const imgRegex = /(https?:\\/\\/[^\\s]+\\.(?:jpg|jpeg|png|gif))/i;\n const imgMatch = urlMatch?.find(url => imgRegex.test(url));\n\n return html`\n \n \n \n \n `;\n })}\n

    ${note.date}

    \n

    ${textContent}

    \n ${thumbnailUrl\n ? html`\"YouTube`\n : imgMatch\n ? html`\"Note`\n : ''}\n
    \n\n\n\n
    \n\n `;\n }\n}\n","const KEY = Symbol.for('app-tools::log::1.x');\n\nglobalThis[KEY] = { \n setDebug, \n debug: 'window' in globalThis ? new URL(window.location.href).searchParams.has('app-tools-debug') : false,\n};\n\n/**\n * @param {boolean} value \n */\nexport function setDebug(value) {\n globalThis[KEY].debug = !!value;\n}\n\n/**\n * @returns {boolean}\n */\nexport function getDebug() {\n return globalThis[KEY].debug;\n}\n\n/**\n * @param {string} action - describing the action\n * @param {*} [data] - any js value\n */\nexport function log(action, data) {\n if(globalThis[KEY].debug) {\n console.groupCollapsed(`[app-tools] ${action}`);\n if(data) {\n console.log(data);\n }\n console.groupEnd();\n }\n}\n\n/**\n * @param {string} title \n * @returns {(action: string, data?: any) => void}\n */\nexport function createLogger(title) {\n return (action, data) => {\n log(`${title}: ${action}`, data);\n }\n}","import { createLogger } from '../utils/log.js';\nconst log = createLogger('router');\n\nclass RouteEvent extends Event {\n /**\n * @param {Context} context \n */\n constructor(context) {\n super('route-changed');\n this.context = context;\n }\n}\n\n/**\n * @typedef {import('./types.js').Plugin} Plugin\n * @typedef {import('./types.js').Context} Context\n * @typedef {import('./types.js').RouteDefinition} RouteDefinition\n * @typedef {import('./types.js').Route} Route\n * @typedef {import('./types.js').Config} Config\n */\n\nexport class Router extends EventTarget {\n context = {\n params: {},\n query: {},\n title: '',\n url: new URL(window.location.href),\n }\n\n /**\n * @param {Config} config \n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {Route[]} */\n this.routes = config.routes.map((route) => {\n const r = /** @type {unknown} */ ({\n ...route,\n // @ts-ignore\n urlPattern: new URLPattern({\n pathname: route.path,\n baseURL: window.location.href,\n search: '*',\n hash: '*',\n }),\n });\n return /** @type {Route} */ (r);\n });\n log('Initialized routes', this.routes);\n\n queueMicrotask(() => {\n this.navigate(new URL(window.location.href), { replace: true });\n });\n window.addEventListener('popstate', this._onPopState);\n window.addEventListener('click', this._onAnchorClick);\n }\n\n uninstall() {\n window.removeEventListener('popstate', this._onPopState);\n window.removeEventListener('click', this._onAnchorClick);\n }\n\n get url() {\n return new URL(window.location.href);\n }\n\n get fallback() {\n return new URL(\n this.config?.fallback || this.baseUrl.href.substring(window.location.origin.length), \n this.baseUrl\n )\n }\n\n get baseUrl() {\n return new URL('./', document.baseURI);\n }\n\n /**\n * @template RenderResult\n */\n render() {\n log(`Rendering route ${this.context.url.pathname}${this.context.url.search}${this.context.url.hash}`, { context: this.context, route: this.route });\n return /** @type {RenderResult} */ (this.route?.render?.(this.context));\n }\n\n /**\n * @private\n * @param {URL} url \n * @returns {Route | null}\n */\n _matchRoute(url) {\n for (const route of this.routes) {\n const match = route.urlPattern.exec(url);\n if (match) {\n const { title } = route;\n const query = Object.fromEntries(new URLSearchParams(url.search)); \n const params = match?.pathname?.groups ?? {};\n this.context = {\n url,\n title: typeof title === 'function' ? title({params, query, url}) : title,\n params,\n query,\n }\n return route;\n }\n }\n log(`No route matched for ${url.pathname}${url.search}${url.hash}`, url);\n return null;\n }\n \n /**\n * @private\n */\n _notifyUrlChanged() {\n this.dispatchEvent(new RouteEvent(this.context));\n }\n\n /**\n * @private\n */\n _onPopState = () => {\n this.navigate(new URL(window.location.href), { backNav: true });\n }\n\n /**\n * @private\n */\n _onAnchorClick = (e) => {\n if (\n e.defaultPrevented ||\n e.button !== 0 ||\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey\n ) {\n return;\n }\n\n const a = e.composedPath().find((el) => el.tagName === 'A');\n if (!a || !a.href) return;\n\n const url = new URL(a.href);\n\n if (this.url.href === url.href) return;\n if (url.host !== window.location.host) return;\n if (a.hasAttribute('download') || a.href.includes('mailto:')) return;\n\n const target = a.getAttribute('target');\n if (target && target !== '' && target !== '_self') return;\n \n e.preventDefault();\n this.navigate(url);\n }\n\n /**\n * @private \n */\n _collectPlugins(route) {\n return [\n ...(this.config?.plugins ?? []), \n ...(route?.plugins ?? []),\n ]\n }\n\n /**\n * @param {string | URL} url The URL to navigate to.\n * @param {{\n * backNav?: boolean,\n * replace?: boolean,\n * }} options options An options object to configure the navigation. The backNav property specifies whether the navigation is a backward navigation, which doesn't push the navigation into browser nav history.\n */\n async navigate(url, options = {}) {\n if (typeof url === 'string') {\n url = new URL(url, this.baseUrl);\n }\n \n let route = this._matchRoute(url) || this._matchRoute(this.fallback);\n log(`Navigating to ${url.pathname}${url.search}${url.hash}`, { context: this.context, route: this.route });\n\n /** @type {Plugin[]} */\n let plugins = this._collectPlugins(route);\n\n for (const plugin of plugins) {\n try {\n const result = await plugin?.shouldNavigate?.(this.context);\n if (result) {\n const condition = await result.condition();\n if (!condition) {\n url = new URL(result.redirect, this.baseUrl);\n route = this._matchRoute(url) || this._matchRoute(this.fallback);\n plugins = this._collectPlugins(route);\n log('Redirecting', { context: this.context, route: this.route });\n }\n }\n } catch(e) {\n log(`Plugin \"${plugin.name}\" error on shouldNavigate hook`, e);\n throw e;\n }\n }\n\n this.route = route;\n\n if (!this.route) {\n throw new Error(`[ROUTER] No route or fallback matched for url ${url}`);\n }\n\n for (const plugin of plugins) {\n try {\n await plugin?.beforeNavigation?.(this.context);\n } catch(e) {\n log(`Plugin \"${plugin.name}\" error on beforeNavigation hook`, e);\n throw e;\n }\n }\n\n if (options?.replace) {\n window.history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`);\n } else if (!options.backNav) {\n window.history.pushState(null, '', `${url.pathname}${url.search}${url.hash}`);\n }\n\n document.title = this.context.title;\n this._notifyUrlChanged();\n\n for (const plugin of plugins) {\n try {\n await plugin?.afterNavigation?.(this.context);\n } catch(e) {\n log(`Plugin \"${plugin.name}\" error on afterNavigation hook`, e);\n throw e;\n }\n }\n }\n}\n","/**\n * @example lazy(() => import('foo'))\n * @param {any} fn\n * @returns {import('../index.js').Plugin}\n */\nexport function lazy(fn) {\n return {\n name: 'lazy',\n beforeNavigation: () => {\n fn();\n }\n }\n}","// docs for router https://github.com/thepassle/app-tools/blob/master/router/README.md\n\nimport { html } from 'lit';\n\nif (!(globalThis as any).URLPattern) {\n await import(\"urlpattern-polyfill\");\n}\n\nimport { Router } from '@thepassle/app-tools/router.js';\nimport { lazy } from '@thepassle/app-tools/router/plugins/lazy.js';\n\n// @ts-ignore\nimport { title } from '@thepassle/app-tools/router/plugins/title.js';\n\nimport './pages/app-home.js';\n\n\nconst baseURL: string = (import.meta as any).env.BASE_URL;\n\nexport const router = new Router({\n routes: [\n {\n path: resolveRouterPath(),\n title: 'Home',\n render: () => html``\n },\n {\n path: resolveRouterPath('about'),\n title: 'About',\n plugins: [\n lazy(() => import('./pages/app-about/app-about.js')),\n ],\n render: () => html``\n },\n {\n path: resolveRouterPath('note-wall'),\n title: 'Note Wall',\n plugins: [\n lazy(() => import('./pages/note-wall.js')),\n ],\n render: () => html``\n },\n {\n path: resolveRouterPath('write'),\n title: 'Write',\n plugins: [\n lazy(() => import('./pages/app-write/app-write.js')),\n ],\n render: () => html``\n },\n ]\n });\n\n // This function will resolve a path with whatever Base URL was passed to the vite build process.\n // Use of this function throughout the starter is not required, but highly recommended, especially if you plan to use GitHub Pages to deploy.\n // If no arg is passed to this function, it will return the base URL.\n\n export function resolveRouterPath(unresolvedPath?: string) {\n var resolvedPath = baseURL;\n if(unresolvedPath) {\n resolvedPath = resolvedPath + unresolvedPath;\n }\n\n return resolvedPath;\n }\n","import { LitElement, css, html } from 'lit';\nimport { property, customElement } from 'lit/decorators.js';\nimport { resolveRouterPath } from '../router';\nimport { Relay } from 'nostr-tools';\nimport { WindowNostr } from 'nostr-tools/nip07';\n\n\nimport '@shoelace-style/shoelace/dist/components/card/card.js';\nimport '@shoelace-style/shoelace/dist/components/button/button.js';\n\nimport { styles } from '../styles/shared-styles';\n\n\ndeclare global {\n interface Window {\n nostr?: WindowNostr;\n }\n}\n\n@customElement('app-home')\nexport class AppHome extends LitElement {\n\n // For more information on using properties and state in lit\n // check out this link https://lit.dev/docs/components/properties/\n @property() message = 'Welcome to my demo!';\n @property({ type: String }) nostrAddy = '';\n @property({ type: String }) bio = '';\n @property({ type: String }) profilePic = '';\n @property({ type: Boolean }) isSignedIn = false;\n @property({ type: String }) publicKey = '';\n\n\n static styles = [\n styles,\n css`\n\n\n\n @media (horizontal-viewport-segments: 2) {\n #welcomeBar {\n flex-direction: row;\n align-items: flex-start;\n justify-content: space-between;\n }\n\n #welcomeCard {\n margin-right: 64px;\n }\n }\n\n /*\n========================================\nProfile Picture Container\n========================================\n*/\n.profile-picture-container {\n display: grid;\n grid-template-columns: 400px 200px;\n grid-template-rows: 250px;\n grid-column-gap: 15px;\n margin-bottom: 12px;\n\n}\n\n.profile-picture-container p {\n margin: 0;\n}\n\n.profile-pic {\n grid-area: 1/1;\n margin-top: 25px;\n margin-left: 100px;\n margin-bottom: 10px;\n border-radius: 50%;\n}\n\n.personal-msg {\n grid-area: 1/2;\n align-content: center;\n align-items: center;\n}\n\n\n\n.nav-button-container {\n justify-self: center;\n align-self: end;\n}\n\n `];\n\n async firstUpdated() {\n // this method is a lifecycle event in lit\n // for more info check out the lit docs https://lit.dev/docs/components/lifecycle/\n console.log('Welcome to my home page');\n }\n\n\n connectedCallback(): void {\n super.connectedCallback();\n\n this.addEventListener('user-state-changed', (event: Event) => {\n const detail = (event as CustomEvent).detail;\n this.nostrAddy = detail.nostrAddy;\n this.bio = detail.bio;\n this.profilePic = detail.profilePic;\n this.isSignedIn = detail.isSignedIn;\n });\n }\n\n\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n window.removeEventListener('profile-updated', this.updateProfileFromEvent.bind(this));\n window.removeEventListener('user-signed-out', this.handlesSignOut.bind(this));\n }\n\n updateProfileFromEvent(event: Event) {\n console.log('Profile updated event received:', (event as CustomEvent).detail);\n\n const detail = (event as CustomEvent).detail;\n this.nostrAddy = detail.nostrAddy;\n this.bio = detail.bio;\n this.profilePic = detail.profilePic;\n this.isSignedIn = true;\n this.requestUpdate();\n }\n\n handlesSignOut() {\n this.profilePic = '';\n this.bio = '';\n this.nostrAddy = 'Guest';\n this.isSignedIn = false;\n this.requestUpdate();\n }\n\n async fetchAndDisplayProfile(pubkey: string) {\n this.nostrAddy = pubkey;\n this.bio = 'Loading profile info...';\n this.profilePic = '/assets/img/loading_pfp.png';\n\n try {\n // Fetch profile metadata from a relay\n const relay = await Relay.connect('wss://notes.miguelalmodo.com'); // Example URL\n const sub = relay.subscribe([{ kinds: [0], authors: [pubkey] }], {\n onevent: (event) => {\n const profileData = JSON.parse(event.content);\n this.nostrAddy = profileData.nip05 || 'No address available';\n this.bio = profileData.about || 'No bio available';\n this.profilePic = profileData.picture || '/assets/img/default_pfp.png';\n this.requestUpdate();\n },\n oneose: () => sub.close(),\n });\n } catch (error) {\n console.error('Error fetching profile:', error);\n this.displayGuestView();\n }\n }\n\n\n displayGuestView() {\n // Set initial values for guest view\n this.nostrAddy = '';\n this.bio = 'Welcome, guest! Please sign in with a browser extension to view your profile.';\n this.profilePic = '/assets/img/default_pfp.png'; // Could be a placeholder image for guests\n this.isSignedIn = false;\n }\n\n\n share() {\n if ((navigator as any).share) {\n (navigator as any).share({\n title: 'A MiggyMofongo Project',\n text: 'This is a personal progressive social web app',\n url: 'https://miguelalmodo.com/dist2',\n });\n }\n }\n\n\n\n\n render() {\n return html`\n \n\n
    \n
    \n \n
    \n

    Welcome to ${this.nostrAddy || 'Guest'}'s Profile

    \n
    \n

    \n You can upgrade your website into\n a micro blog client with a social protocol to do things\n like browse a feed, compose a note, or post to your network.\n\n

    \n\n\n
    \n\"Profile\n\n

    ${this.bio || 'Welcome, guest! Please sign in to view your profile.'}

    \n\n
    \n
    \n About this Web App\n Feed\n Compose a Note\n
    \n ${'share' in navigator\n ? html`\n \n Share this personal website with a friend!\n `\n : null}\n
    \n\n\n\n
    \n
    \n `;\n }\n\n\n\n\n}\n","import { LitElement, css, html } from 'lit';\nimport { property, customElement } from 'lit/decorators.js';\nimport { resolveRouterPath } from '../router';\nimport { Relay } from 'nostr-tools';\n\nimport '@shoelace-style/shoelace/dist/components/button/button.js';\n@customElement('app-header')\nexport class AppHeader extends LitElement {\n @property({ type: String }) title = 'fostr';\n\n @property({ type: Boolean}) enableBack: boolean = false;\n\n @property({ type: String }) nostrAddy = '';\n @property({ type: String }) bio = '';\n @property({ type: String }) profilePic = '';\n @property({ type: Boolean }) isSignedIn = false;\n @property({ type: String }) publicKey = '';\n\n static styles = css`\n header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n background: var(--app-color-primary);\n color: white;\n padding: 12px;\n padding-top: 4px;\n\n position: fixed;\n left: env(titlebar-area-x, 0);\n top: env(titlebar-area-y, 0);\n height: env(titlebar-area-height, 30px);\n width: env(titlebar-area-width, 100%);\n -webkit-app-region: drag;\n }\n\n header h1 {\n margin-top: 0;\n margin-bottom: 0;\n font-size: 12px;\n font-weight: bold;\n }\n\n nav a {\n margin-left: 10px;\n }\n\n #back-button-block {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n }\n\n @media(prefers-color-scheme: light) {\n header {\n color: black;\n }\n\n nav a {\n color: initial;\n }\n }\n `;\n /** the connected callback method one of the lifecycle methods that runs once the element is added\n * to the dom. there is no disconnectedCallback because the header is never removed from the DOM.\n * i centralize state in this component because it's where the sign in and out button resides.\n *\n *\n */\n connectedCallback(): void {\n super.connectedCallback();\n\n // Check for stored pubkey and fetch metadata if available\n const storedPubkey = localStorage.getItem('pubkey');\n if (storedPubkey) {\n this.isSignedIn = true;\n this.fetchProfileMetadata(storedPubkey);\n } else {\n this.displayGuestView();\n }\n }\n\n displayGuestView() {\n // this method displays a guest view when the user is signed out\n this.nostrAddy = '';\n this.bio = 'Welcome, guest! Please sign in with a browser extension to view your profile.';\n this.profilePic = '/public/assets/img/default_pfp.png'; // a placeholder profile picture\n this.isSignedIn = false;\n\n this.dispatchUserStateChanged();\n }\n\n async fetchProfileMetadata(pubkey: string) {\n try {\n const relay = await Relay.connect('wss://notes.miguelalmodo.com');\n const sub = relay.subscribe(\n [{ kinds: [0], authors: [pubkey] }],\n {\n onevent: (event) => {\n const profileData = JSON.parse(event.content);\n this.profilePic = profileData.picture || '/assets/img/default_pfp.png';\n this.nostrAddy = profileData.nip05 || 'no addy available';\n this.bio = profileData.about || 'bio not available';\n\n this.dispatchUserStateChanged();\n },\n oneose: () => sub.close(),\n }\n );\n } catch (error) {\n console.error('Failed to fetch profile metadata:', error);\n this.displayGuestView();\n }\n }\n\n async signInWithNostr() {\n if (window.nostr) {\n try {\n const userPubkey = await window.nostr.getPublicKey();\n this.isSignedIn = true;\n\n //save pubkey in localStorage to keep sign-in state\n localStorage.setItem('pubkey', userPubkey)\n\n await this.fetchProfileMetadata(userPubkey);\n } catch (error) {\n console.error('Failed to sign in:', error);\n this.isSignedIn = false;\n }\n } else {\n alert('Nostr extension not detected. Please install a Nostr extension.');\n }\n }\n\n /* this sign out method clears the public key from local storage and sets the profile view\n back to guest view */\n signOut() {\n localStorage.removeItem('pubkey');\n this.displayGuestView();\n }\n\n dispatchUserStateChanged() {\n this.dispatchEvent(\n new CustomEvent('user-state-changed', {\n detail: {\n isSignedIn: this.isSignedIn,\n nostrAddy: this.nostrAddy,\n bio: this.bio,\n profilePic: this.profilePic,\n },\n bubbles: true,\n composed: true,\n })\n );\n }\n\n render() {\n return html`\n
    \n\n
    \n ${this.enableBack ? html`\n Back\n ` : null}\n\n

    ${this.title}

    \n
    \n\n \n ${this.isSignedIn ? 'Sign out' : 'Sign in'}\n\n \n
    \n `;\n }\n}\n","import { LitElement, css } from 'lit';\nimport { customElement } from 'lit/decorators.js';\n\nimport './pages/note-wall'\nimport './pages/app-home';\nimport './components/header';\nimport './styles/global.css';\nimport { router } from './router';\n\n\n\n@customElement('app-index')\nexport class AppIndex extends LitElement {\n static styles = css`\n main {\n padding-left: 16px;\n padding-right: 16px;\n padding-bottom: 16px;\n }\n `;\n\n firstUpdated() {\n router.addEventListener('route-changed', () => {\n if (\"startViewTransition\" in document) {\n (document as any).startViewTransition(() => this.requestUpdate());\n }\n else {\n this.requestUpdate();\n }\n });\n }\n\n render() {\n // router config can be round in src/router.ts\n return router.render();\n }\n}\n"],"file":"code/index-COc6jZBc.js"} \ No newline at end of file diff --git a/dist2/code/index-DkYRBo1e.css b/dist2/code/index-DkYRBo1e.css new file mode 100644 index 0000000..b21ae66 --- /dev/null +++ b/dist2/code/index-DkYRBo1e.css @@ -0,0 +1 @@ +:root{--font-family: sans-serif}html,body{font-family:var(--font-family);padding:0;margin:0;height:100%}@media (prefers-color-scheme: dark){html,body{background-color:#181818;color:#fff}}@media (prefers-color-scheme: light){html,body{background-color:#f5f5f5;color:#000}} diff --git a/dist2/index.html b/dist2/index.html new file mode 100644 index 0000000..788c860 --- /dev/null +++ b/dist2/index.html @@ -0,0 +1,57 @@ + + + + + + fostr + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dist2/manifest.json b/dist2/manifest.json new file mode 100644 index 0000000..c01cf18 --- /dev/null +++ b/dist2/manifest.json @@ -0,0 +1,86 @@ +{ + "id": "/", + "scope": "/", + "name": "fostr", + "display": "standalone", + "start_url": "/", + "short_name": "starter", + "theme_color": "#E1477E", + "description": "This is a fostr app", + "orientation": "any", + "background_color": "#E1477E", + "related_applications": [], + "prefer_related_applications": false, + "display_override": ["window-controls-overlay"], + "launch_handler": { + "client_mode": "focus-existing" + }, + "icons": [ + { + "src": "assets/icons/512x512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "assets/icons/192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "assets/icons/48x48.png", + "sizes": "48x48", + "type": "image/png" + }, + { + "src": "assets/icons/24x24.png", + "sizes": "24x24", + "type": "image/png" + } + ], + "screenshots": [ + { + "src": "assets/screenshots/screen.png", + "sizes": "1617x1012", + "type": "image/png" + } + ], + "features": [ + "Cross Platform", + "fast", + "simple" + ], + "categories": [ + "social" + ], + "shortcuts": [ + { + "name": "Open About", + "short_name": "About", + "description": "Open the about page", + "url": "/about", + "icons": [{ "src": "assets/icons/192x192.png", "sizes": "192x192" }] + } + ], + "widgets": [ + { + "name": "Starter Widget", + "tag": "starterWidget", + "ms_ac_template": "widget/ac.json", + "data": "widget/data.json", + "description": "A simple widget example from pwa-starter.", + "screenshots": [ + { + "src": "assets/screenshots/widget-screen.png", + "sizes": "500x500", + "label": "Widget screenshot" + } + ], + "icons": [ + { + "src": "assets/icons/48x48.png", + "sizes": "48x48" + } + ] + } + ] +} diff --git a/dist2/staticwebapp.config.json b/dist2/staticwebapp.config.json new file mode 100644 index 0000000..7a4a067 --- /dev/null +++ b/dist2/staticwebapp.config.json @@ -0,0 +1,6 @@ +{ + "navigationFallback": { + "rewrite": "index.html", + "exclude": ["*.{css,js,mjs,ts,png,gif,ico,jpg,svg,json,woff2,ttf}"] + } +} diff --git a/dist2/sw.js b/dist2/sw.js new file mode 100644 index 0000000..7e34861 --- /dev/null +++ b/dist2/sw.js @@ -0,0 +1,2 @@ +importScripts("https://storage.googleapis.com/workbox-cdn/releases/7.3.0/workbox-sw.js");self.addEventListener("widgetinstall",t=>{t.waitUntil(e(t))});self.addEventListener("widgetresume",t=>{t.waitUntil(e(t))});self.addEventListener("widgetclick",t=>{t.action=="updateName"&&t.waitUntil(s(t))});self.addEventListener("widgetuninstall",t=>{});const e=async t=>{const a=t.widget.definition,i={template:JSON.stringify(await(await fetch(a.msAcTemplate)).json()),data:JSON.stringify(await(await fetch(a.data)).json())};await self.widgets.updateByInstanceId(t.instanceId,i)},s=async t=>{const a=t.data.json().name,i=t.widget.definition,n={template:JSON.stringify(await(await fetch(i.msAcTemplate)).json()),data:JSON.stringify({name:a})};await self.widgets.updateByInstanceId(t.instanceId,n)};workbox.precaching.precacheAndRoute([{"revision":"fe970448513b18d0c37b4b671ca94a06","url":"assets/icons/192x192.png"},{"revision":"5b1c195400df0f16c3f6cb2aa4665622","url":"assets/icons/24x24.png"},{"revision":"c3f013b68eae92565e8337ee50472cdc","url":"assets/icons/48x48.png"},{"revision":"e2a009c0f6aaa11d03a8e0728869b583","url":"assets/icons/512x512.png"},{"revision":"d1e55c63934b5f79f366bf723605bc26","url":"assets/icons/casto_kingdom.png"},{"revision":"a80ffffb8d3a555b25a0f19a0a9878f1","url":"assets/icons/icon_192.png"},{"revision":"04fa5b0f5827d885b678f0d131406aab","url":"assets/icons/icon_24.png"},{"revision":"3dbd388868265c8498acfe676ef27811","url":"assets/icons/icon_48.png"},{"revision":"414aacb61ad294e75f267554db7e9368","url":"assets/icons/icon_512.png"},{"revision":"67906584562cfe06b57d99c15a470a8d","url":"assets/img/default_pfp.png"},{"revision":"ee332fabed8b56f4aae86902c18146a2","url":"assets/readme/build-output.png"},{"revision":"be7f5a61d03a119f2e297d15df7dfab2","url":"assets/readme/codespace-button.png"},{"revision":"969196419238157c3d673545c2daed32","url":"assets/readme/copy-starter.png"},{"revision":"65897273261e49c6c9148df875e13e4d","url":"assets/readme/git-clone.png"},{"revision":"cd10ec0be4be4b10195986d075904542","url":"assets/readme/intro.png"},{"revision":"1b40f28a11a334cc90e6802070b9eae1","url":"assets/readme/local-button.png"},{"revision":"184b8b88c43aa759948968f69251200e","url":"assets/readme/new-repo-from-starter.png"},{"revision":"a5a5ef96823c312160626df383d0925d","url":"assets/readme/pwa-running.png"},{"revision":"480b506d1a2a832131525fd4d0fd7478","url":"assets/readme/pwa-starter-overview.png"},{"revision":"865934771530a3b8f9e10aae8d0423d9","url":"assets/readme/static-web-app-slash.png"},{"revision":"2d67dfcbdc3c8c6f8b5fefcd0016021f","url":"assets/readme/use-this-template.png"},{"revision":"fc3d41a79144a5bb00a423b78ec73c1f","url":"assets/readme/vscode-in-browser.png"},{"revision":"808ac8889e4c17f3f83fd9235f1aa28d","url":"assets/screenshots/screen.png"},{"revision":"bd2d64ab3b867df1017d43ec20b73cca","url":"assets/screenshots/widget-screen.png"},{"revision":null,"url":"code/app-about-BGKiJfUr.js"},{"revision":null,"url":"code/app-write-DLE2Mxxa.js"},{"revision":null,"url":"code/index-CBloBB_n.js"},{"revision":null,"url":"code/index-COc6jZBc.js"},{"revision":null,"url":"code/index-DkYRBo1e.css"},{"revision":"f5266149bb7950e2721802c8a674af23","url":"index.html"},{"revision":"288b15a933c65f7ad15d8d4567d18212","url":"manifest.json"},{"revision":"b1a4910d7cbaa47fcc8f72ecb2028ff1","url":"staticwebapp.config.json"},{"revision":"a7591c595c4a231a1f67943e58f3d6eb","url":"widget/ac.json"},{"revision":"a70ebb50d5f5ab6a37f24795e292547d","url":"widget/data.json"}]||[]); +//# sourceMappingURL=sw.js.map diff --git a/dist2/sw.js.map b/dist2/sw.js.map new file mode 100644 index 0000000..796621f --- /dev/null +++ b/dist2/sw.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../public/sw.js"],"names":["event","updateWidget","updateName","widgetDefinition","payload","name"],"mappings":"AAAA,cACI,yEACJ,EAMA,KAAK,iBAAiB,gBAAkB,GAAU,CAC9C,EAAM,UAAU,EAAa,CAAK,CAAC,CACvC,CAAC,EAGD,KAAK,iBAAiB,eAAiB,GAAU,CAC7C,EAAM,UAAU,EAAa,CAAK,CAAC,CACvC,CAAC,EAID,KAAK,iBAAiB,cAAgB,GAAU,CAC5C,EAAM,QAAU,cAChB,EAAM,UAAU,EAAW,CAAK,CAAC,CAErC,CAAC,EAID,KAAK,iBAAiB,kBAAoB,GAAU,CAAA,CAAE,EAEtD,MAAM,EAAe,MAAO,GAAU,CAElC,MAAM,EAAmB,EAAM,OAAO,WAGhC,EAAU,CACZ,SAAU,KAAK,UAAU,MAAO,MAAM,MAAM,EAAiB,YAAY,GAAG,MAAM,EAClF,KAAM,KAAK,UAAU,MAAO,MAAM,MAAM,EAAiB,IAAI,GAAG,MAAM,CACzE,EAGD,MAAM,KAAK,QAAQ,mBAAmB,EAAM,WAAY,CAAO,CACnE,EAEM,EAAa,MAAO,GAAU,CAChC,MAAM,EAAO,EAAM,KAAK,KAAM,EAAC,KAGzB,EAAmB,EAAM,OAAO,WAGhC,EAAU,CACZ,SAAU,KAAK,UAAU,MAAO,MAAM,MAAM,EAAiB,YAAY,GAAG,MAAM,EAClF,KAAM,KAAK,UAAU,CAAC,KAAA,CAAI,CAAC,CAC9B,EAGD,MAAM,KAAK,QAAQ,mBAAmB,EAAM,WAAY,CAAO,CACnE,EAEA,QAAQ,WAAW,iBAAiB,+mFAAK,eAAiB,CAAA,CAAE","file":"sw.js","sourcesContent":["importScripts(\n 'https://storage.googleapis.com/workbox-cdn/releases/7.3.0/workbox-sw.js'\n);\n\n// This is your Service Worker, you can put any of your custom Service Worker\n// code in this file, above the `precacheAndRoute` line.\n\n// When widget is installed/pinned, push initial state.\nself.addEventListener('widgetinstall', (event) => {\n event.waitUntil(updateWidget(event));\n});\n\n// When widget is shown, update content to ensure it is up-to-date.\nself.addEventListener('widgetresume', (event) => {\n event.waitUntil(updateWidget(event));\n});\n\n// When the user clicks an element with an associated Action.Execute,\n// handle according to the 'verb' in event.action.\nself.addEventListener('widgetclick', (event) => {\nif (event.action == \"updateName\") {\n event.waitUntil(updateName(event));\n}\n});\n\n// When the widget is uninstalled/unpinned, clean up any unnecessary\n// periodic sync or widget-related state.\nself.addEventListener('widgetuninstall', (event) => {});\n\nconst updateWidget = async (event) => {\n// The widget definition represents the fields specified in the manifest.\n const widgetDefinition = event.widget.definition;\n\n // Fetch the template and data defined in the manifest to generate the payload.\n const payload = {\n template: JSON.stringify(await (await fetch(widgetDefinition.msAcTemplate)).json()),\n data: JSON.stringify(await (await fetch(widgetDefinition.data)).json()),\n };\n\n // Push payload to widget.\n await self.widgets.updateByInstanceId(event.instanceId, payload);\n}\n\nconst updateName = async (event) => {\n const name = event.data.json().name;\n\n // The widget definition represents the fields specified in the manifest.\n const widgetDefinition = event.widget.definition;\n\n // Fetch the template and data defined in the manifest to generate the payload.\n const payload = {\n template: JSON.stringify(await (await fetch(widgetDefinition.msAcTemplate)).json()),\n data: JSON.stringify({name}),\n };\n\n // Push payload to widget.\n await self.widgets.updateByInstanceId(event.instanceId, payload);\n}\n\nworkbox.precaching.precacheAndRoute(self.__WB_MANIFEST || []);"]} \ No newline at end of file diff --git a/dist2/widget/ac.json b/dist2/widget/ac.json new file mode 100644 index 0000000..7b40171 --- /dev/null +++ b/dist2/widget/ac.json @@ -0,0 +1,24 @@ +{ + "type": "AdaptiveCard", + "body": [ + { + "type": "TextBlock", + "text": "Hello ${$root.name}!", + "wrap": true, + "horizontalAlignment": "Center", + "size": "ExtraLarge" + }, + { + "type": "Input.Text", + "placeholder": "Name", + "id": "name", + "inlineAction": { + "type": "Action.Execute", + "verb": "updateName", + "title": "Submit" + } + } + ], + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "version": "1.6" + } \ No newline at end of file diff --git a/dist2/widget/data.json b/dist2/widget/data.json new file mode 100644 index 0000000..f947112 --- /dev/null +++ b/dist2/widget/data.json @@ -0,0 +1,3 @@ +{ + "name": "Widget" + } \ No newline at end of file diff --git a/src/components/header.ts b/src/components/header.ts index 355abaa..926d590 100644 --- a/src/components/header.ts +++ b/src/components/header.ts @@ -2,7 +2,6 @@ import { LitElement, css, html } from 'lit'; import { property, customElement } from 'lit/decorators.js'; import { resolveRouterPath } from '../router'; import { Relay } from 'nostr-tools'; -import { WindowNostr } from 'nostr-tools/nip07'; import '@shoelace-style/shoelace/dist/components/button/button.js'; @customElement('app-header') diff --git a/src/pages/app-about/app-about.ts b/src/pages/app-about/app-about.ts index cf77e0f..835e7a5 100644 --- a/src/pages/app-about/app-about.ts +++ b/src/pages/app-about/app-about.ts @@ -29,15 +29,15 @@ export class AppAbout extends LitElement {

    This is a personal micro-social media client that can be installed to your desktop or smartphone home screen. You can sign in via an extension - to display your profile data and notes from preprogrammed relays. You - can compose a letter to me using a rich text editor I built with Prosemirror. + to display your profile data and notes from my relay. You + can compose a note using a rich text editor I built with Prosemirror.

    How do I install this on my home screen?

    -

    Look for "Add to Home Screen" in your browser toolbar and - to save it to your homescreen.

    +

    Look for "Add to Home Screen" in your browser toolbar + to install it to your homescreen.

    What is Nostr?

    Notes and Other Stuff Transmitted Over Relays is a simple open source diff --git a/src/pages/app-home.ts b/src/pages/app-home.ts index 9aaa88d..449afd8 100644 --- a/src/pages/app-home.ts +++ b/src/pages/app-home.ts @@ -22,7 +22,7 @@ export class AppHome extends LitElement { // For more information on using properties and state in lit // check out this link https://lit.dev/docs/components/properties/ - @property() message = 'Welcome to my nostr demo!'; + @property() message = 'Welcome to my demo!'; @property({ type: String }) nostrAddy = ''; @property({ type: String }) bio = ''; @property({ type: String }) profilePic = ''; @@ -55,7 +55,7 @@ Profile Picture Container */ .profile-picture-container { display: grid; - grid-template-columns: 300px 150px; + grid-template-columns: 400px 200px; grid-template-rows: 250px; grid-column-gap: 15px; margin-bottom: 12px; @@ -68,20 +68,21 @@ Profile Picture Container .profile-pic { grid-area: 1/1; - margin-top: 10px; + margin-top: 25px; + margin-left: 100px; margin-bottom: 10px; border-radius: 50%; } .personal-msg { grid-area: 1/2; - margin-top: 300px; + align-content: center; + align-items: center; } -.pics-videos { - grid-area: 1/1; +.nav-button-container { justify-self: center; align-self: end; } @@ -171,9 +172,9 @@ Profile Picture Container share() { if ((navigator as any).share) { (navigator as any).share({ - title: 'PWABuilder pwa-starter', - text: 'Check out the PWABuilder pwa-starter!', - url: 'https://github.com/pwa-builder/pwa-starter', + title: 'A MiggyMofongo Project', + text: 'This is a personal progressive social web app', + url: 'https://miguelalmodo.com/dist2', }); } } @@ -192,9 +193,9 @@ Profile Picture Container

    Welcome to ${this.nostrAddy || 'Guest'}'s Profile

    - You can use the Nostr protocol to transform your personal website into - a micro blog client. You can compose a note and post it to your social - network. + You can upgrade your website into + a micro blog client with a social protocol to do things + like browse a feed, compose a note, or post to your network.

    @@ -205,18 +206,20 @@ Profile Picture Container

    ${this.bio || 'Welcome, guest! Please sign in to view your profile.'}

    - + ${'share' in navigator ? html` - Share this Starter! + Share this personal website with a friend! ` : null} - Navigate to About - Navigate to Note Wall - Navigate to Note Compose + diff --git a/src/pages/app-write/app-write.ts b/src/pages/app-write/app-write.ts index 2634149..9cd1b76 100644 --- a/src/pages/app-write/app-write.ts +++ b/src/pages/app-write/app-write.ts @@ -154,7 +154,7 @@ export class AppWrite extends LitElement { all: unset; /* Remove inherited or conflicting styles */ font-weight: bold; text-transform: uppercase; - color: red; /* Add a visible color for debugging */ + color: red; } ` @@ -172,14 +172,29 @@ private initializeEditor() { console.error('Editor container not here'); return } - const doc = customSchema.nodes.doc.createAndFill(); - if (!doc) { + const initialContent = customSchema.nodes.doc.createAndFill([ + customSchema.nodes.paragraph.create( + null, + customSchema.text("Welcome to the editor! Try typing here.") + ), + customSchema.nodes.paragraph.create( + null, + customSchema.text("Press Ctrl+Space to insert a ⭐.") + ), + customSchema.nodes.paragraph.create( + null, + customSchema.text("Highlight text and press Ctrl+B to SHOUT it!") + ), + ]); + + + if (!initialContent) { console.error("failed to create initial document") return; } const state = EditorState.create({ - doc, + doc: initialContent, plugins: [ menuPlugin, history(), @@ -243,14 +258,15 @@ private initializeEditor() { -

    Basic Intructions

    -

    click inside the white text area to highlight with your cursor. - You can type and press enter to insert a new block below. +

    Instructions

    +

    Click inside the white text area to highlight with your cursor. + You can type and press enter to insert a new block below.


    - Highlight a piece of text, then CTRL+X to cut and CTRL+V to paste.
    - Press Ctrl+Space to add a yellow star to the document. Press - Ctrl+B over a highlighted selection to add the "shouting" mark, making - it all caps and red.

    +

    Try to highlight a piece of text, then CTRL+X to cut and + CTRL+V to paste.


    +

    Press Ctrl+Space to add a yellow star to the document.

    +

    Press Ctrl+B over a highlighted selection to add a "shouting" + mark and format it all caps and red.