@woven-canvas/vue 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/build/index.js +9141 -8651
  2. package/build/index.umd.cjs +41 -40
  3. package/build/src/components/ActionBar.vue.d.ts +3 -0
  4. package/build/src/components/ActionBar.vue.d.ts.map +1 -0
  5. package/build/src/components/EditableText.vue.d.ts +0 -1
  6. package/build/src/components/EditableText.vue.d.ts.map +1 -1
  7. package/build/src/components/FileDropZone.vue.d.ts +8 -0
  8. package/build/src/components/FileDropZone.vue.d.ts.map +1 -0
  9. package/build/src/components/FloatingMenu.vue.d.ts.map +1 -1
  10. package/build/src/components/FloatingMenuBar.vue.d.ts.map +1 -1
  11. package/build/src/components/Toolbar.vue.d.ts +4 -2
  12. package/build/src/components/Toolbar.vue.d.ts.map +1 -1
  13. package/build/src/components/WovenCanvas.vue.d.ts +1 -0
  14. package/build/src/components/WovenCanvas.vue.d.ts.map +1 -1
  15. package/build/src/components/blocks/ShapeBlock.vue.d.ts.map +1 -1
  16. package/build/src/components/blocks/StickyNote.vue.d.ts.map +1 -1
  17. package/build/src/components/blocks/TextBlock.vue.d.ts.map +1 -1
  18. package/build/src/components/buttons/MenuDropdown.vue.d.ts.map +1 -1
  19. package/build/src/components/buttons/text/TextButtonGroup.vue.d.ts +8 -0
  20. package/build/src/components/buttons/text/TextButtonGroup.vue.d.ts.map +1 -0
  21. package/build/src/components/buttons/text/index.d.ts +2 -0
  22. package/build/src/components/buttons/text/index.d.ts.map +1 -1
  23. package/build/src/components/tools/ImageTool.vue.d.ts.map +1 -1
  24. package/build/src/composables/index.d.ts +1 -0
  25. package/build/src/composables/index.d.ts.map +1 -1
  26. package/build/src/composables/useImageCreation.d.ts +13 -0
  27. package/build/src/composables/useImageCreation.d.ts.map +1 -0
  28. package/build/src/composables/useTextBatchController.d.ts.map +1 -1
  29. package/build/src/injection/dropdown.d.ts +4 -0
  30. package/build/src/injection/dropdown.d.ts.map +1 -0
  31. package/build/src/injection/index.d.ts +1 -0
  32. package/build/src/injection/index.d.ts.map +1 -1
  33. package/build/style.css +1 -1
  34. package/build/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +5 -5
  36. package/src/theme.css +8 -0
@@ -1,44 +1,44 @@
1
- (function(R,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],f):(R=typeof globalThis<"u"?globalThis:R||self,f(R.Vue={},R.Vue))})(this,function(R,f){"use strict";var XL=Object.defineProperty;var GL=(R,f,Rr)=>f in R?XL(R,f,{enumerable:!0,configurable:!0,writable:!0,value:Rr}):R[f]=Rr;var C=(R,f,Rr)=>GL(R,typeof f!="symbol"?f+"":f,Rr);var cr,Nr,Dr,Mn,ns,rs,ss,Bt,Ne,is,ur;const Rr=(t,e)=>e.some(n=>t instanceof n);let Jf,Xf;function Pv(){return Jf||(Jf=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Nv(){return Xf||(Xf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const vc=new WeakMap,bc=new WeakMap,sa=new WeakMap;function Dv(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(vo(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return sa.set(e,t),e}function Ov(t){if(vc.has(t))return;const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",i),t.removeEventListener("abort",i)},s=()=>{n(),o()},i=()=>{r(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",s),t.addEventListener("error",i),t.addEventListener("abort",i)});vc.set(t,e)}let Sc={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return vc.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return vo(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function Gf(t){Sc=t(Sc)}function Rv(t){return Nv().includes(t)?function(...e){return t.apply(Ec(this),e),vo(this.request)}:function(...e){return vo(t.apply(Ec(this),e))}}function zv(t){return typeof t=="function"?Rv(t):(t instanceof IDBTransaction&&Ov(t),Rr(t,Pv())?new Proxy(t,Sc):t)}function vo(t){if(t instanceof IDBRequest)return Dv(t);if(bc.has(t))return bc.get(t);const e=zv(t);return e!==t&&(bc.set(t,e),sa.set(e,t)),e}const Ec=t=>sa.get(t);function Qf(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=vo(i);return r&&i.addEventListener("upgradeneeded",l=>{r(vo(i.result),l.oldVersion,l.newVersion,vo(i.transaction),l)}),n&&i.addEventListener("blocked",l=>n(l.oldVersion,l.newVersion,l)),a.then(l=>{s&&l.addEventListener("close",()=>s()),o&&l.addEventListener("versionchange",c=>o(c.oldVersion,c.newVersion,c))}).catch(()=>{}),a}const $v=["get","getKey","getAll","getAllKeys","count"],Lv=["put","add","delete","clear"],Cc=new Map;function eh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Cc.get(e))return Cc.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=Lv.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||$v.includes(n)))return;const s=async function(i,...a){const l=this.transaction(i,o?"readwrite":"readonly");let c=l.store;return r&&(c=c.index(a.shift())),(await Promise.all([c[n](...a),o&&l.done]))[0]};return Cc.set(e,s),s}Gf(t=>({...t,get:(e,n,r)=>eh(e,n)||t.get(e,n,r),has:(e,n)=>!!eh(e,n)||t.has(e,n)}));const Fv=["continue","continuePrimaryKey","advance"],th={},xc=new WeakMap,nh=new WeakMap,Vv={get(t,e){if(!Fv.includes(e))return t[e];let n=th[e];return n||(n=th[e]=function(...r){xc.set(this,nh.get(this)[e](...r))}),n}};async function*Wv(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;e=e;const n=new Proxy(e,Vv);for(nh.set(n,e),sa.set(n,Ec(e));e;)yield n,e=await(xc.get(n)||e.continue()),xc.delete(n)}function rh(t,e){return e===Symbol.asyncIterator&&Rr(t,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&Rr(t,[IDBIndex,IDBObjectStore])}Gf(t=>({...t,get(e,n,r){return rh(e,n)?Wv:t.get(e,n,r)},has(e,n){return rh(e,n)||t.has(e,n)}}));var Zt=Symbol("schemaDefault"),dr=class{},Uv=new Set(["string","number","boolean","binary"]);function oh(t,e){const n=t.def.type;if(!Uv.has(n))throw new Error(`Invalid ${e} element type: "${n}". Only primitive types are allowed: string, number, boolean, binary. Nested ${e}s, tuples, arrays, enums, and refs are not supported.`)}var Hv=class extends dr{constructor(){super(...arguments);C(this,"def",{type:"string"})}max(e){return this.def.maxLength=e,this}default(e){return this.def.default=e,this}[Zt](){return this.def.default??""}},zr=class extends dr{constructor(e){super();C(this,"def");this.def={type:"number",btype:e}}default(e){return this.def.default=e,this}[Zt](){return this.def.default??0}},jv=class extends dr{constructor(){super(...arguments);C(this,"def",{type:"boolean"})}default(e){return this.def.default=e,this}[Zt](){return this.def.default??!1}},Zv=class extends dr{constructor(){super(...arguments);C(this,"def",{type:"binary"})}max(e){return this.def.maxLength=e,this}default(e){return this.def.default=e,this}[Zt](){return this.def.default??new Uint8Array(0)}},Kv=class extends dr{constructor(e,n){super();C(this,"def");oh(e,"array"),this.def={type:"array",elementDef:e.def,maxLength:n}}default(e){return this.def.default=e,this}[Zt](){return this.def.default??[]}},Yv=class extends dr{constructor(e,n){super();C(this,"def");C(this,"elementBuilder");oh(e,"tuple"),this.elementBuilder=e,this.def={type:"tuple",elementDef:e.def,length:n}}default(e){return this.def.default=e,this}[Zt](){if(this.def.default)return this.def.default;const e=this.elementBuilder[Zt]();return new Array(this.def.length).fill(e)}},qv=class extends dr{constructor(e){super();C(this,"def");this.def={type:"buffer",elementDef:e.def,size:0}}size(e){return this.def.size=e,this}default(e){return this.def.default=e,this}[Zt](){return this.def.default??new Array(this.def.size).fill(0)}},Jv=class extends dr{constructor(e){super();C(this,"def");this.def={type:"enum",values:Object.values(e)}}default(e){return this.def.default=e,this}[Zt](){return this.def.default!==void 0?this.def.default:[...this.def.values].sort()[0]}},Xv=class extends dr{constructor(){super(...arguments);C(this,"def",{type:"ref"})}[Zt](){return null}},E={string:()=>new Hv,uint8:()=>new zr("uint8"),uint16:()=>new zr("uint16"),uint32:()=>new zr("uint32"),int8:()=>new zr("int8"),int16:()=>new zr("int16"),int32:()=>new zr("int32"),float32:()=>new zr("float32"),float64:()=>new zr("float64"),boolean:()=>new jv,binary:()=>new Zv,enum:t=>new Jv(t),array:(t,e)=>new Kv(t,e),tuple:(t,e)=>new Yv(t,e),buffer:t=>new qv(t),ref:()=>new Xv},fr=class{constructor(t){C(this,"fieldDef");this.fieldDef=t}getDefaultValue(){return this.fieldDef.schemaDefault}};function as(t){switch(t){case"uint8":case"int8":return 1;case"uint16":case"int16":return 2;case"uint32":case"int32":case"float32":return 4;case"float64":return 8}}function Gv(t,e,n){switch(t){case"uint8":return new Uint8Array(n,0,e);case"uint16":return new Uint16Array(n,0,e);case"uint32":return new Uint32Array(n,0,e);case"int8":return new Int8Array(n,0,e);case"int16":return new Int16Array(n,0,e);case"int32":return new Int32Array(n,0,e);case"float32":return new Float32Array(n,0,e);case"float64":return new Float64Array(n,0,e)}}function Qv(t){return t!=="float32"&&t!=="float64"}var eb=class extends fr{constructor(e){super(e);C(this,"useAtomics");this.useAtomics=Qv(e.btype)}initializeStorage(e,n){const r=as(this.fieldDef.btype),o=new n(e*r),s=Gv(this.fieldDef.btype,e,o);return{buffer:o,view:s}}defineReadonly(e,n,r,o){const s=this.useAtomics;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n];return s?Atomics.load(i,o()):i[o()]}})}defineWritable(e,n,r,o){const s=this.useAtomics;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n];return s?Atomics.load(i,o()):i[o()]},set:i=>{const a=r[n];s?Atomics.store(a,o(),i):a[o()]=i}})}setValue(e,n,r){this.useAtomics?Atomics.store(e,n,r):e[n]=r}},tb=512,nb=256,sh=new TextEncoder,ih=new TextDecoder;function ah(t){switch(t.type){case"number":return as(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||tb;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||nb;return Math.ceil((e+4)/4)*4}}}function ia(t,e,n,r){switch(t){case"float32":return new Float32Array(n,r,e);case"float64":return new Float64Array(n,r,e);case"int8":return new Int8Array(n,r,e);case"int16":return new Int16Array(n,r,e);case"int32":return new Int32Array(n,r,e);case"uint8":return new Uint8Array(n,r,e);case"uint16":return new Uint16Array(n,r,e);case"uint32":return new Uint32Array(n,r,e);default:throw new Error(`Unknown btype: ${t}`)}}var lh=(cr=class{constructor(e,n,r,o,s){C(this,"buffer");C(this,"uint8View");C(this,"bytesPerEntry");C(this,"bytesPerElement");C(this,"capacity");C(this,"elementDef");C(this,"maxLength");this.buffer=e,this.uint8View=new Uint8Array(e),this.bytesPerEntry=r,this.bytesPerElement=ah(o),this.capacity=n,this.elementDef=o,this.maxLength=s}get length(){return this.capacity}readUint32(e){const n=Atomics.load(this.uint8View,e),r=Atomics.load(this.uint8View,e+1),o=Atomics.load(this.uint8View,e+2),s=Atomics.load(this.uint8View,e+3);return n|r<<8|o<<16|s<<24}writeUint32(e,n){Atomics.store(this.uint8View,e,n&255),Atomics.store(this.uint8View,e+1,n>>8&255),Atomics.store(this.uint8View,e+2,n>>16&255),Atomics.store(this.uint8View,e+3,n>>24&255)}get(e){const n=e*this.bytesPerEntry,r=this.readUint32(n);if(r===0)return[];const o=n+cr.LENGTH_BYTES,s=[];switch(this.elementDef.type){case"number":{const i=ia(this.elementDef.btype,r,this.buffer,o),a=this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64";for(let l=0;l<r;l++)a?s.push(Atomics.load(i,l)):s.push(i[l]);break}case"boolean":{for(let i=0;i<r;i++)s.push(Atomics.load(this.uint8View,o+i)!==0);break}case"string":{for(let i=0;i<r;i++){const a=o+i*this.bytesPerElement,l=this.readUint32(a);if(l===0)s.push("");else{const c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=Atomics.load(this.uint8View,a+4+u);s.push(ih.decode(c))}}break}case"binary":{for(let i=0;i<r;i++){const a=o+i*this.bytesPerElement,l=this.readUint32(a);if(l===0)s.push(new Uint8Array(0));else{const c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=Atomics.load(this.uint8View,a+4+u);s.push(c)}}break}}return s}set(e,n){const r=e*this.bytesPerEntry,o=Math.min(n.length,this.maxLength);this.writeUint32(r,o);const s=r+cr.LENGTH_BYTES,i=this.maxLength*this.bytesPerElement;for(let a=0;a<i;a++)Atomics.store(this.uint8View,s+a,0);if(o!==0)switch(this.elementDef.type){case"number":{const a=ia(this.elementDef.btype,o,this.buffer,s),l=this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64";for(let c=0;c<o;c++)l?Atomics.store(a,c,n[c]):a[c]=n[c];break}case"boolean":{for(let a=0;a<o;a++)Atomics.store(this.uint8View,s+a,n[a]?1:0);break}case"string":{const a=this.bytesPerElement-4;for(let l=0;l<o;l++){const c=s+l*this.bytesPerElement,u=n[l],d=sh.encode(u),h=Math.min(d.length,a);this.writeUint32(c,h);for(let p=0;p<h;p++)Atomics.store(this.uint8View,c+4+p,d[p])}break}case"binary":{const a=this.bytesPerElement-4;for(let l=0;l<o;l++){const c=s+l*this.bytesPerElement,u=n[l],d=Math.min(u.length,a);this.writeUint32(c,d);for(let h=0;h<d;h++)Atomics.store(this.uint8View,c+4+h,u[h])}break}}}getElement(e,n){const r=e*this.bytesPerEntry,o=this.readUint32(r);if(n<0||n>=o)return;const s=r+cr.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const i=ia(this.elementDef.btype,o,this.buffer,s);return this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64"?Atomics.load(i,n):i[n]}case"boolean":return Atomics.load(this.uint8View,s+n)!==0;case"string":{const i=s+n*this.bytesPerElement,a=this.readUint32(i);if(a===0)return"";const l=new Uint8Array(a);for(let c=0;c<a;c++)l[c]=Atomics.load(this.uint8View,i+4+c);return ih.decode(l)}case"binary":{const i=s+n*this.bytesPerElement,a=this.readUint32(i);if(a===0)return new Uint8Array(0);const l=new Uint8Array(a);for(let c=0;c<a;c++)l[c]=Atomics.load(this.uint8View,i+4+c);return l}}}setElement(e,n,r){if(n<0||n>=this.maxLength)return;const o=e*this.bytesPerEntry;let s=this.readUint32(o);n>=s&&(s=n+1,this.writeUint32(o,s));const i=o+cr.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const a=ia(this.elementDef.btype,this.maxLength,this.buffer,i);this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64"?Atomics.store(a,n,r):a[n]=r;break}case"boolean":{Atomics.store(this.uint8View,i+n,r?1:0);break}case"string":{const a=i+n*this.bytesPerElement,l=r,c=sh.encode(l),u=this.bytesPerElement-4,d=Math.min(c.length,u);for(let h=0;h<u;h++)Atomics.store(this.uint8View,a+4+h,0);this.writeUint32(a,d);for(let h=0;h<d;h++)Atomics.store(this.uint8View,a+4+h,c[h]);break}case"binary":{const a=i+n*this.bytesPerElement,l=r,c=this.bytesPerElement-4,u=Math.min(l.length,c);for(let d=0;d<c;d++)Atomics.store(this.uint8View,a+4+d,0);this.writeUint32(a,u);for(let d=0;d<u;d++)Atomics.store(this.uint8View,a+4+d,l[d]);break}}}getStoredLength(e){const n=e*this.bytesPerEntry;return this.readUint32(n)}getMaxLength(){return this.maxLength}getBuffer(){return this.buffer}getBytesPerEntry(){return this.bytesPerEntry}},C(cr,"LENGTH_BYTES",4),cr),rb=class extends fr{initializeStorage(t,e){const n=ah(this.fieldDef.elementDef),r=this.fieldDef.maxLength*n+lh.LENGTH_BYTES,o=Math.ceil(r/8)*8,s=new e(t*o),i=new lh(s,t,o,this.fieldDef.elementDef,this.fieldDef.maxLength);return{buffer:s,view:i}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>{const o=n[e],s=r(),i=new Set(["push","pop","shift","unshift","splice","reverse","sort","fill","copyWithin"]);return new Proxy([],{get(a,l){if(typeof l=="string"&&/^\d+$/.test(l)){const d=parseInt(l,10);return o.getElement(s,d)}if(l==="length")return o.getStoredLength(s);if(typeof l=="string"&&i.has(l))return(...d)=>{const h=o.get(s),p=h[l](...d);return o.set(s,h),p};const c=o.get(s),u=c[l];return typeof u=="function"?u.bind(c):u},set(a,l,c){if(typeof l=="string"&&/^\d+$/.test(l)){const u=parseInt(l,10);return o.setElement(s,u,c),!0}return!1},has(a,l){if(typeof l=="string"&&/^\d+$/.test(l)){const c=parseInt(l,10);return c>=0&&c<o.getStoredLength(s)}return l in[]},ownKeys(){const a=o.getStoredLength(s),l=[];for(let c=0;c<a;c++)l.push(String(c));return l.push("length"),l},getOwnPropertyDescriptor(a,l){if(typeof l=="string"&&/^\d+$/.test(l)){const c=parseInt(l,10);if(c>=0&&c<o.getStoredLength(s))return{value:o.getElement(s,c),writable:!0,enumerable:!0,configurable:!0}}if(l==="length")return{value:o.getStoredLength(s),writable:!1,enumerable:!1,configurable:!1}}})},set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){t.set(e,n)}},ob=256,ch=(Nr=class{constructor(e,n,r){C(this,"buffer");C(this,"bytesPerEntry");C(this,"capacity");this.buffer=new Uint8Array(e),this.bytesPerEntry=r,this.capacity=n}get length(){return this.capacity}get(e){const n=e*this.bytesPerEntry,r=Atomics.load(this.buffer,n),o=Atomics.load(this.buffer,n+1),s=Atomics.load(this.buffer,n+2),i=Atomics.load(this.buffer,n+3),a=r|o<<8|s<<16|i<<24;if(a===0)return new Uint8Array(0);const l=n+Nr.LENGTH_BYTES,c=new Uint8Array(a);for(let u=0;u<a;u++)c[u]=Atomics.load(this.buffer,l+u);return c}set(e,n){const r=e*this.bytesPerEntry,o=this.bytesPerEntry-Nr.LENGTH_BYTES,s=Math.min(n.length,o);Atomics.store(this.buffer,r,s&255),Atomics.store(this.buffer,r+1,s>>8&255),Atomics.store(this.buffer,r+2,s>>16&255),Atomics.store(this.buffer,r+3,s>>24&255);const i=r+Nr.LENGTH_BYTES;for(let a=0;a<o;a++)Atomics.store(this.buffer,i+a,0);for(let a=0;a<s;a++)Atomics.store(this.buffer,i+a,n[a])}getBuffer(){return this.buffer}},C(Nr,"LENGTH_BYTES",4),Nr),sb=class extends fr{initializeStorage(t,e){const r=(this.fieldDef.maxLength||ob)+ch.LENGTH_BYTES,o=new e(t*r),s=new ch(o,t,r);return{buffer:o,view:s}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){t.set(e,n)}},ib=class extends fr{initializeStorage(t,e){const n=new e(t),r=new Uint8Array(n,0,t);return{buffer:n,view:r}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>{const o=n[e];return!!Atomics.load(o,r())}})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>{const o=n[e];return!!Atomics.load(o,r())},set:o=>{const s=n[e];Atomics.store(s,r(),o?1:0)}})}setValue(t,e,n){Atomics.store(t,e,n?1:0)}};function ab(t,e,n,r){switch(t){case"float32":return new Float32Array(n,r,e);case"float64":return new Float64Array(n,r,e);case"int8":return new Int8Array(n,r,e);case"int16":return new Int16Array(n,r,e);case"int32":return new Int32Array(n,r,e);case"uint8":return new Uint8Array(n,r,e);case"uint16":return new Uint16Array(n,r,e);case"uint32":return new Uint32Array(n,r,e);default:throw new Error(`Unknown btype: ${t}`)}}var lb=class{constructor(t,e,n,r,o){C(this,"buffer");C(this,"bytesPerEntry");C(this,"bytesPerElement");C(this,"capacity");C(this,"bufferSize");C(this,"numberTypedArray");C(this,"elementsPerEntry");this.buffer=t,this.bytesPerEntry=n,this.bytesPerElement=as(r.btype),this.capacity=e,this.bufferSize=o,this.elementsPerEntry=n/this.bytesPerElement,this.numberTypedArray=ab(r.btype,e*this.elementsPerEntry,t,0)}get length(){return this.capacity}get(t){const e=t*this.elementsPerEntry;return this.numberTypedArray.subarray(e,e+this.bufferSize)}set(t,e){const n=t*this.elementsPerEntry,r=Math.min(e.length,this.bufferSize);for(let o=0;o<r;o++)this.numberTypedArray[n+o]=e[o];for(let o=r;o<this.bufferSize;o++)this.numberTypedArray[n+o]=0}getBuffer(){return this.buffer}getBytesPerEntry(){return this.bytesPerEntry}getSize(){return this.bufferSize}},cb=class extends fr{initializeStorage(t,e){const n=as(this.fieldDef.elementDef.btype),r=this.fieldDef.size*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new lb(s,t,o,this.fieldDef.elementDef,this.fieldDef.size);return{buffer:s,view:i}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){if(n&&typeof n=="object"&&!Array.isArray(n)&&n.length===void 0){const r=[];let o=0;for(;o in n;)r.push(n[o]),o++;n=r}t.set(e,n??[])}},ub=class extends fr{constructor(e){super(e);C(this,"sortedValues");C(this,"valueToIndex");this.sortedValues=[...e.values].sort(),this.valueToIndex=new Map,this.sortedValues.forEach((n,r)=>{this.valueToIndex.set(n,r)})}initializeStorage(e,n){const r=new n(e*2),o=new Uint16Array(r);return{buffer:r,view:o}}defineReadonly(e,n,r,o){const s=this.sortedValues;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n],a=Atomics.load(i,o());return s[a]??s[0]??""}})}defineWritable(e,n,r,o){const s=this.sortedValues,i=this.valueToIndex;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const a=r[n],l=Atomics.load(a,o());return s[l]??s[0]??""},set:a=>{const l=r[n],c=i.get(a);c!==void 0&&Atomics.store(l,o(),c)}})}setValue(e,n,r){if(typeof r=="string"){const o=this.valueToIndex.get(r);Atomics.store(e,n,o!==void 0?o:0)}else Atomics.store(e,n,r)}},Yn=4294967295,uh=33554431,dh=25;function fh(t,e){return t&uh|e<<dh}function db(t){return t&uh}function fb(t){return t>>>dh}function Tc(t,e,n=!0){if(t===Yn)return null;const r=db(t),o=fb(t);return n&&!e.has(r)||e.getGeneration(r)!==o?null:r}var hb=class extends fr{constructor(e,n){super(e);C(this,"entityBuffer");this.entityBuffer=n}initializeStorage(e,n){const r=new n(e*4),o=new Uint32Array(r);return o.fill(Yn),{buffer:r,view:o}}defineReadonly(e,n,r,o){const s=this.entityBuffer;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n],a=o(),l=Atomics.load(i,a),c=Tc(l,s);return l!==Yn&&c===null&&Atomics.store(i,a,Yn),c}})}defineWritable(e,n,r,o){const s=this.entityBuffer;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n],a=o(),l=Atomics.load(i,a),c=Tc(l,s);return l!==Yn&&c===null&&Atomics.store(i,a,Yn),c},set:i=>{const a=r[n],l=o();if(i===null||i===Yn)Atomics.store(a,l,Yn);else{const c=s.getGeneration(i);Atomics.store(a,l,fh(i,c))}}})}setValue(e,n,r){if(r===null||r===Yn)Atomics.store(e,n,Yn);else{const o=this.entityBuffer.getGeneration(r);Atomics.store(e,n,fh(r,o))}}},pb=512,mb=new TextEncoder,gb=new TextDecoder,hh=(Dr=class{constructor(e,n,r){C(this,"buffer");C(this,"bytesPerString");C(this,"capacity");this.buffer=new Uint8Array(e),this.bytesPerString=r,this.capacity=n}get length(){return this.capacity}get(e){const n=e*this.bytesPerString,r=Atomics.load(this.buffer,n),o=Atomics.load(this.buffer,n+1),s=Atomics.load(this.buffer,n+2),i=Atomics.load(this.buffer,n+3),a=r|o<<8|s<<16|i<<24;if(a===0)return"";const l=n+Dr.LENGTH_BYTES,c=new Uint8Array(a);for(let u=0;u<a;u++)c[u]=Atomics.load(this.buffer,l+u);return gb.decode(c)}set(e,n){const r=e*this.bytesPerString,o=mb.encode(n),s=this.bytesPerString-Dr.LENGTH_BYTES,i=Math.min(o.length,s);Atomics.store(this.buffer,r,i&255),Atomics.store(this.buffer,r+1,i>>8&255),Atomics.store(this.buffer,r+2,i>>16&255),Atomics.store(this.buffer,r+3,i>>24&255);const a=r+Dr.LENGTH_BYTES;for(let l=0;l<s;l++)Atomics.store(this.buffer,a+l,0);for(let l=0;l<i;l++)Atomics.store(this.buffer,a+l,o[l])}getBuffer(){return this.buffer}},C(Dr,"LENGTH_BYTES",4),Dr),yb=class extends fr{initializeStorage(t,e){const r=(this.fieldDef.maxLength||pb)+hh.LENGTH_BYTES,o=new e(t*r),s=new hh(o,t,r);return{buffer:o,view:s}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){t.set(e,n)}},wb=512,kb=256,vb=new TextEncoder,bb=new TextDecoder;function ph(t){switch(t.type){case"number":return as(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||wb;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||kb;return Math.ceil((e+4)/4)*4}}}function Sb(t,e,n,r){switch(t){case"float32":return new Float32Array(n,r,e);case"float64":return new Float64Array(n,r,e);case"int8":return new Int8Array(n,r,e);case"int16":return new Int16Array(n,r,e);case"int32":return new Int32Array(n,r,e);case"uint8":return new Uint8Array(n,r,e);case"uint16":return new Uint16Array(n,r,e);case"uint32":return new Uint32Array(n,r,e);default:throw new Error(`Unknown btype: ${t}`)}}var Eb=class{constructor(t,e,n,r,o){C(this,"buffer");C(this,"uint8View");C(this,"bytesPerEntry");C(this,"bytesPerElement");C(this,"capacity");C(this,"elementDef");C(this,"tupleLength");C(this,"numberTypedArray",null);C(this,"elementsPerEntry",0);if(this.buffer=t,this.uint8View=new Uint8Array(t),this.bytesPerEntry=n,this.bytesPerElement=ph(r),this.capacity=e,this.elementDef=r,this.tupleLength=o,r.type==="number"){const s=as(r.btype);this.elementsPerEntry=n/s,this.numberTypedArray=Sb(r.btype,e*this.elementsPerEntry,t,0)}}get length(){return this.capacity}readUint32(t){const e=Atomics.load(this.uint8View,t),n=Atomics.load(this.uint8View,t+1),r=Atomics.load(this.uint8View,t+2),o=Atomics.load(this.uint8View,t+3);return e|n<<8|r<<16|o<<24}writeUint32(t,e){Atomics.store(this.uint8View,t,e&255),Atomics.store(this.uint8View,t+1,e>>8&255),Atomics.store(this.uint8View,t+2,e>>16&255),Atomics.store(this.uint8View,t+3,e>>24&255)}get(t){if(this.numberTypedArray!==null){const r=t*this.elementsPerEntry;return this.numberTypedArray.subarray(r,r+this.tupleLength)}const e=t*this.bytesPerEntry,n=[];switch(this.elementDef.type){case"boolean":{for(let r=0;r<this.tupleLength;r++)n.push(Atomics.load(this.uint8View,e+r)!==0);break}case"string":{for(let r=0;r<this.tupleLength;r++){const o=e+r*this.bytesPerElement,s=this.readUint32(o);if(s===0)n.push("");else{const i=new Uint8Array(s);for(let a=0;a<s;a++)i[a]=Atomics.load(this.uint8View,o+4+a);n.push(bb.decode(i))}}break}case"binary":{for(let r=0;r<this.tupleLength;r++){const o=e+r*this.bytesPerElement,s=this.readUint32(o);if(s===0)n.push(new Uint8Array(0));else{const i=new Uint8Array(s);for(let a=0;a<s;a++)i[a]=Atomics.load(this.uint8View,o+4+a);n.push(i)}}break}}return n}set(t,e){if(this.numberTypedArray!==null){const s=t*this.elementsPerEntry,i=Math.min(e.length,this.tupleLength);for(let a=0;a<i;a++)this.numberTypedArray[s+a]=e[a];for(let a=i;a<this.tupleLength;a++)this.numberTypedArray[s+a]=0;return}const n=t*this.bytesPerEntry,r=Math.min(e.length,this.tupleLength),o=this.tupleLength*this.bytesPerElement;for(let s=0;s<o;s++)Atomics.store(this.uint8View,n+s,0);if(r!==0)switch(this.elementDef.type){case"boolean":{for(let s=0;s<r;s++)Atomics.store(this.uint8View,n+s,e[s]?1:0);break}case"string":{const s=this.bytesPerElement-4;for(let i=0;i<r;i++){const a=n+i*this.bytesPerElement,l=e[i],c=vb.encode(l),u=Math.min(c.length,s);this.writeUint32(a,u);for(let d=0;d<u;d++)Atomics.store(this.uint8View,a+4+d,c[d])}break}case"binary":{const s=this.bytesPerElement-4;for(let i=0;i<r;i++){const a=n+i*this.bytesPerElement,l=e[i],c=Math.min(l.length,s);this.writeUint32(a,c);for(let u=0;u<c;u++)Atomics.store(this.uint8View,a+4+u,l[u])}break}}}getBuffer(){return this.buffer}getBytesPerEntry(){return this.bytesPerEntry}},Cb=class extends fr{initializeStorage(t,e){const n=ph(this.fieldDef.elementDef),r=this.fieldDef.length*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new Eb(s,t,o,this.fieldDef.elementDef,this.fieldDef.length);return{buffer:s,view:i}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){if(n&&typeof n=="object"&&!Array.isArray(n)&&n.length===void 0){const r=new Array(this.fieldDef.length);for(let o=0;o<this.fieldDef.length;o++)r[o]=n[o];n=r}t.set(e,n)}},xb=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Tb={string:yb,number:eb,boolean:ib,binary:sb,array:rb,tuple:Cb,buffer:cb,enum:ub},ls=4294967295,cs=0,mh=0,Mb=(Mn=class{constructor(e,n=!1){C(this,"componentId",-1);C(this,"isSingleton");C(this,"initialized",!1);C(this,"eventBuffer",null);C(this,"entityBuffer",null);C(this,"schema");C(this,"fieldNames");C(this,"fields",{});C(this,"_buffer",null);C(this,"readonlyPool",[]);C(this,"writablePool",[]);C(this,"readPoolIndex",0);C(this,"writePoolIndex",0);this.isSingleton=n,this.schema={},this.fieldNames=[];for(const[r,o]of Object.entries(e)){const s=o,i=s.def||o;s[Zt]&&i.schemaDefault===void 0&&(i.schemaDefault=s[Zt]()),this.schema[r]=i,this.fieldNames.push(r)}}static fromDef(e){return new Mn(e.schema,e.isSingleton)}static fromTransfer(e,n,r,o){const s=new Mn(n.schema,n.isSingleton);return s.initialize(n.componentId,e,r,o,n.buffer),s}initialize(e,n,r,o,s){this.ensureNotInitialized(),this.initialized=!0,this.componentId=e,this.eventBuffer=r,this.entityBuffer=o;const i=this.isSingleton?1:n;for(const[a,l]of Object.entries(this.schema))this.fields[a]=this.createFieldInstance(l);if(s)this._buffer=s;else{const a={};for(const l of this.fieldNames){const c=this.fields[l],{view:u}=c.initializeStorage(i,xb);a[l]=u}this._buffer=a,this.isSingleton&&this.initializeSingletonDefaults()}this.initializeMasters()}ensureNotInitialized(){if(this.initialized)throw new Error("Component has already been initialized. Each component instance can only be registered with one World. If you need multiple worlds, define separate component instances for each.")}createFieldInstance(e){if(e.type==="ref")return new hb(e,this.entityBuffer);const n=Tb[e.type];if(!n)throw new Error(`Unknown field type: ${e.type}`);return new n(e)}get buffer(){return this._buffer}initializeSingletonDefaults(){if(this._buffer===null)throw new Error("Component buffers not initialized");for(let e=0;e<this.fieldNames.length;e++){const n=this.fieldNames[e],r=this._buffer[n],o=this.fields[n],s=o.getDefaultValue();o.setValue(r,cs,s)}}initializeMasters(){if(this._buffer===null)throw new Error("Component buffers not initialized");for(let e=0;e<Mn.POOL_SIZE;e++){const n={view:{},entityId:0};for(const r of this.fieldNames)this.fields[r].defineReadonly(n.view,r,this._buffer,()=>n.entityId);this.readonlyPool.push(n)}for(let e=0;e<Mn.POOL_SIZE;e++){const n={view:{},entityId:0};for(const r of this.fieldNames)this.fields[r].defineWritable(n.view,r,this._buffer,()=>n.entityId);this.writablePool.push(n)}}copy(e,n){var o;for(let s=0;s<this.fieldNames.length;s++){const i=this.fieldNames[s],a=this.buffer[i],l=this.fields[i],u=n&&i in n?n[i]:l.getDefaultValue();l.setValue(a,e,u)}const r=this.isSingleton?ls:e;(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId)}patch(e,n){var o;for(const s in n){const i=this.fields[s];if(!i)continue;const a=this.buffer[s];i.setValue(a,e,n[s])}const r=this.isSingleton?ls:e;(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId)}read(e){const n=this.readonlyPool[this.readPoolIndex];return this.readPoolIndex=(this.readPoolIndex+1)%Mn.POOL_SIZE,n.entityId=e,n.view}write(e){var o;const n=this.writablePool[this.writePoolIndex];this.writePoolIndex=(this.writePoolIndex+1)%Mn.POOL_SIZE,n.entityId=e;const r=this.isSingleton?ls:e;return(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId),n.view}snapshot(e){const n=this.read(e),r={};for(let o=0;o<this.fieldNames.length;o++){const s=this.fieldNames[o];let i=n[s];ArrayBuffer.isView(i)&&(i=Array.from(i)),r[s]=i}return r}},C(Mn,"POOL_SIZE",8),Mn),Mc=class{constructor(t,e=!1){C(this,"_defId");C(this,"schema");C(this,"isSingleton");this._defId=mh++,this.schema=t,this.isSingleton=e}_getInstance(t){const e=t.components[this._defId];if(!e)throw new Error(`Component "${this.constructor.name}" is not registered with this World.`);return e}_getComponentId(t){return this._getInstance(t).componentId}read(t,e){return this._getInstance(t).read(e)}write(t,e){return this._getInstance(t).write(e)}copy(t,e,n){this._getInstance(t).copy(e,n)}patch(t,e,n){this._getInstance(t).patch(e,n)}snapshot(t,e){return this._getInstance(t).snapshot(e)}default(){const t={};for(const[e,n]of Object.entries(this.schema))t[e]=n[Zt]();return t}};function _c(t){return new Mc(t,!1)}var gh=class{constructor(t){C(this,"_defId");C(this,"schema");C(this,"isSingleton",!0);this._defId=mh++,this.schema=t}_getInstance(t){const e=t.components[this._defId];if(!e)throw new Error(`Singleton "${this.constructor.name}" is not registered with this World.`);if(!e.isSingleton)throw new Error(`Component "${this.constructor.name}" is not a singleton. Use defineSingleton() to create singletons.`);return e}_getComponentId(t){return this._getInstance(t).componentId}read(t){return this._getInstance(t).read(cs)}write(t){return this._getInstance(t).write(cs)}copy(t,e){this._getInstance(t).copy(cs,e)}patch(t,e){this._getInstance(t).patch(cs,e)}snapshot(t){return this._getInstance(t).snapshot(cs)}default(){const t={};for(const[e,n]of Object.entries(this.schema))t[e]=n[Zt]();return t}},_b=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,_e={ADDED:1,REMOVED:2,CHANGED:4,COMPONENT_ADDED:8,COMPONENT_REMOVED:16},Ab=8,Ac=4,Ic=0,Ib=class Tv{constructor(e){C(this,"buffer");C(this,"headerView");C(this,"dataView");C(this,"maxEvents");C(this,"reusableSet",new Set);this.maxEvents=e;const n=Ac+e*Ab;this.buffer=new _b(n),this.headerView=new Uint32Array(this.buffer,0,1),this.dataView=new Uint32Array(this.buffer,Ac),Atomics.store(this.headerView,Ic,0)}static fromTransfer(e,n){const r=Object.create(Tv.prototype);return r.buffer=e,r.headerView=new Uint32Array(e,0,1),r.dataView=new Uint32Array(e,Ac),r.maxEvents=n,r.reusableSet=new Set,r}getBuffer(){return this.buffer}getDataView(){return this.dataView}push(e,n,r=0){const s=Atomics.add(this.headerView,Ic,1)%this.maxEvents*2,i=n|r<<16;Atomics.store(this.dataView,s,e),Atomics.store(this.dataView,s+1,i)}pushAdded(e){this.push(e,_e.ADDED,0)}pushRemoved(e){this.push(e,_e.REMOVED,0)}pushChanged(e,n){this.push(e,_e.CHANGED,n)}pushComponentAdded(e,n){this.push(e,_e.COMPONENT_ADDED,n)}pushComponentRemoved(e,n){this.push(e,_e.COMPONENT_REMOVED,n)}readEvent(e){const n=e*2,r=Atomics.load(this.dataView,n),o=Atomics.load(this.dataView,n+1);return{entityId:r,eventType:o&255,componentId:o>>16&65535}}getWriteIndex(){return Atomics.load(this.headerView,Ic)}collectEntitiesInRange(e,n,r,o){const s=o??this.getWriteIndex();s-e>this.maxEvents&&(e=s-this.maxEvents,console.warn("EventBuffer: Missed events due to buffer overflow, adjusting read index. Increase the maxEvents size to prevent this from happening."));const i=this.reusableSet;i.clear();const a=e%this.maxEvents,l=s%this.maxEvents;if(a===l)return{entities:i,newIndex:s};let c;l>=a?c=l-a:c=this.maxEvents-a+l,c>this.maxEvents&&(c=this.maxEvents);const u=this.dataView,d=this.maxEvents;for(let h=0;h<c;h++){const m=(a+h)%d*2,g=Atomics.load(u,m+1),y=g&255;if(!(y&n))continue;if(r!==void 0&&y===_e.CHANGED){const k=g>>16&65535,b=k>>3,S=k&7;if(b>=r.length||!(r[b]&1<<S))continue}const w=Atomics.load(u,m);i.add(w)}return{entities:i,newIndex:s}}readEvents(e){const n=this.getWriteIndex(),r=[];n-e>this.maxEvents&&(e=n-this.maxEvents);const o=e%this.maxEvents,s=n%this.maxEvents;if(o===s)return{events:r,newIndex:n};let i;s>=o?i=s-o:i=this.maxEvents-o+s,i>this.maxEvents&&(i=this.maxEvents);const a=this.dataView,l=this.maxEvents;for(let c=0;c<i;c++){const d=(o+c)%l*2,h=Atomics.load(a,d+1),p=h&255,m=h>>16&65535,g=Atomics.load(a,d);r.push({entityId:g,eventType:p,componentId:m})}return{events:r,newIndex:n}}},Bb=class{constructor(t,e,n,r,o,s,i,a){C(this,"tracking");C(this,"with");C(this,"without");C(this,"any");C(this,"hasTracking");C(this,"hasWith");C(this,"hasWithout");C(this,"hasAny");this.tracking=t,this.with=e,this.without=n,this.any=r,this.hasTracking=o,this.hasWith=s,this.hasWithout=i,this.hasAny=a}usesSingleton(t){const{components:e}=t;if(!this.hasTracking)return!1;for(let n=0;n<this.tracking.length;n++){const r=this.tracking[n];if(r!==0){for(let o=0;o<8;o++)if(r&1<<o){const s=n*8+o,i=Object.values(e).find(a=>a.componentId===s);if(i&&!i.isSingleton)return!1}}}return!0}},Bc=Symbol("buildQuery");function aa(t){return new Uint8Array(t)}function Xs(t,e){const n=Math.floor(e/8),r=e%8;n<t.length&&(t[n]|=1<<r)}var yh=class{constructor(t,e){C(this,"withMask");C(this,"withoutMask");C(this,"anyMask");C(this,"trackingMask");C(this,"ctx");const n=Math.ceil(t/8);this.withMask=aa(n),this.withoutMask=aa(n),this.anyMask=aa(n),this.trackingMask=aa(n),this.ctx=e}_getComponentId(t){const e=this.ctx.components[t._defId];if(!e)throw new Error(`Component "${t.constructor.name}" is not registered with this World.`);return e.componentId}with(...t){for(const e of t)Xs(this.withMask,this._getComponentId(e));return this}without(...t){for(const e of t)Xs(this.withoutMask,this._getComponentId(e));return this}any(...t){for(const e of t)Xs(this.anyMask,this._getComponentId(e));return this}tracking(...t){for(const e of t){const n=this._getComponentId(e);Xs(this.withMask,n),Xs(this.trackingMask,n)}return this}[Bc](){const t=!this.trackingMask.every(o=>o===0),e=!this.withMask.every(o=>o===0),n=!this.withoutMask.every(o=>o===0),r=!this.anyMask.every(o=>o===0);return new Bb(this.trackingMask,this.withMask,this.withoutMask,this.anyMask,t,e,n,r)}},wh=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,qn=0,$r=1,us=4294967295,kh=class{constructor(t){C(this,"denseBuffer");C(this,"sparseBuffer");C(this,"dense");C(this,"sparse");C(this,"maxEntities");this.maxEntities=t,this.denseBuffer=new wh(($r+t)*4),this.dense=new Uint32Array(this.denseBuffer),this.dense[qn]=0,this.sparseBuffer=new wh(t*4),this.sparse=new Uint32Array(this.sparseBuffer),this.sparse.fill(us)}get count(){return this.dense[qn]}add(t){const e=this.sparse;if(e[t]!==us)return;const n=this.dense,r=n[qn];if(r>=this.maxEntities)throw new Error("QueryCache is full");n[$r+r]=t,e[t]=r,n[qn]=r+1}remove(t){const e=this.sparse,n=e[t];if(n===us)return;const r=this.dense,s=r[qn]-1;if(n!==s){const i=r[$r+s];r[$r+n]=i,e[i]=n}e[t]=us,r[qn]=s}has(t){return this.sparse[t]!==us}clear(){const t=this.dense[qn];for(let e=0;e<t;e++){const n=this.dense[$r+e];this.sparse[n]=us}this.dense[qn]=0}toArray(){const t=this.dense[qn],e=new Array(t);for(let n=0;n<t;n++)e[n]=this.dense[$r+n];return e}getDenseView(){const t=this.dense[qn];return this.dense.subarray($r,$r+t)}},Pb=class{constructor(t,e){C(this,"cache");C(this,"lastIndex",0);C(this,"masks");this.masks=e,this.cache=new kh(t.maxEntities)}current(t){const e=t.currEventIndex??t.eventBuffer.getWriteIndex();if(e===this.lastIndex)return this.cache.getDenseView();const n=e-this.lastIndex,r=this.cache.count,o=t.maxEvents;return n>o||r===0||n>=r?this.rebuildFromEntityBuffer(t):this.processEvents(t,e),this.lastIndex=e,this.cache.getDenseView()}rebuildFromEntityBuffer(t){const e=t.entityBuffer,n=t.maxEntities,r=this.masks,o=this.cache;o.clear();for(let s=0;s<n;s++)e.has(s)&&e.matches(s,r)&&o.add(s)}processEvents(t,e){const n=t.maxEvents,r=t.entityBuffer,o=t.eventBuffer.getDataView(),s=this.masks,i=this.cache,l=this.lastIndex%n,c=e%n,u=c>=l?c-l:n-l+c;for(let d=0;d<u;d++){const p=(l+d)%n*2,m=Atomics.load(o,p),y=Atomics.load(o,p+1)&255;if(y===_e.REMOVED)i.remove(m);else if(y===_e.ADDED||y===_e.COMPONENT_ADDED||y===_e.COMPONENT_REMOVED){const k=r.has(m)&&r.matches(m,s),b=i.has(m);k&&!b?i.add(m):!k&&b&&i.remove(m)}}}},Nb=(ns=class{constructor(e){C(this,"builder");C(this,"instances",{});C(this,"id");this.builder=e,this.id=`current_query_${ns.queryCounter++}`}getName(e){return`${this.id}_${e.readerId}`}_getInstance(e){const n=this.getName(e);let r=this.instances[n];if(r)return r;const o=new yh(e.componentCount,e),i=this.builder(o)[Bc]();return r=new Pb(e,i),this.instances[n]=r,r}current(e){return this._getInstance(e).current(e)}},C(ns,"queryCounter",0),ns);function Db(t){return new Nb(t)}var vh=new Map;function Ob(t){const e=t._defId;let n=vh.get(e);return n||(n=Db(r=>r.with(t)),vh.set(e,n)),n}function vt(t){const e=t.pool.get();return t.entityBuffer.create(e),t.eventBuffer.pushAdded(e),e}function Jn(t,e,n,r,o=!0){const s=n._getInstance(t),i=Ob(n),a=s.buffer[r],l=[];for(const c of i.current(t))Tc(a[c],t.entityBuffer,o)===e&&l.push(c);return l}function Ye(t,e){t.entityBuffer.has(e)&&(t.eventBuffer.pushRemoved(e),t.entityBuffer.markDead(e))}function G(t,e,n,r={},o=!0){if(o&&!t.entityBuffer.has(e))throw new Error(`Entity with ID ${e} does not exist.`);const s=n._getInstance(t);if(t.entityBuffer.hasComponent(e,s.componentId))throw new Error(`Entity ${e} already has component. Use removeComponent() first or update the existing component.`);t.entityBuffer.addComponentToEntity(e,s.componentId),t.eventBuffer.pushComponentAdded(e,s.componentId),s.copy(e,r)}function nn(t,e,n,r=!0){if(r&&!t.entityBuffer.has(e))throw new Error(`Entity with ID ${e} does not exist.`);const o=n._getInstance(t);t.entityBuffer.removeComponentFromEntity(e,o.componentId),t.eventBuffer.pushComponentRemoved(e,o.componentId)}function O(t,e,n,r=!0){if(r&&!t.entityBuffer.has(e))throw new Error(`Entity with ID ${e} does not exist.`);const o=n._getInstance(t);return t.entityBuffer.hasComponent(e,o.componentId)}function Le(t){return t.resources}function Rb(t,e){return t.entityBuffer.has(e)}var zb=class{constructor(t){C(this,"lastIndex");C(this,"lastPrevEventIndex",-1);C(this,"lastCurrEventIndex",-1);C(this,"prevExecutionIndex",0);C(this,"prevFrameIndex",0);C(this,"toIndex",0);C(this,"added",[]);C(this,"removed",[]);C(this,"changed",[]);this.lastIndex=t}updateCache(t,e,n){const r=t.currEventIndex??t.eventBuffer.getWriteIndex(),o=t.prevEventIndex;o===this.lastPrevEventIndex&&r===this.lastCurrEventIndex||(this.added=[],this.removed=[],this.changed=[],this.lastPrevEventIndex=o,this.lastCurrEventIndex=r,this.prevExecutionIndex=this.lastIndex,this.prevFrameIndex=o,this.toIndex=r,this.lastIndex=r,this.processEventsAndComputeResults(t,e,n))}updateSingletonChanged(t,e){const n=t.currEventIndex??t.eventBuffer.getWriteIndex(),r=t.prevEventIndex;if(r===this.lastPrevEventIndex&&n===this.lastCurrEventIndex)return;this.changed=[],this.lastPrevEventIndex=r,this.lastCurrEventIndex=n,this.prevFrameIndex=r,this.toIndex=n,this.lastIndex=n,t.eventBuffer.collectEntitiesInRange(this.prevFrameIndex,_e.CHANGED,e.tracking).entities.size>0&&this.changed.push(ls)}rebuildCacheFromEntityBuffer(t,e,n){const r=t.entityBuffer,o=t.maxEntities;e.clear();for(let s=0;s<o;s++)r.has(s)&&r.matches(s,n)&&e.add(s)}processEventsAndComputeResults(t,e,n){const r=t.maxEvents,o=t.entityBuffer,s=t.eventBuffer.getDataView(),i=this.prevExecutionIndex,a=this.toIndex;let l=this.prevFrameIndex;const c=a-i>r;c&&this.rebuildCacheFromEntityBuffer(t,e,n),a-l>r&&(console.warn(`[ECS] Event buffer overflow: ${a-l} events since last frame, but maxEvents is ${r}. Some added/removed/changed events may be missed. Consider increasing maxEvents in World constructor.`),l=a-r);const d=c?l:i,h=d%r,p=a%r;let m=p>=h?p-h:r-h+p;m>r&&(m=r);const g=this.added,y=this.removed,w=this.changed;g.length=0,y.length=0,w.length=0;const k={},b=1,S=2,v=3,x=n.hasTracking,T=n.tracking;for(let A=0;A<m;A++){const $=(h+A)%r*2,U=d+A>=l,M=Atomics.load(s,$),L=Atomics.load(s,$+1),q=L&255,se=e.has(M),Z=k[M];if(q===_e.REMOVED){if(!c&&se&&e.remove(M),U)if(Z===b){const H=g.indexOf(M);H!==-1&&(g[H]=g[g.length-1],g.length--),k[M]=S}else if(Z===v&&se){const H=w.indexOf(M);H!==-1&&(w[H]=w[w.length-1],w.length--),k[M]=S,y.push(M)}else!Z&&se&&(k[M]=S,y.push(M))}else if(q===_e.ADDED){const H=o.matches(M,n);!c&&!se&&H&&e.add(M),U&&!Z&&!se&&H&&(k[M]=b,g.push(M))}else if(q===_e.COMPONENT_ADDED||q===_e.COMPONENT_REMOVED){const J=o.has(M)&&o.matches(M,n);c||(J&&!se?e.add(M):!J&&se&&e.remove(M)),U&&!Z&&(!se&&J?(k[M]=b,g.push(M)):se&&!J&&(k[M]=S,y.push(M)))}else if(q===_e.CHANGED&&x&&U&&!Z&&se){const H=L>>16&65535,J=H>>3,ce=H&7;J<T.length&&T[J]&1<<ce&&(k[M]=v,w.push(M))}}}},Pc=[],$b=class{constructor(t,e){C(this,"masks");C(this,"cache",null);C(this,"reader");C(this,"isSingletonQuery");this.masks=e,this.isSingletonQuery=e.usesSingleton(t),this.isSingletonQuery||(this.cache=new kh(t.maxEntities)),this.reader=new zb(0)}current(t,e){if(this.isSingletonQuery)return[ls];this.reader.updateCache(t,this.cache,this.masks);const n=this.cache.getDenseView();return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}added(t,e){if(this.isSingletonQuery)return Pc;this.reader.updateCache(t,this.cache,this.masks);const n=this.reader.added;return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}removed(t,e){if(this.isSingletonQuery)return Pc;this.reader.updateCache(t,this.cache,this.masks);const n=this.reader.removed;return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}changed(t,e){if(this.isSingletonQuery)return this.reader.updateSingletonChanged(t,this.masks),this.reader.changed;this.reader.updateCache(t,this.cache,this.masks);const n=this.reader.changed;return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}addedOrChanged(t,e){return[...this.added(t,e),...this.changed(t,e)]}addedOrRemoved(t,e){return[...this.added(t,e),...this.removed(t,e)]}removedOrChanged(t,e){return[...this.removed(t,e),...this.changed(t,e)]}addedOrChangedOrRemoved(t,e){return[...this.added(t,e),...this.removed(t,e),...this.changed(t,e)]}partitionEntities(t,e,n){if(t.length===0||n<=1)return t;const r=[];for(let o=0;o<t.length;o++)t[o]%n===e&&r.push(t[o]);return r.length>0?r:Pc}},Lb=(rs=class{constructor(e){C(this,"builder");C(this,"instances",{});C(this,"id");this.builder=e,this.id=`query_${rs.queryCounter++}`}getName(e){return`${this.id}_${e.readerId}`}_getInstance(e){const n=this.getName(e);let r=this.instances[n];if(r)return r;const o=this._getMasks(e);return r=new $b(e,o),this.instances[n]=r,r}_getMasks(e){const n=new yh(e.componentCount,e);return this.builder(n)[Bc]()}current(e,n){return this._getInstance(e).current(e,n)}added(e,n){return this._getInstance(e).added(e,n)}removed(e,n){return this._getInstance(e).removed(e,n)}changed(e,n){return this._getInstance(e).changed(e,n)}addedOrChanged(e,n){return this._getInstance(e).addedOrChanged(e,n)}addedOrRemoved(e,n){return this._getInstance(e).addedOrRemoved(e,n)}removedOrChanged(e,n){return this._getInstance(e).removedOrChanged(e,n)}addedOrChangedOrRemoved(e,n){return this._getInstance(e).addedOrChangedOrRemoved(e,n)}},C(rs,"queryCounter",0),rs);function ne(t){return new Lb(t)}var bh=(ss=class{constructor(){C(this,"id");this.id=ss.systemCounter++}},C(ss,"systemCounter",0),ss),Fb=class extends bh{constructor(e){super();C(this,"type","main");C(this,"execute");this.execute=e}},Vb=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Wb=(Bt=class{constructor(e,n){C(this,"buffer");C(this,"view");C(this,"bytesPerEntity");const r=Math.ceil(n/8);this.bytesPerEntity=1+r;const o=e*this.bytesPerEntity;this.buffer=new Vb(o),this.view=new Uint8Array(this.buffer)}static fromTransfer(e,n){const r=Object.create(Bt.prototype);r.buffer=e,r.view=new Uint8Array(e);const o=Math.ceil(n/8);return r.bytesPerEntity=1+o,r}getBuffer(){return this.buffer}create(e){const n=e*this.bytesPerEntity,r=this.view,o=this.bytesPerEntity,a=((Atomics.load(r,n)&Bt.GENERATION_MASK)>>Bt.GENERATION_SHIFT)+1&127;for(let l=0;l<o;l++)Atomics.store(r,n+l,0);Atomics.store(r,n,Bt.ALIVE_FLAG|a<<Bt.GENERATION_SHIFT)}addComponentToEntity(e,n){const r=1+(n>>3),o=n&7,s=e*this.bytesPerEntity;Atomics.or(this.view,s+r,1<<o)}removeComponentFromEntity(e,n){const r=1+(n>>3),o=n&7,s=e*this.bytesPerEntity;Atomics.and(this.view,s+r,~(1<<o))}hasComponent(e,n){const r=1+(n>>3),o=n&7,s=e*this.bytesPerEntity;return(Atomics.load(this.view,s+r)&1<<o)!==0}matches(e,n){const r=this.bytesPerEntity,o=e*r,s=this.view;if(!(Atomics.load(s,o)&Bt.ALIVE_FLAG))return!1;const i=o+1;if(n.hasWith){const a=n.with,l=a.length;for(let c=0;c<l;c++){const u=a[c];if(u!==0&&(Atomics.load(s,i+c)&u)!==u)return!1}}if(n.hasWithout){const a=n.without,l=a.length;for(let c=0;c<l;c++){const u=a[c];if(u!==0&&Atomics.load(s,i+c)&u)return!1}}if(n.hasAny){const a=n.any,l=a.length;let c=!1;for(let u=0;u<l;u++){const d=a[u];if(d!==0&&Atomics.load(s,i+u)&d){c=!0;break}}if(!c)return!1}return!0}delete(e){const n=e*this.bytesPerEntity,r=this.view,o=this.bytesPerEntity;for(let s=0;s<o;s++)Atomics.store(r,n+s,0)}markDead(e){const n=e*this.bytesPerEntity;Atomics.and(this.view,n,-2)}has(e){const n=e*this.bytesPerEntity;return(Atomics.load(this.view,n)&Bt.ALIVE_FLAG)!==0}getGeneration(e){const n=e*this.bytesPerEntity;return(Atomics.load(this.view,n)&Bt.GENERATION_MASK)>>Bt.GENERATION_SHIFT}*getComponentIds(e){const n=e*this.bytesPerEntity,r=this.view,o=this.bytesPerEntity-1;for(let s=0;s<o;s++){const i=Atomics.load(r,n+1+s);if(i!==0)for(let a=0;a<8;a++)i&1<<a&&(yield s*8+a)}}},C(Bt,"ALIVE_FLAG",1),C(Bt,"GENERATION_MASK",254),C(Bt,"GENERATION_SHIFT",1),Bt),Ub=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function Hb(t){return t===0?-1:31-Math.clz32(t&-t)}var jb=(Ne=class{constructor(e,n,r){C(this,"buffer");C(this,"view");C(this,"bucketCount");C(this,"size");this.buffer=e,this.view=new Int32Array(e),this.bucketCount=n,this.size=r}static create(e){const n=Math.ceil(e/32),r=new Ub((n+1)*4),o=new Int32Array(r);for(let i=Ne.DATA_OFFSET;i<n+Ne.DATA_OFFSET;i++)o[i]=-1;const s=e%32;if(s!==0){const i=n-1+Ne.DATA_OFFSET,a=(1<<s)-1;o[i]=a}return o[Ne.HINT_INDEX]=0,new Ne(r,n,e)}static fromTransfer(e,n,r){return new Ne(e,n,r)}getBuffer(){return this.buffer}getBucketCount(){return this.bucketCount}getSize(){return this.size}free(e){const n=(e>>5)+Ne.DATA_OFFSET,r=1<<(e&31);Atomics.or(this.view,n,r);const o=Atomics.load(this.view,Ne.HINT_INDEX),s=n-Ne.DATA_OFFSET;(o===-1||s<o)&&Atomics.store(this.view,Ne.HINT_INDEX,s)}get(){for(let e=0;e<this.bucketCount*2;e++){let n=Atomics.load(this.view,Ne.HINT_INDEX);n===-1&&(n=0);for(let r=0;r<this.bucketCount;r++){const o=(n+r)%this.bucketCount+Ne.DATA_OFFSET,s=Atomics.load(this.view,o);if(s===0)continue;const i=Hb(s);if(i===-1)continue;const a=1<<i;if(Atomics.compareExchange(this.view,o,s,s&~a)===s)return(s&~a)===0&&this.updateHint(o-Ne.DATA_OFFSET),(o-Ne.DATA_OFFSET<<5)+i}}throw Atomics.store(this.view,Ne.HINT_INDEX,-1),new Error(`Entity pool exhausted: maximum of ${this.size} entities reached`)}updateHint(e){for(let n=0;n<this.bucketCount;n++){const r=(e+n)%this.bucketCount+Ne.DATA_OFFSET;if(Atomics.load(this.view,r)!==0){Atomics.store(this.view,Ne.HINT_INDEX,r-Ne.DATA_OFFSET);return}}Atomics.store(this.view,Ne.HINT_INDEX,-1)}},C(Ne,"HINT_INDEX",0),C(Ne,"DATA_OFFSET",1),Ne),Sh=3,Zb=.75,Kb=class{constructor(t){C(this,"systems",new Map);C(this,"lastReclaimIndex",0);C(this,"maxEvents");C(this,"warnedStaleSystems",new Set);this.maxEvents=t}recordExecution(t,e){let n=this.systems.get(t);return n||(n={prev:0,curr:0,history:[]},this.systems.set(t,n)),n.prev=n.curr,n.curr=e,n.history.push(e),n.history.length>Sh&&n.history.shift(),n.prev}getPrevIndex(t){var e;return((e=this.systems.get(t))==null?void 0:e.prev)??0}calculateWatermark(t){if(this.systems.size===0)return null;const r=this.calculateEventsInFlight(t)/this.maxEvents>Zb;let o=0;if(r){const a=Math.floor(this.maxEvents*.25);o=this.wrapAwareSubtract(t,a)}let s=null,i=!1;for(const[a,l]of this.systems){if(l.history.length<Sh){if(r)continue;i=!0;continue}if(r){const u=l.history[l.history.length-1];if(this.isOlderThan(u,o)){this.warnedStaleSystems.has(a)||(this.warnedStaleSystems.add(a),console.warn(`[History] Stale system detected (id: ${a}). System queries will miss some events. Consider increasing maxEvents or running the system more frequently.`));continue}}const c=l.history[0];(s===null||this.isOlderThan(c,s))&&(s=c)}return i&&!r?null:s!==null&&this.isNewerThan(s,this.lastReclaimIndex)?s:null}markReclaimed(t){this.lastReclaimIndex=t}getLastReclaimIndex(){return this.lastReclaimIndex}calculateEventsInFlight(t){return t>=this.lastReclaimIndex?t-this.lastReclaimIndex:this.maxEvents-this.lastReclaimIndex+t}wrapAwareSubtract(t,e){const n=t-e;return n<0?this.maxEvents+n:n}isOlderThan(t,e){const n=e-t,r=this.maxEvents/2;return Math.abs(n)<r?t<e:t>e}isNewerThan(t,e){return t===e?!1:!this.isOlderThan(t,e)}clear(){this.systems.clear(),this.lastReclaimIndex=0,this.warnedStaleSystems.clear()}},Yb=class{constructor(t){C(this,"maxWorkers");C(this,"workerPool",new Map);C(this,"initializedWorkers",new Set);C(this,"taskQueue",new Map);C(this,"busyWorkers",0);this.maxWorkers=t}async execute(t,e,n){const r=[],o=t.threads;if(o>this.maxWorkers)throw new Error(`Worker system requests ${o} threads, but World was configured with only ${this.maxWorkers} max workers. Increase the 'threads' option in World constructor or reduce the worker system's thread count.`);for(let s=0;s<o;s++)r.push(this.executeTask(e,t.path,s,o,n));await Promise.all(r)}async initializeWorker(t,e,n,r){return new Promise((o,s)=>{const i=setTimeout(()=>{s(new Error(`Worker ${n} initialization timed out`))},5e3),a=u=>{u.data.threadIndex===n&&(clearTimeout(i),e.removeEventListener("message",a),"error"in u.data?s(new Error(u.data.error)):o())};e.addEventListener("message",a);const l={};for(const[u,d]of Object.entries(t.components))l[Number(u)]={componentId:d.componentId,buffer:d.buffer,schema:d.schema,isSingleton:d.isSingleton};const c={type:"init",entitySAB:t.entityBuffer.getBuffer(),eventSAB:t.eventBuffer.getBuffer(),poolSAB:t.pool.getBuffer(),poolBucketCount:t.pool.getBucketCount(),poolSize:t.pool.getSize(),componentTransferMap:l,maxEntities:t.maxEntities,maxEvents:t.maxEvents,componentCount:t.componentCount,threadIndex:n,threadCount:r};e.postMessage(c)})}async executeTask(t,e,n,r,o){const s=await this.getWorker(e);return this.initializedWorkers.has(s)||(await this.initializeWorker(t,s,n,r),this.initializedWorkers.add(s)),new Promise((i,a)=>{const l=setTimeout(()=>{s.terminate(),this.removeWorker(e,s),a(new Error(`Task ${n} timed out`))},5e3);s.onmessage=u=>{clearTimeout(l),"error"in u.data?a(new Error(u.data.error)):i(!0),this.releaseWorker(e,s)},s.onerror=u=>{clearTimeout(l),a(u),this.removeWorker(e,s)};const c={type:"execute",threadIndex:n,currEventIndex:o};s.postMessage(c)})}async getWorker(t){let e=this.workerPool.get(t);return e||(e=[],this.workerPool.set(t,e)),e.length>0?(this.busyWorkers++,e.pop()):this.busyWorkers>=this.maxWorkers?new Promise(n=>{let r=this.taskQueue.get(t);r||(r=[],this.taskQueue.set(t,r)),r.push(n)}):(this.busyWorkers++,this.createWorker(t))}createWorker(t){return new Worker(t,{type:"module"})}releaseWorker(t,e){const n=this.taskQueue.get(t);if(n&&n.length>0){const o=n.shift();if(o){o(e);return}}for(const[o,s]of this.taskQueue.entries())if(o!==t&&s.length>0){const i=this.workerPool.get(t);i&&i.push(e),this.busyWorkers--;let a=this.workerPool.get(o);a||(a=[],this.workerPool.set(o,a));const l=s.shift();if(l)if(a.length>0)this.busyWorkers++,l(a.pop());else{this.busyWorkers++;const c=this.createWorker(o);l(c)}return}this.busyWorkers--;const r=this.workerPool.get(t);r&&r.push(e)}removeWorker(t,e){this.busyWorkers--,this.initializedWorkers.delete(e);const n=this.workerPool.get(t);if(n){const r=n.indexOf(e);r>-1&&n.splice(r,1)}}dispose(){for(const t of this.workerPool.values())for(const e of t)e.terminate();this.workerPool.clear(),this.initializedWorkers.clear(),this.busyWorkers=0,this.taskQueue.clear()}},Eh={high:2,medium:1,low:0},qb=(is=class{constructor(e,n={}){C(this,"componentIndex",0);C(this,"workerManager");C(this,"context");C(this,"worldId");C(this,"subscriberCounter",0);C(this,"subscribers",[]);C(this,"componentIdToDef",new Map);C(this,"nextSyncCallbacks",[]);C(this,"prevSyncEventIndex",0);C(this,"history");const r=n.threads??(typeof navigator<"u"?Math.max(1,navigator.hardwareConcurrency??4):3),o=n.maxEntities??1e4,s=n.maxEvents??131072,i=e.length;this.workerManager=new Yb(r);const a=new Ib(s),l=new Wb(o,i),c={};for(const u of e){const d=Mb.fromDef(u);d.initialize(this.componentIndex++,o,a,l),c[u._defId]=d,this.componentIdToDef.set(this.componentIndex-1,u)}this.worldId=is.worldCounter++,this.history=new Kb(s),this.context={entityBuffer:l,eventBuffer:a,components:c,maxEntities:o,maxEvents:s,componentCount:i,pool:jb.create(o),threadIndex:0,threadCount:1,readerId:`world_${this.worldId}`,prevEventIndex:0,resources:n.resources}}_getContext(){return this.context}async execute(...e){const n=this.context,r=n.eventBuffer.getWriteIndex(),o=[],s=[];for(const d of e)d instanceof bh?o.push(d):s.push(d);for(const d of s)d({...n,prevEventIndex:this.prevSyncEventIndex,currEventIndex:r});for(const d of o)this.history.recordExecution(d.id,r);const i=o.filter(d=>d.type==="worker"),a=o.filter(d=>d.type==="main"),c=[...i].sort((d,h)=>Eh[h.priority]-Eh[d.priority]).map(d=>this.workerManager.execute(d,n,r));for(const d of a){const h=`world_${this.worldId}_system_${d.id}`,p=this.history.getPrevIndex(d.id);d.execute({...n,readerId:h,prevEventIndex:p,currEventIndex:r})}await Promise.all(c);const u=this.history.calculateWatermark(r);u!==null&&(this.reclaimRemovedEntityIds(this.history.getLastReclaimIndex(),u),this.history.markReclaimed(u))}reclaimRemovedEntityIds(e,n){if(e===n)return;const r=this.context,{entities:o}=r.eventBuffer.collectEntitiesInRange(e,_e.REMOVED,void 0,n);for(const s of o)r.entityBuffer.has(s)||(r.pool.free(s),r.entityBuffer.delete(s))}subscribe(e,n){const r=this.context,o=this.subscriberCounter++,s=`world_${this.worldId}_subscriber_${o}`;let i;return e._getInstance({...r,readerId:s}),i={queryDef:e,callback:n,readerId:s,prevEventIndex:r.eventBuffer.getWriteIndex()},this.subscribers.push(i),()=>{const a=this.subscribers.indexOf(i);a!==-1&&this.subscribers.splice(a,1)}}sync(){const e=this.context.eventBuffer.getWriteIndex();if(this.nextSyncCallbacks.length>0){const n=this.nextSyncCallbacks;this.nextSyncCallbacks=[];for(const r of n)r({...this.context,prevEventIndex:this.prevSyncEventIndex,currEventIndex:e});this.prevSyncEventIndex=e}if(this.subscribers.length!==0)for(const n of this.subscribers){const r={...this.context,readerId:n.readerId,prevEventIndex:n.prevEventIndex,currEventIndex:e};n.prevEventIndex=e;const o=n.queryDef,s={added:o.added(r),removed:o.removed(r),changed:o.changed(r)};s.added.length===0&&s.removed.length===0&&s.changed.length===0||n.callback(r,s)}}nextSync(e){return this.nextSyncCallbacks.push(e),()=>{const n=this.nextSyncCallbacks.indexOf(e);n!==-1&&this.nextSyncCallbacks.splice(n,1)}}dispose(){this.workerManager.dispose(),this.subscribers=[],this.nextSyncCallbacks=[],this.componentIdToDef.clear(),this.history.clear()}},C(is,"worldCounter",0),is);function Ch(t){const e=new Set,n=new Map;for(const r of t){if(e.has(r.name))throw new Error(`Duplicate migration name: "${r.name}"`);if(e.add(r.name),r.supersedes!=null){if(!e.has(r.supersedes))throw new Error(`Migration "${r.name}" supersedes "${r.supersedes}", which ${t.some(o=>o.name===r.supersedes)?"must come before it":"does not exist"}`);if(n.has(r.supersedes))throw new Error(`Migration "${r.supersedes}" is already superseded by "${n.get(r.supersedes)}"`);n.set(r.supersedes,r.name)}}}var Kt=class extends Mc{constructor(n,r){super(r,!1);C(this,"name");C(this,"sync");C(this,"migrations");C(this,"excludeFromHistory");this.name=n.name,this.sync=n.sync??"none",this.migrations=n.migrations??[],this.excludeFromHistory=n.excludeFromHistory??[],this.migrations.length>0&&Ch(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(n,r){return{...super.snapshot(n,r),_exists:!0,_version:this.currentVersion}}};function He(t,e){return new Kt(t,e)}var bt=class extends gh{constructor(n,r){super(r);C(this,"name");C(this,"sync");C(this,"migrations");C(this,"excludeFromHistory");this.name=n.name,this.sync=n.sync??"none",this.migrations=n.migrations??[],this.excludeFromHistory=n.excludeFromHistory??[],this.migrations.length>0&&Ch(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(n){return{...super.snapshot(n),_exists:!0,_version:this.currentVersion}}};function xh(t,e){return new bt(t,e)}var de=_c({id:E.string().max(36)}),we=0,ke=1,ve=2,be=3,Q;(t=>{t.create=(e,n,r,o)=>[e,n,r,o],t.zero=()=>[0,0,0,0],t.clone=e=>[e[0],e[1],e[2],e[3]],t.fromPoints=e=>{if(e.length===0)return(0,t.zero)();let n=e[0][0],r=e[0][1],o=e[0][0],s=e[0][1];for(let i=1;i<e.length;i++){const[a,l]=e[i];a<n&&(n=a),l<r&&(r=l),a>o&&(o=a),l>s&&(s=l)}return[n,r,o,s]},t.fromPositionSize=(e,n,r,o)=>[e,n,e+r,n+o],t.left=e=>e[we],t.top=e=>e[ke],t.right=e=>e[ve],t.bottom=e=>e[be],t.width=e=>e[ve]-e[we],t.height=e=>e[be]-e[ke],t.center=e=>[(e[we]+e[ve])/2,(e[ke]+e[be])/2],t.size=e=>[(0,t.width)(e),(0,t.height)(e)],t.corners=e=>[[e[we],e[ke]],[e[ve],e[ke]],[e[ve],e[be]],[e[we],e[be]]],t.containsPoint=(e,n,r=!0)=>r?n[0]>=e[we]&&n[0]<=e[ve]&&n[1]>=e[ke]&&n[1]<=e[be]:n[0]>e[we]&&n[0]<e[ve]&&n[1]>e[ke]&&n[1]<e[be],t.intersects=(e,n)=>!(e[ve]<n[we]||e[we]>n[ve]||e[be]<n[ke]||e[ke]>n[be]),t.contains=(e,n)=>e[we]<=n[we]&&e[ke]<=n[ke]&&e[ve]>=n[ve]&&e[be]>=n[be],t.distanceToPoint=(e,n)=>{const r=Math.max(e[we]-n[0],0,n[0]-e[ve]),o=Math.max(e[ke]-n[1],0,n[1]-e[be]);return Math.hypot(r,o)},t.set=(e,n,r,o,s)=>{e[we]=n,e[ke]=r,e[ve]=o,e[be]=s},t.copy=(e,n)=>{e[we]=n[we],e[ke]=n[ke],e[ve]=n[ve],e[be]=n[be]},t.expand=(e,n)=>{e[we]=Math.min(e[we],n[0]),e[ke]=Math.min(e[ke],n[1]),e[ve]=Math.max(e[ve],n[0]),e[be]=Math.max(e[be],n[1])},t.union=(e,n)=>{e[we]=Math.min(e[we],n[we]),e[ke]=Math.min(e[ke],n[ke]),e[ve]=Math.max(e[ve],n[ve]),e[be]=Math.max(e[be],n[be])},t.intersection=(e,n)=>{e[we]=Math.max(e[we],n[we]),e[ke]=Math.max(e[ke],n[ke]),e[ve]=Math.min(e[ve],n[ve]),e[be]=Math.min(e[be],n[be])},t.pad=(e,n)=>{e[we]-=n,e[ke]-=n,e[ve]+=n,e[be]+=n},t.setFromPoints=(e,n)=>{if(n.length===0){e[we]=0,e[ke]=0,e[ve]=0,e[be]=0;return}e[we]=n[0][0],e[ke]=n[0][1],e[ve]=n[0][0],e[be]=n[0][1];for(let r=1;r<n.length;r++){const[o,s]=n[r];o<e[we]&&(e[we]=o),s<e[ke]&&(e[ke]=s),o>e[ve]&&(e[ve]=o),s>e[be]&&(e[be]=s)}},t.translate=(e,n)=>{e[we]+=n[0],e[ke]+=n[1],e[ve]+=n[0],e[be]+=n[1]},t.scale=(e,n)=>{e[we]*=n,e[ke]*=n,e[ve]*=n,e[be]*=n}})(Q||(Q={}));var rn=0,on=1,hr=2,pr=3,sn=4,an=5,Xn=6,xe;(t=>{t.create=(e,n,r,o,s,i,a)=>[e,n,r,o,s,i,a],t.zero=()=>[0,0,0,0,0,0,0],t.clone=e=>[e[0],e[1],e[2],e[3],e[4],e[5],e[6]],t.a=e=>[e[rn],e[on]],t.b=e=>[e[hr],e[pr]],t.c=e=>[e[sn],e[an]],t.thickness=e=>e[Xn],t.isCollinear=e=>{const n=(e[rn]-e[sn])*(e[pr]-e[an])-(e[hr]-e[sn])*(e[on]-e[an]);return Math.abs(n)<1e-8},t.computeCenter=e=>{const n=e[rn],r=e[on],o=e[hr],s=e[pr],i=e[sn],a=e[an],l=(n-i)*(s-a)-(o-i)*(r-a);if(Math.abs(l)<1e-10)return null;const c=2*(n*(s-a)+o*(a-r)+i*(r-s));if(Math.abs(c)<1e-10)return null;const u=((n*n+r*r)*(s-a)+(o*o+s*s)*(a-r)+(i*i+a*a)*(r-s))/c,d=((n*n+r*r)*(i-o)+(o*o+s*s)*(n-i)+(i*i+a*a)*(o-n))/c;return[u,d]},t.compute=e=>{const n=(0,t.computeCenter)(e);if(!n)return null;const r=e[rn],o=e[on],s=e[hr],i=e[pr],a=e[sn],l=e[an],c=Math.hypot(s-n[0],i-n[1]),u=(s-r)*(l-o)-(i-o)*(a-r)<0,d=Jb(e,n);let h=Math.atan2(o-n[1],r-n[0]);h=bo(h);let p=h+d*(u?-1:1);return p=bo(p),{center:n,radius:c,clockwise:u,arcAngle:d,startAngle:h,endAngle:p}},t.inArcAngle=(e,n,r,o)=>(e=bo(e),o?n<r?e>=r||e<=n:e>=r&&e<=n:n>r?e>=n||e<=r:e>=n&&e<=r),t.containsPoint=(e,n)=>{const r=(0,t.compute)(e);if(!r)return!1;const{center:o,radius:s,startAngle:i,endAngle:a,clockwise:l}=r,c=e[Xn]/2,u=n[0]-o[0],d=n[1]-o[1],h=Math.hypot(u,d);if(Math.abs(h-s)>c)return!1;const m=Math.atan2(d,u);return(0,t.inArcAngle)(m,i,a,l)},t.intersectsAabb=(e,n)=>{const r=(0,t.compute)(e);if(!r)return!1;const{center:o,radius:s,startAngle:i,endAngle:a,clockwise:l}=r,c=e[Xn]/2,u=(0,t.a)(e),d=(0,t.b)(e),h=(0,t.c)(e);if(Nc(n,u)||Nc(n,d)||Nc(n,h))return!0;const p=s-c,m=s+c;if(!Xb(o,m,n))return!1;const g=[[n[0],n[1]],[n[2],n[1]],[n[2],n[3]],[n[0],n[3]]];for(const y of[m,p])for(let w=0;w<g.length;w++){const k=g[w],b=g[(w+1)%g.length],S=Mh(k,b,o,y);for(const v of S){const x=Math.atan2(v[1]-o[1],v[0]-o[0]);if((0,t.inArcAngle)(x,i,a,l))return!0}}return!1},t.intersectsCapsule=(e,n,r,o)=>{const s=(0,t.compute)(e);if(!s)return!1;const{center:i,radius:a,startAngle:l,endAngle:c,clockwise:u}=s,d=e[Xn]/2,h=a-d,p=a+d;for(const m of[p,h]){const g=Th(i,m,n),y=Th(i,m,r);if(g!==y){const w=Math.atan2(n[1]-i[1],n[0]-i[0]);if((0,t.inArcAngle)(w,l,c,u))return!0}}return!1},t.intersectSegment=(e,n,r)=>{const o=(0,t.compute)(e);if(!o)return[];const{center:s,radius:i,startAngle:a,endAngle:l,clockwise:c}=o;return Mh(n,r,s,i).filter(d=>{const h=Math.atan2(d[1]-s[1],d[0]-s[0]);return(0,t.inArcAngle)(h,a,l,c)})},t.intersectRect=(e,n)=>{const r=[];for(let o=0;o<n.length;o++){const s=n[o],i=n[(o+1)%n.length],a=(0,t.intersectSegment)(e,s,i);r.push(...a)}return r},t.pointToParametric=(e,n)=>{const r=(0,t.compute)(e);if(!r)return null;const{center:o,startAngle:s,arcAngle:i,clockwise:a}=r;let l=Math.atan2(n[1]-o[1],n[0]-o[0]);if(l=bo(l),!(0,t.inArcAngle)(l,r.startAngle,r.endAngle,a))return null;let c=(l-s)*(a?-1:1);return c<0&&(c+=2*Math.PI),c/i},t.parametricToPoint=(e,n)=>{const r=(0,t.compute)(e);if(!r)return[e[rn]+n*(e[sn]-e[rn]),e[on]+n*(e[an]-e[on])];const{center:o,radius:s,startAngle:i,arcAngle:a,clockwise:l}=r,c=i+n*a*(l?-1:1);return[o[0]+Math.cos(c)*s,o[1]+Math.sin(c)*s]},t.length=e=>{const n=(0,t.compute)(e);return n?n.arcAngle*n.radius:Math.hypot(e[sn]-e[rn],e[an]-e[on])},t.directionAt=(e,n)=>{const r=(0,t.compute)(e);if(!r){const c=e[sn]-e[rn],u=e[an]-e[on],d=Math.hypot(c,u);return d>0?[c/d,u/d]:[0,0]}const o=(0,t.parametricToPoint)(e,n),{center:s,clockwise:i}=r,a=[o[0]-s[0],o[1]-s[1]],l=Math.hypot(a[0],a[1]);return l===0?[0,0]:i?[a[1]/l,-a[0]/l]:[-a[1]/l,a[0]/l]},t.extremaPoints=(e,n=0)=>{const r=(0,t.compute)(e),o=[(0,t.a)(e),(0,t.c)(e)];if(!r)return o;const{center:s,radius:i,startAngle:a,endAngle:l,clockwise:c}=r;for(let u=0;u<4;u++){const d=u*Math.PI/2+n;(0,t.inArcAngle)(d,a,l,c)&&o.push([s[0]+Math.cos(d)*i,s[1]+Math.sin(d)*i])}return o},t.getExtrema=e=>{const n=(0,t.extremaPoints)(e),r=e[Xn]/2,o=[];for(const s of n)o.push([s[0]-r,s[1]-r]),o.push([s[0]-r,s[1]+r]),o.push([s[0]+r,s[1]-r]),o.push([s[0]+r,s[1]+r]);return o},t.set=(e,n,r,o,s,i,a,l)=>{e[rn]=n,e[on]=r,e[hr]=o,e[pr]=s,e[sn]=i,e[an]=a,e[Xn]=l},t.copy=(e,n)=>{e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6]},t.setA=(e,n,r)=>{e[rn]=n,e[on]=r},t.setB=(e,n,r)=>{e[hr]=n,e[pr]=r},t.setC=(e,n,r)=>{e[sn]=n,e[an]=r},t.setThickness=(e,n)=>{e[Xn]=n},t.setFromPoints=(e,n,r,o,s)=>{e[rn]=n[0],e[on]=n[1],e[hr]=r[0],e[pr]=r[1],e[sn]=o[0],e[an]=o[1],e[Xn]=s},t.trim=(e,n,r)=>{const o=(0,t.parametricToPoint)(e,n),s=(0,t.parametricToPoint)(e,(n+r)/2),i=(0,t.parametricToPoint)(e,r),a=e[Xn];e[rn]=o[0],e[on]=o[1],e[hr]=s[0],e[pr]=s[1],e[sn]=i[0],e[an]=i[1],e[Xn]=a}})(xe||(xe={}));function bo(t){for(;t<0;)t+=2*Math.PI;for(;t>=2*Math.PI;)t-=2*Math.PI;return t}function Jb(t,e){const n=t[rn],r=t[on],o=t[hr],s=t[pr],i=t[sn],a=t[an],l=bo(Math.atan2(r-e[1],n-e[0])),c=bo(Math.atan2(s-e[1],o-e[0])),u=bo(Math.atan2(a-e[1],i-e[0]));let d=Math.abs(u-l);d>Math.PI&&(d=2*Math.PI-d);const h=Math.min(l,u),p=Math.max(l,u);let m;return p-h>Math.PI?m=c>=p||c<=h:m=c>=h&&c<=p,m?d:2*Math.PI-d}function Nc(t,e){return e[0]>=t[0]&&e[0]<=t[2]&&e[1]>=t[1]&&e[1]<=t[3]}function Th(t,e,n){const r=n[0]-t[0],o=n[1]-t[1];return r*r+o*o<=e*e}function Xb(t,e,n){const r=Math.max(n[0],Math.min(t[0],n[2])),o=Math.max(n[1],Math.min(t[1],n[3])),s=t[0]-r,i=t[1]-o;return s*s+i*i<=e*e}function Mh(t,e,n,r){const o=[e[0]-t[0],e[1]-t[1]],s=[t[0]-n[0],t[1]-n[1]],i=o[0]*o[0]+o[1]*o[1],a=2*(s[0]*o[0]+s[1]*o[1]),l=s[0]*s[0]+s[1]*s[1]-r*r;if(i===0){const m=s[0]*s[0]+s[1]*s[1];return Math.abs(m-r*r)<=1e-12?[[t[0],t[1]]]:[]}let c=a*a-4*i*l;const u=1e-12;if(c<-u)return[];c=Math.sqrt(Math.max(0,c));const d=(-a-c)/(2*i),h=(-a+c)/(2*i),p=[];return d>=0&&d<=1&&p.push([t[0]+d*o[0],t[1]+d*o[1]]),h>=0&&h<=1&&Math.abs(h-d)>u&&p.push([t[0]+h*o[0],t[1]+h*o[1]]),p}var z;(t=>{t.create=(e,n)=>[e,n],t.zero=()=>[0,0],t.clone=e=>[e[0],e[1]],t.dot=(e,n)=>e[0]*n[0]+e[1]*n[1],t.lengthSq=e=>e[0]*e[0]+e[1]*e[1],t.length=e=>Math.hypot(e[0],e[1]),t.distance=(e,n)=>{const r=n[0]-e[0],o=n[1]-e[1];return Math.hypot(r,o)},t.distanceSq=(e,n)=>{const r=n[0]-e[0],o=n[1]-e[1];return r*r+o*o},t.midPoint=(e,n)=>[(e[0]+n[0])/2,(e[1]+n[1])/2],t.angleTo=(e,n)=>Math.atan2(n[1]-e[1],n[0]-e[0]),t.angle=e=>Math.atan2(e[1],e[0]),t.fromPolar=(e,n,r=[0,0])=>[r[0]+Math.cos(n)*e,r[1]+Math.sin(n)*e],t.set=(e,n,r)=>{e[0]=n,e[1]=r},t.copy=(e,n)=>{e[0]=n[0],e[1]=n[1]},t.add=(e,n)=>{e[0]+=n[0],e[1]+=n[1]},t.addScalar=(e,n)=>{e[0]+=n,e[1]+=n},t.sub=(e,n)=>{e[0]-=n[0],e[1]-=n[1]},t.scale=(e,n)=>{e[0]*=n,e[1]*=n},t.multiply=(e,n)=>{e[0]*=n[0],e[1]*=n[1]},t.divide=(e,n)=>{(n[0]===0||n[1]===0)&&console.warn("Vec2.divide: division by zero, using 1 as divisor"),e[0]/=n[0]||1,e[1]/=n[1]||1},t.negate=e=>{e[0]=-e[0],e[1]=-e[1]},t.normalize=e=>{const n=(0,t.length)(e);n>0&&(e[0]/=n,e[1]/=n)},t.rotate=(e,n)=>{const r=Math.cos(n),o=Math.sin(n),s=e[0]*r-e[1]*o,i=e[0]*o+e[1]*r;e[0]=s,e[1]=i},t.rotateAround=(e,n,r)=>{(0,t.sub)(e,n),(0,t.rotate)(e,r),(0,t.add)(e,n)}})(z||(z={}));var qe=0,Je=1,St=2,Et=3,Gn=4,rt;(t=>{t.create=(e,n,r,o,s)=>[e,n,r,o,s],t.fromPoints=(e,n,r)=>[e[0],e[1],n[0],n[1],r],t.clone=e=>[e[0],e[1],e[2],e[3],e[4]],t.pointA=e=>[e[qe],e[Je]],t.pointB=e=>[e[St],e[Et]],t.radius=e=>e[Gn],t.center=e=>[(e[qe]+e[St])/2,(e[Je]+e[Et])/2],t.length=e=>{const n=e[St]-e[qe],r=e[Et]-e[Je];return Math.hypot(n,r)},t.bounds=e=>{const n=e[Gn];return[Math.min(e[qe],e[St])-n,Math.min(e[Je],e[Et])-n,Math.max(e[qe],e[St])+n,Math.max(e[Je],e[Et])+n]},t.getExtrema=e=>{const n=e[qe],r=e[Je],o=e[St],s=e[Et],i=e[Gn];return[[n-i,r-i],[n-i,r+i],[n+i,r-i],[n+i,r+i],[o-i,s-i],[o-i,s+i],[o+i,s-i],[o+i,s+i]]},t.closestPointOnSegmentParam=(e,n,r,o,s,i)=>{const a=r-e,l=o-n,c=a*a+l*l;if(c===0)return 0;const u=((s-e)*a+(i-n)*l)/c;return Math.max(0,Math.min(1,u))},t.closestPointOnCenterLine=(e,n)=>{const r=(0,t.closestPointOnSegmentParam)(e[qe],e[Je],e[St],e[Et],n[0],n[1]);return[e[qe]+r*(e[St]-e[qe]),e[Je]+r*(e[Et]-e[Je])]},t.distanceToPoint=(e,n)=>{const r=(0,t.closestPointOnCenterLine)(e,n);return z.distance(r,n)},t.containsPoint=(e,n)=>(0,t.distanceToPoint)(e,n)<=e[Gn],t.intersectsAabb=(e,n)=>{const r=e[Gn],o=(0,t.bounds)(e);if(!Q.intersects(o,n))return!1;const s=e[St]-e[qe],i=e[Et]-e[Je],a=s*s+i*i;if(a===0)return Q.distanceToPoint(n,[e[qe],e[Je]])<=r;n[0],n[1],n[2],n[3];const l=Math.max(1,Math.ceil(Math.sqrt(a)/r));for(let c=0;c<=l;c++){const u=c/l,d=e[qe]+u*s,h=e[Je]+u*i;if(Q.distanceToPoint(n,[d,h])<=r)return!0}return!1},t.intersectsCapsule=(e,n)=>(0,t.segmentToSegmentDistance)(e[qe],e[Je],e[St],e[Et],n[qe],n[Je],n[St],n[Et])<=e[Gn]+n[Gn],t.segmentToSegmentDistance=(e,n,r,o,s,i,a,l)=>{const c=r-e,u=o-n,d=a-s,h=l-i,p=e-s,m=n-i,g=c*c+u*u,y=c*d+u*h,w=d*d+h*h,k=c*p+u*m,b=d*p+h*m,S=g*w-y*y;let v,x;S<1e-10?(v=0,x=b/w):(v=(y*b-w*k)/S,x=(g*b-y*k)/S),v=Math.max(0,Math.min(1,v)),x=Math.max(0,Math.min(1,x)),(v<0||v>1)&&(x=(y*v+b)/w,x=Math.max(0,Math.min(1,x)),v=(y*x-k)/g,v=Math.max(0,Math.min(1,v)));const T=e+v*c,A=n+v*u,P=s+x*d,$=i+x*h;return Math.hypot(P-T,$-A)},t.set=(e,n,r,o,s,i)=>{e[qe]=n,e[Je]=r,e[St]=o,e[Et]=s,e[Gn]=i},t.copy=(e,n)=>{e[qe]=n[qe],e[Je]=n[Je],e[St]=n[St],e[Et]=n[Et],e[Gn]=n[Gn]},t.translate=(e,n)=>{e[qe]+=n[0],e[Je]+=n[1],e[St]+=n[0],e[Et]+=n[1]},t.trim=(e,n,r)=>{const o=e[qe],s=e[Je],i=e[St],a=e[Et],l=i-o,c=a-s;e[qe]=o+n*l,e[Je]=s+n*c,e[St]=o+r*l,e[Et]=s+r*c}})(rt||(rt={}));var Te;(t=>{t.create=(a,l,c,u,d,h)=>[a,l,c,u,d,h],t.identity=()=>[1,0,0,1,0,0],t.clone=a=>[a[0],a[1],a[2],a[3],a[4],a[5]],t.fromTranslation=(a,l)=>[1,0,0,1,a,l],t.fromScale=(a,l)=>[a,0,0,l??a,0,0],t.fromRotation=a=>{const l=Math.cos(a),c=Math.sin(a);return[l,c,-c,l,0,0]},t.fromSkew=(a,l)=>[1,Math.tan(l),Math.tan(a),1,0,0],t.getTranslation=a=>[a[4],a[5]],t.getScale=a=>{const l=Math.sqrt(a[0]*a[0]+a[1]*a[1]),c=Math.sqrt(a[2]*a[2]+a[3]*a[3]);return[l,c]},t.getRotation=a=>Math.atan2(a[1],a[0]),t.determinant=a=>a[0]*a[3]-a[1]*a[2],t.set=(a,l,c,u,d,h,p)=>{a[0]=l,a[1]=c,a[2]=u,a[3]=d,a[4]=h,a[5]=p},t.copy=(a,l)=>{a[0]=l[0],a[1]=l[1],a[2]=l[2],a[3]=l[3],a[4]=l[4],a[5]=l[5]},t.setIdentity=a=>{a[0]=1,a[1]=0,a[2]=0,a[3]=1,a[4]=0,a[5]=0},t.multiply=(a,l)=>{const c=a[0]*l[0]+a[2]*l[1],u=a[1]*l[0]+a[3]*l[1],d=a[0]*l[2]+a[2]*l[3],h=a[1]*l[2]+a[3]*l[3],p=a[0]*l[4]+a[2]*l[5]+a[4],m=a[1]*l[4]+a[3]*l[5]+a[5];a[0]=c,a[1]=u,a[2]=d,a[3]=h,a[4]=p,a[5]=m},t.premultiply=(a,l)=>{const c=l[0]*a[0]+l[2]*a[1],u=l[1]*a[0]+l[3]*a[1],d=l[0]*a[2]+l[2]*a[3],h=l[1]*a[2]+l[3]*a[3],p=l[0]*a[4]+l[2]*a[5]+l[4],m=l[1]*a[4]+l[3]*a[5]+l[5];a[0]=c,a[1]=u,a[2]=d,a[3]=h,a[4]=p,a[5]=m},t.invert=a=>{const l=(0,t.determinant)(a);if(l===0)return!1;const c=1/l,u=a[3]*c,d=-a[1]*c,h=-a[2]*c,p=a[0]*c,m=(a[2]*a[5]-a[3]*a[4])*c,g=(a[1]*a[4]-a[0]*a[5])*c;return a[0]=u,a[1]=d,a[2]=h,a[3]=p,a[4]=m,a[5]=g,!0},t.translate=(a,l,c)=>{a[4]+=a[0]*l+a[2]*c,a[5]+=a[1]*l+a[3]*c},t.scale=(a,l,c)=>{const u=c??l;a[0]*=l,a[1]*=l,a[2]*=u,a[3]*=u},t.rotate=(a,l)=>{const c=Math.cos(l),u=Math.sin(l),d=a[0]*c+a[2]*u,h=a[1]*c+a[3]*u,p=a[0]*-u+a[2]*c,m=a[1]*-u+a[3]*c;a[0]=d,a[1]=h,a[2]=p,a[3]=m},t.skew=(a,l,c)=>{const u=Math.tan(l),d=Math.tan(c),h=a[0]+a[2]*d,p=a[1]+a[3]*d,m=a[0]*u+a[2],g=a[1]*u+a[3];a[0]=h,a[1]=p,a[2]=m,a[3]=g},t.transformPoint=(a,l)=>{const c=a[0]*l[0]+a[2]*l[1]+a[4],u=a[1]*l[0]+a[3]*l[1]+a[5];l[0]=c,l[1]=u},t.transformVector=(a,l)=>{const c=a[0]*l[0]+a[2]*l[1],u=a[1]*l[0]+a[3]*l[1];l[0]=c,l[1]=u},t.inverseTransformPoint=(a,l)=>{const c=(0,t.determinant)(a);if(c===0)return!1;const u=1/c,d=l[0]-a[4],h=l[1]-a[5];return l[0]=(a[3]*d-a[2]*h)*u,l[1]=(a[0]*h-a[1]*d)*u,!0},t.equals=(a,l,c=1e-6)=>Math.abs(a[0]-l[0])<c&&Math.abs(a[1]-l[1])<c&&Math.abs(a[2]-l[2])<c&&Math.abs(a[3]-l[3])<c&&Math.abs(a[4]-l[4])<c&&Math.abs(a[5]-l[5])<c,t.isIdentity=(a,l=1e-6)=>Math.abs(a[0]-1)<l&&Math.abs(a[1])<l&&Math.abs(a[2])<l&&Math.abs(a[3]-1)<l&&Math.abs(a[4])<l&&Math.abs(a[5])<l,t.toCssMatrix=a=>`matrix(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]}, ${a[4]}, ${a[5]})`,t.fromCssMatrix=a=>{const l=a.match(/matrix\(\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^)]+)\s*\)/);if(!l)return null;const c=l.slice(1).map(Number);return c.some(Number.isNaN)?null:c}})(Te||(Te={}));var K=0,Y=1,ot;(t=>{t.getCenter=(e,n,r)=>{r[K]=e[K]+n[K]/2,r[Y]=e[Y]+n[Y]/2},t.getCorners=(e,n,r,o)=>{const s=n[K]/2,i=n[Y]/2,a=e[K]+s,l=e[Y]+i,c=Math.cos(r),u=Math.sin(r);o[0][K]=a+-s*c- -i*u,o[0][Y]=l+-s*u+-i*c,o[1][K]=a+s*c- -i*u,o[1][Y]=l+s*u+-i*c,o[2][K]=a+s*c-i*u,o[2][Y]=l+s*u+i*c,o[3][K]=a+-s*c-i*u,o[3][Y]=l+-s*u+i*c},t.getAabb=(e,n,r,o)=>{const s=n[K]/2,i=n[Y]/2,a=e[K]+s,l=e[Y]+i,c=Math.cos(r),u=Math.sin(r),d=a+-s*c- -i*u,h=l+-s*u+-i*c,p=a+s*c- -i*u,m=l+s*u+-i*c,g=a+s*c-i*u,y=l+s*u+i*c,w=a+-s*c-i*u,k=l+-s*u+i*c;o[0]=Math.min(d,p,g,w),o[1]=Math.min(h,m,y,k),o[2]=Math.max(d,p,g,w),o[3]=Math.max(h,m,y,k)},t.uvToWorld=(e,n,r,o)=>{const s=[(o[K]-.5)*n[K],(o[Y]-.5)*n[Y]];z.rotate(s,r);const i=[0,0];return(0,t.getCenter)(e,n,i),z.add(s,i),s},t.worldToUv=(e,n,r,o)=>{const s=[0,0];(0,t.getCenter)(e,n,s);const i=z.clone(o);return z.sub(i,s),z.rotate(i,-r),z.divide(i,n),z.addScalar(i,.5),i},t.getUvToWorldMatrix=(e,n,r,o)=>{const s=Math.cos(r),i=Math.sin(r),a=n[K],l=n[Y],c=e[K]+a/2,u=e[Y]+l/2;o[0]=a*s,o[1]=a*i,o[2]=-l*i,o[3]=l*s,o[4]=c-.5*(a*s-l*i),o[5]=u-.5*(a*i+l*s)},t.containsPoint=(e,n,r,o)=>{const s=n[K]/2,i=n[Y]/2,a=e[K]+s,l=e[Y]+i,c=o[K]-a,u=o[Y]-l,d=Math.cos(-r),h=Math.sin(-r),p=c*d-u*h,m=c*h+u*d;return p>=-s&&p<=s&&m>=-i&&m<=i},t.intersectsAabb=(e,n,r,o,s,i,a)=>{const l=n[K]/2,c=n[Y]/2,u=e[K]+l,d=e[Y]+c,h=Math.cos(r),p=Math.sin(r);i[0][K]=o[0],i[0][Y]=o[1],i[1][K]=o[2],i[1][Y]=o[1],i[2][K]=o[2],i[2][Y]=o[3],i[3][K]=o[0],i[3][Y]=o[3],s[0][K]=u+-l*h- -c*p,s[0][Y]=d+-l*p+-c*h,s[1][K]=u+l*h- -c*p,s[1][Y]=d+l*p+-c*h,s[2][K]=u+l*h-c*p,s[2][Y]=d+l*p+c*h,s[3][K]=u+-l*h-c*p,s[3][Y]=d+-l*p+c*h;const m=s[1][K]-s[0][K],g=s[1][Y]-s[0][Y],y=Math.sqrt(m*m+g*g);y>0&&(a[0][K]=-g/y,a[0][Y]=m/y);const w=s[2][K]-s[1][K],k=s[2][Y]-s[1][Y],b=Math.sqrt(w*w+k*k);return b>0&&(a[1][K]=-k/b,a[1][Y]=w/b),!(la(i,s,1,0)||la(i,s,0,1)||la(i,s,a[0][K],a[0][Y])||la(i,s,a[1][K],a[1][Y]))},t.setCenter=(e,n,r)=>{e[K]=r[K]-n[K]/2,e[Y]=r[Y]-n[Y]/2},t.translate=(e,n)=>{e[K]+=n[K],e[Y]+=n[Y]},t.scaleBy=(e,n,r)=>{const o=e[K]+n[K]/2,s=e[Y]+n[Y]/2;n[K]*=r,n[Y]*=r,e[K]=o-n[K]/2,e[Y]=s-n[Y]/2},t.scaleAround=(e,n,r,o)=>{const s=e[K]+n[K]/2,i=e[Y]+n[Y]/2,a=r[K]+(s-r[K])*o,l=r[Y]+(i-r[Y])*o;n[K]*=o,n[Y]*=o,e[K]=a-n[K]/2,e[Y]=l-n[Y]/2},t.rotateAround=(e,n,r,o,s)=>{const i=e[K]+n[K]/2,a=e[Y]+n[Y]/2,l=i-o[K],c=a-o[Y],u=Math.cos(s),d=Math.sin(s),h=o[K]+l*u-c*d,p=o[Y]+l*d+c*u;return e[K]=h-n[K]/2,e[Y]=p-n[Y]/2,r+s},t.boundPoints=(e,n,r,o)=>{if(o.length===0)return;if(r===0){let b=o[0][K],S=o[0][Y],v=b,x=S;for(let T=1;T<o.length;T++){const A=o[T][K],P=o[T][Y];A<b&&(b=A),P<S&&(S=P),A>v&&(v=A),P>x&&(x=P)}e[K]=b,e[Y]=S,n[K]=v-b,n[Y]=x-S;return}const s=Math.cos(-r),i=Math.sin(-r);let a=Number.POSITIVE_INFINITY,l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(const b of o){const S=b[K]*s-b[Y]*i,v=b[K]*i+b[Y]*s;S<a&&(a=S),v<l&&(l=v),S>c&&(c=S),v>u&&(u=v)}const d=(a+c)/2,h=(l+u)/2,p=c-a,m=u-l,g=Math.cos(r),y=Math.sin(r),w=d*g-h*y,k=d*y+h*g;e[K]=w-p/2,e[Y]=k-m/2,n[K]=p,n[Y]=m}})(ot||(ot={}));function la(t,e,n,r){let o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let l=0;l<4;l++){const c=t[l][0]*n+t[l][1]*r;c<o&&(o=c),c>s&&(s=c);const u=e[l][0]*n+e[l][1]*r;u<i&&(i=u),u>a&&(a=u)}return s<i||a<o}var mr=0,gr=1,Lr=2,Fr=3,lt;(t=>{t.create=(n,r,o,s)=>[n,r,o,s],t.fromPoints=(n,r)=>[n[0],n[1],r[0],r[1]],t.zero=()=>[0,0,0,0],t.clone=n=>[n[0],n[1],n[2],n[3]],t.origin=n=>[n[mr],n[gr]],t.direction=n=>[n[Lr],n[Fr]],t.set=(n,r,o,s,i)=>{n[mr]=r,n[gr]=o,n[Lr]=s,n[Fr]=i},t.copy=(n,r)=>{n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3]},t.setOrigin=(n,r)=>{n[mr]=r[0],n[gr]=r[1]},t.setDirection=(n,r)=>{n[Lr]=r[0],n[Fr]=r[1]},t.pointAt=(n,r)=>[n[mr]+n[Lr]*r,n[gr]+n[Fr]*r],t.intersectSegment=(n,r,o)=>{const s=n[mr],i=n[gr],a=n[Lr],l=n[Fr],c=r[0],u=r[1],d=o[0],h=o[1],p=d-c,m=h-u,g=a*m-l*p;if(Math.abs(g)<1e-10)return Gb(n,r,o);const y=c-s,w=u-i,k=(y*m-w*p)/g,b=(y*l-w*a)/g;if(k>=0&&b>=0&&b<=1){const S=s+k*a,v=i+k*l;return{point:[S,v],distance:k*Math.sqrt(a*a+l*l)}}return null},t.intersectAabb=(n,r)=>{const o=[],s=n[mr],i=n[gr],a=n[Lr],l=n[Fr],c=r[0],u=r[1],d=r[2],h=r[3];if(s>=c&&s<=d){if(i<h&&l>0||i>u&&l<0){const p=u-i;o.push({point:[s,u],distance:p})}if(i>u&&l<0||i<h&&l>0){const p=h-i;o.push({point:[s,h],distance:p})}}if(i>=u&&i<=h){if(s<c&&a>0||s>c&&a<0){const p=c-s;o.push({point:[c,i],distance:p})}if(s>c&&a<0||s<d&&a>0){const p=d-s;o.push({point:[d,i],distance:p})}}return o.sort((p,m)=>p.distance-m.distance),o};const e=[[0,0],[0,0],[0,0],[0,0]];t.intersectRect=(n,r,o,s=0)=>{ot.getCorners(r,o,s,e);const i=[];for(let a=0;a<4;a++){const l=(0,t.intersectSegment)(n,e[a],e[(a+1)%4]);l&&i.push(l)}return i.sort((a,l)=>a.distance-l.distance),i}})(lt||(lt={}));function Gb(t,e,n){const r=t[mr],o=t[gr],s=t[Lr],i=t[Fr];return e[0]===n[0]&&e[1]===n[1]?r===e[0]&&o===e[1]?{point:[r,o],distance:0}:null:i===0&&e[1]===n[1]&&o===e[1]?_h(t,e,n,0):s===0&&e[0]===n[0]&&r===e[0]?_h(t,e,n,1):null}function _h(t,e,n,r){const o=r===0?t[mr]:t[gr],s=r===0?t[Lr]:t[Fr],i=Math.min(e[r],n[r]),a=Math.max(e[r],n[r]);if(o>=i&&o<=a)return{point:[t[mr],t[gr]],distance:0};const l=[];return s>0?(e[r]>=o&&l.push({point:e,distance:e[r]-o}),n[r]>=o&&l.push({point:n,distance:n[r]-o})):s<0&&(e[r]<=o&&l.push({point:e,distance:o-e[r]}),n[r]<=o&&l.push({point:n,distance:o-n[r]})),l.length===0?null:l.reduce((c,u)=>u.distance<c.distance?u:c)}var Dc=Math.PI*2,Ct;(t=>{t.clamp=(e,n,r)=>Math.min(r,Math.max(n,e)),t.lerp=(e,n,r)=>e+(n-e)*r,t.normalizeAngle=e=>{const n=e%Dc;return n<0?n+Dc:n},t.normalizeAngleSigned=e=>{const n=(0,t.normalizeAngle)(e);return n>Math.PI?n-Dc:n},t.anglesApproxEqual=(e,n,r=1e-4)=>Math.abs((0,t.normalizeAngleSigned)(e-n))<r,t.approxEqual=(e,n,r=1e-4)=>Math.abs(e-n)<r})(Ct||(Ct={}));function I(t,e,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,l);const c=i.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){const h=u[d];h in a||(a[h]=c[h].bind(a))}}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var l;const c=n!=null&&n.Parent?new s:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>{var l,c;return n!=null&&n.Parent&&a instanceof n.Parent?!0:(c=(l=a==null?void 0:a._zod)==null?void 0:l.traits)==null?void 0:c.has(t)}}),Object.defineProperty(i,"name",{value:t}),i}class ds extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ah extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Ih={};function Vr(t){return Ih}function Bh(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function Oc(t,e){return typeof e=="bigint"?e.toString():e}function Rc(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function zc(t){return t==null}function $c(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Qb(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l!=null&&l[1]&&(o=Number.parseInt(l[1]))}const s=n>o?n:o,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}const Ph=Symbol("evaluating");function Ee(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Ph)return r===void 0&&(r=Ph,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function So(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Wr(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function Nh(t){return JSON.stringify(t)}function eS(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Dh="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ca(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const tS=Rc(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function fs(t){if(ca(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(ca(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Oh(t){return fs(t)?{...t}:Array.isArray(t)?[...t]:t}const nS=new Set(["string","number","symbol"]);function ua(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ur(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(r._zod.parent=t),r}function ee(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function rS(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const oS={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function sS(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=Wr(t._zod.def,{get shape(){const i={};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return So(this,"shape",i),i},checks:[]});return Ur(t,s)}function iS(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Wr(t._zod.def,{get shape(){const i={...t._zod.def.shape};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return So(this,"shape",i),i},checks:[]});return Ur(t,s)}function aS(t,e){if(!fs(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0){const s=t._zod.def.shape;for(const i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Wr(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return So(this,"shape",s),s}});return Ur(t,o)}function lS(t,e){if(!fs(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Wr(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return So(this,"shape",r),r}});return Ur(t,n)}function cS(t,e){const n=Wr(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return So(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Ur(t,n)}function uS(t,e,n){const o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=Wr(e._zod.def,{get shape(){const a=e._zod.def.shape,l={...a};if(n)for(const c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=t?new t({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)l[c]=t?new t({type:"optional",innerType:a[c]}):a[c];return So(this,"shape",l),l},checks:[]});return Ur(e,i)}function dS(t,e,n){const r=Wr(e._zod.def,{get shape(){const o=e._zod.def.shape,s={...o};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(const i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return So(this,"shape",s),s}});return Ur(e,r)}function hs(t,e=0){var n;if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(((n=t.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function Eo(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function da(t){return typeof t=="string"?t:t==null?void 0:t.message}function Hr(t,e,n){var o,s,i,a,l,c;const r={...t,path:t.path??[]};if(!t.message){const u=da((i=(s=(o=t.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,t))??da((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??da((l=n.customError)==null?void 0:l.call(n,t))??da((c=n.localeError)==null?void 0:c.call(n,t))??"Invalid input";r.message=u}return delete r.inst,delete r.continue,e!=null&&e.reportInput||delete r.input,r}function Lc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Gs(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Rh=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Oc,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},zh=I("$ZodError",Rh),fa=I("$ZodError",Rh,{Parent:Error});function fS(t,e=n=>n.message){const n={},r=[];for(const o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function hS(t,e=n=>n.message){const n={_errors:[]},r=o=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>r({issues:i}));else if(s.code==="invalid_key")r({issues:s.issues});else if(s.code==="invalid_element")r({issues:s.issues});else if(s.path.length===0)n._errors.push(e(s));else{let i=n,a=0;for(;a<s.path.length;){const l=s.path[a];a===s.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(e(s))):i[l]=i[l]||{_errors:[]},i=i[l],a++}}};return r(t),n}const ha=t=>(e,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new ds;if(i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>Hr(l,s,Vr())));throw Dh(a,o==null?void 0:o.callee),a}return i.value},$h=ha(fa),pa=t=>async(e,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>Hr(l,s,Vr())));throw Dh(a,o==null?void 0:o.callee),a}return i.value},Lh=pa(fa),ma=t=>(e,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new ds;return s.issues.length?{success:!1,error:new(t??zh)(s.issues.map(i=>Hr(i,o,Vr())))}:{success:!0,data:s.value}},pS=ma(fa),ga=t=>async(e,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Hr(i,o,Vr())))}:{success:!0,data:s.value}},mS=ga(fa),gS=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ha(t)(e,n,o)},yS=t=>(e,n,r)=>ha(t)(e,n,r),wS=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return pa(t)(e,n,o)},kS=t=>async(e,n,r)=>pa(t)(e,n,r),vS=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ma(t)(e,n,o)},bS=t=>(e,n,r)=>ma(t)(e,n,r),SS=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ga(t)(e,n,o)},ES=t=>async(e,n,r)=>ga(t)(e,n,r),CS=/^[cC][^\s-]{8,}$/,xS=/^[0-9a-z]+$/,TS=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,MS=/^[0-9a-vA-V]{20}$/,_S=/^[A-Za-z0-9]{27}$/,AS=/^[a-zA-Z0-9_-]{21}$/,IS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,BS=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Fh=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,PS=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,NS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function DS(){return new RegExp(NS,"u")}const OS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,RS=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,zS=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,$S=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,LS=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vh=/^[A-Za-z0-9_-]*$/,FS=/^\+[1-9]\d{6,14}$/,Wh="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",VS=new RegExp(`^${Wh}$`);function Uh(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function WS(t){return new RegExp(`^${Uh(t)}$`)}function US(t){const e=Uh({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Wh}T(?:${r})$`)}const HS=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},jS=/^-?\d+$/,Hh=/^-?\d+(?:\.\d+)?$/,ZS=/^(?:true|false)$/i,KS=/^[^A-Z]*$/,YS=/^[^a-z]*$/,Yt=I("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),jh={number:"number",bigint:"bigint",object:"date"},Zh=I("$ZodCheckLessThan",(t,e)=>{Yt.init(t,e);const n=jh[typeof e.value];t._zod.onattach.push(r=>{const o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Kh=I("$ZodCheckGreaterThan",(t,e)=>{Yt.init(t,e);const n=jh[typeof e.value];t._zod.onattach.push(r=>{const o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),qS=I("$ZodCheckMultipleOf",(t,e)=>{Yt.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Qb(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),JS=I("$ZodCheckNumberFormat",(t,e)=>{var i;Yt.init(t,e),e.format=e.format||"float64";const n=(i=e.format)==null?void 0:i.includes("int"),r=n?"int":"number",[o,s]=oS[e.format];t._zod.onattach.push(a=>{const l=a._zod.bag;l.format=e.format,l.minimum=o,l.maximum=s,n&&(l.pattern=jS)}),t._zod.check=a=>{const l=a.value;if(n){if(!Number.isInteger(l)){a.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?a.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):a.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}l<o&&a.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),l>s&&a.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}}),XS=I("$ZodCheckMaxLength",(t,e)=>{var n;Yt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!zc(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const o=r.value;if(o.length<=e.maximum)return;const i=Lc(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),GS=I("$ZodCheckMinLength",(t,e)=>{var n;Yt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!zc(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const o=r.value;if(o.length>=e.minimum)return;const i=Lc(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),QS=I("$ZodCheckLengthEquals",(t,e)=>{var n;Yt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!zc(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{const o=r.value,s=o.length;if(s===e.length)return;const i=Lc(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),ya=I("$ZodCheckStringFormat",(t,e)=>{var n,r;Yt.init(t,e),t._zod.onattach.push(o=>{const s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),eE=I("$ZodCheckRegex",(t,e)=>{ya.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),tE=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=KS),ya.init(t,e)}),nE=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=YS),ya.init(t,e)}),rE=I("$ZodCheckIncludes",(t,e)=>{Yt.init(t,e);const n=ua(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),oE=I("$ZodCheckStartsWith",(t,e)=>{Yt.init(t,e);const n=new RegExp(`^${ua(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),sE=I("$ZodCheckEndsWith",(t,e)=>{Yt.init(t,e);const n=new RegExp(`.*${ua(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),iE=I("$ZodCheckOverwrite",(t,e)=>{Yt.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class aE{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
1
+ (function($,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],d):($=typeof globalThis<"u"?globalThis:$||self,d($.Vue={},$.Vue))})(this,function($,d){"use strict";var kV=Object.defineProperty;var vV=($,d,Lr)=>d in $?kV($,d,{enumerable:!0,configurable:!0,writable:!0,value:Lr}):$[d]=Lr;var x=($,d,Lr)=>vV($,typeof d!="symbol"?d+"":d,Lr);var fr,Rr,zr,Nn,as,ls,cs,Pt,De,us,hr;const Lr=(t,e)=>e.some(n=>t instanceof n);let lh,ch;function Fv(){return lh||(lh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Wv(){return ch||(ch=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Ic=new WeakMap,Bc=new WeakMap,da=new WeakMap;function Uv(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(Eo(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return da.set(e,t),e}function Hv(t){if(Ic.has(t))return;const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",i),t.removeEventListener("abort",i)},s=()=>{n(),o()},i=()=>{r(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",s),t.addEventListener("error",i),t.addEventListener("abort",i)});Ic.set(t,e)}let Nc={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return Ic.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Eo(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function uh(t){Nc=t(Nc)}function jv(t){return Wv().includes(t)?function(...e){return t.apply(Pc(this),e),Eo(this.request)}:function(...e){return Eo(t.apply(Pc(this),e))}}function Zv(t){return typeof t=="function"?jv(t):(t instanceof IDBTransaction&&Hv(t),Lr(t,Fv())?new Proxy(t,Nc):t)}function Eo(t){if(t instanceof IDBRequest)return Uv(t);if(Bc.has(t))return Bc.get(t);const e=Zv(t);return e!==t&&(Bc.set(t,e),da.set(e,t)),e}const Pc=t=>da.get(t);function dh(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=Eo(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Eo(i.result),l.oldVersion,l.newVersion,Eo(i.transaction),l)}),n&&i.addEventListener("blocked",l=>n(l.oldVersion,l.newVersion,l)),a.then(l=>{s&&l.addEventListener("close",()=>s()),o&&l.addEventListener("versionchange",c=>o(c.oldVersion,c.newVersion,c))}).catch(()=>{}),a}const Kv=["get","getKey","getAll","getAllKeys","count"],Yv=["put","add","delete","clear"],Dc=new Map;function fh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Dc.get(e))return Dc.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=Yv.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||Kv.includes(n)))return;const s=async function(i,...a){const l=this.transaction(i,o?"readwrite":"readonly");let c=l.store;return r&&(c=c.index(a.shift())),(await Promise.all([c[n](...a),o&&l.done]))[0]};return Dc.set(e,s),s}uh(t=>({...t,get:(e,n,r)=>fh(e,n)||t.get(e,n,r),has:(e,n)=>!!fh(e,n)||t.has(e,n)}));const qv=["continue","continuePrimaryKey","advance"],hh={},Oc=new WeakMap,ph=new WeakMap,Xv={get(t,e){if(!qv.includes(e))return t[e];let n=hh[e];return n||(n=hh[e]=function(...r){Oc.set(this,ph.get(this)[e](...r))}),n}};async function*Gv(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;e=e;const n=new Proxy(e,Xv);for(ph.set(n,e),da.set(n,Pc(e));e;)yield n,e=await(Oc.get(n)||e.continue()),Oc.delete(n)}function mh(t,e){return e===Symbol.asyncIterator&&Lr(t,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&Lr(t,[IDBIndex,IDBObjectStore])}uh(t=>({...t,get(e,n,r){return mh(e,n)?Gv:t.get(e,n,r)},has(e,n){return mh(e,n)||t.has(e,n)}}));var Zt=Symbol("schemaDefault"),mr=class{},Jv=new Set(["string","number","boolean","binary"]);function gh(t,e){const n=t.def.type;if(!Jv.has(n))throw new Error(`Invalid ${e} element type: "${n}". Only primitive types are allowed: string, number, boolean, binary. Nested ${e}s, tuples, arrays, enums, and refs are not supported.`)}var Qv=class extends mr{constructor(){super(...arguments);x(this,"def",{type:"string"})}max(e){return this.def.maxLength=e,this}default(e){return this.def.default=e,this}[Zt](){return this.def.default??""}},Vr=class extends mr{constructor(e){super();x(this,"def");this.def={type:"number",btype:e}}default(e){return this.def.default=e,this}[Zt](){return this.def.default??0}},eb=class extends mr{constructor(){super(...arguments);x(this,"def",{type:"boolean"})}default(e){return this.def.default=e,this}[Zt](){return this.def.default??!1}},tb=class extends mr{constructor(){super(...arguments);x(this,"def",{type:"binary"})}max(e){return this.def.maxLength=e,this}default(e){return this.def.default=e,this}[Zt](){return this.def.default??new Uint8Array(0)}},nb=class extends mr{constructor(e,n){super();x(this,"def");gh(e,"array"),this.def={type:"array",elementDef:e.def,maxLength:n}}default(e){return this.def.default=e,this}[Zt](){return this.def.default??[]}},rb=class extends mr{constructor(e,n){super();x(this,"def");x(this,"elementBuilder");gh(e,"tuple"),this.elementBuilder=e,this.def={type:"tuple",elementDef:e.def,length:n}}default(e){return this.def.default=e,this}[Zt](){if(this.def.default)return this.def.default;const e=this.elementBuilder[Zt]();return new Array(this.def.length).fill(e)}},ob=class extends mr{constructor(e){super();x(this,"def");this.def={type:"buffer",elementDef:e.def,size:0}}size(e){return this.def.size=e,this}default(e){return this.def.default=e,this}[Zt](){return this.def.default??new Array(this.def.size).fill(0)}},sb=class extends mr{constructor(e){super();x(this,"def");this.def={type:"enum",values:Object.values(e)}}default(e){return this.def.default=e,this}[Zt](){return this.def.default!==void 0?this.def.default:[...this.def.values].sort()[0]}},ib=class extends mr{constructor(){super(...arguments);x(this,"def",{type:"ref"})}[Zt](){return null}},C={string:()=>new Qv,uint8:()=>new Vr("uint8"),uint16:()=>new Vr("uint16"),uint32:()=>new Vr("uint32"),int8:()=>new Vr("int8"),int16:()=>new Vr("int16"),int32:()=>new Vr("int32"),float32:()=>new Vr("float32"),float64:()=>new Vr("float64"),boolean:()=>new eb,binary:()=>new tb,enum:t=>new sb(t),array:(t,e)=>new nb(t,e),tuple:(t,e)=>new rb(t,e),buffer:t=>new ob(t),ref:()=>new ib},gr=class{constructor(t){x(this,"fieldDef");this.fieldDef=t}getDefaultValue(){return this.fieldDef.schemaDefault}};function fs(t){switch(t){case"uint8":case"int8":return 1;case"uint16":case"int16":return 2;case"uint32":case"int32":case"float32":return 4;case"float64":return 8}}function ab(t,e,n){switch(t){case"uint8":return new Uint8Array(n,0,e);case"uint16":return new Uint16Array(n,0,e);case"uint32":return new Uint32Array(n,0,e);case"int8":return new Int8Array(n,0,e);case"int16":return new Int16Array(n,0,e);case"int32":return new Int32Array(n,0,e);case"float32":return new Float32Array(n,0,e);case"float64":return new Float64Array(n,0,e)}}function lb(t){return t!=="float32"&&t!=="float64"}var cb=class extends gr{constructor(e){super(e);x(this,"useAtomics");this.useAtomics=lb(e.btype)}initializeStorage(e,n){const r=fs(this.fieldDef.btype),o=new n(e*r),s=ab(this.fieldDef.btype,e,o);return{buffer:o,view:s}}defineReadonly(e,n,r,o){const s=this.useAtomics;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n];return s?Atomics.load(i,o()):i[o()]}})}defineWritable(e,n,r,o){const s=this.useAtomics;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n];return s?Atomics.load(i,o()):i[o()]},set:i=>{const a=r[n];s?Atomics.store(a,o(),i):a[o()]=i}})}setValue(e,n,r){this.useAtomics?Atomics.store(e,n,r):e[n]=r}},ub=512,db=256,yh=new TextEncoder,wh=new TextDecoder;function kh(t){switch(t.type){case"number":return fs(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||ub;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||db;return Math.ceil((e+4)/4)*4}}}function fa(t,e,n,r){switch(t){case"float32":return new Float32Array(n,r,e);case"float64":return new Float64Array(n,r,e);case"int8":return new Int8Array(n,r,e);case"int16":return new Int16Array(n,r,e);case"int32":return new Int32Array(n,r,e);case"uint8":return new Uint8Array(n,r,e);case"uint16":return new Uint16Array(n,r,e);case"uint32":return new Uint32Array(n,r,e);default:throw new Error(`Unknown btype: ${t}`)}}var vh=(fr=class{constructor(e,n,r,o,s){x(this,"buffer");x(this,"uint8View");x(this,"bytesPerEntry");x(this,"bytesPerElement");x(this,"capacity");x(this,"elementDef");x(this,"maxLength");this.buffer=e,this.uint8View=new Uint8Array(e),this.bytesPerEntry=r,this.bytesPerElement=kh(o),this.capacity=n,this.elementDef=o,this.maxLength=s}get length(){return this.capacity}readUint32(e){const n=Atomics.load(this.uint8View,e),r=Atomics.load(this.uint8View,e+1),o=Atomics.load(this.uint8View,e+2),s=Atomics.load(this.uint8View,e+3);return n|r<<8|o<<16|s<<24}writeUint32(e,n){Atomics.store(this.uint8View,e,n&255),Atomics.store(this.uint8View,e+1,n>>8&255),Atomics.store(this.uint8View,e+2,n>>16&255),Atomics.store(this.uint8View,e+3,n>>24&255)}get(e){const n=e*this.bytesPerEntry,r=this.readUint32(n);if(r===0)return[];const o=n+fr.LENGTH_BYTES,s=[];switch(this.elementDef.type){case"number":{const i=fa(this.elementDef.btype,r,this.buffer,o),a=this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64";for(let l=0;l<r;l++)a?s.push(Atomics.load(i,l)):s.push(i[l]);break}case"boolean":{for(let i=0;i<r;i++)s.push(Atomics.load(this.uint8View,o+i)!==0);break}case"string":{for(let i=0;i<r;i++){const a=o+i*this.bytesPerElement,l=this.readUint32(a);if(l===0)s.push("");else{const c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=Atomics.load(this.uint8View,a+4+u);s.push(wh.decode(c))}}break}case"binary":{for(let i=0;i<r;i++){const a=o+i*this.bytesPerElement,l=this.readUint32(a);if(l===0)s.push(new Uint8Array(0));else{const c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=Atomics.load(this.uint8View,a+4+u);s.push(c)}}break}}return s}set(e,n){const r=e*this.bytesPerEntry,o=Math.min(n.length,this.maxLength);this.writeUint32(r,o);const s=r+fr.LENGTH_BYTES,i=this.maxLength*this.bytesPerElement;for(let a=0;a<i;a++)Atomics.store(this.uint8View,s+a,0);if(o!==0)switch(this.elementDef.type){case"number":{const a=fa(this.elementDef.btype,o,this.buffer,s),l=this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64";for(let c=0;c<o;c++)l?Atomics.store(a,c,n[c]):a[c]=n[c];break}case"boolean":{for(let a=0;a<o;a++)Atomics.store(this.uint8View,s+a,n[a]?1:0);break}case"string":{const a=this.bytesPerElement-4;for(let l=0;l<o;l++){const c=s+l*this.bytesPerElement,u=n[l],f=yh.encode(u),h=Math.min(f.length,a);this.writeUint32(c,h);for(let p=0;p<h;p++)Atomics.store(this.uint8View,c+4+p,f[p])}break}case"binary":{const a=this.bytesPerElement-4;for(let l=0;l<o;l++){const c=s+l*this.bytesPerElement,u=n[l],f=Math.min(u.length,a);this.writeUint32(c,f);for(let h=0;h<f;h++)Atomics.store(this.uint8View,c+4+h,u[h])}break}}}getElement(e,n){const r=e*this.bytesPerEntry,o=this.readUint32(r);if(n<0||n>=o)return;const s=r+fr.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const i=fa(this.elementDef.btype,o,this.buffer,s);return this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64"?Atomics.load(i,n):i[n]}case"boolean":return Atomics.load(this.uint8View,s+n)!==0;case"string":{const i=s+n*this.bytesPerElement,a=this.readUint32(i);if(a===0)return"";const l=new Uint8Array(a);for(let c=0;c<a;c++)l[c]=Atomics.load(this.uint8View,i+4+c);return wh.decode(l)}case"binary":{const i=s+n*this.bytesPerElement,a=this.readUint32(i);if(a===0)return new Uint8Array(0);const l=new Uint8Array(a);for(let c=0;c<a;c++)l[c]=Atomics.load(this.uint8View,i+4+c);return l}}}setElement(e,n,r){if(n<0||n>=this.maxLength)return;const o=e*this.bytesPerEntry;let s=this.readUint32(o);n>=s&&(s=n+1,this.writeUint32(o,s));const i=o+fr.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const a=fa(this.elementDef.btype,this.maxLength,this.buffer,i);this.elementDef.btype!=="float32"&&this.elementDef.btype!=="float64"?Atomics.store(a,n,r):a[n]=r;break}case"boolean":{Atomics.store(this.uint8View,i+n,r?1:0);break}case"string":{const a=i+n*this.bytesPerElement,l=r,c=yh.encode(l),u=this.bytesPerElement-4,f=Math.min(c.length,u);for(let h=0;h<u;h++)Atomics.store(this.uint8View,a+4+h,0);this.writeUint32(a,f);for(let h=0;h<f;h++)Atomics.store(this.uint8View,a+4+h,c[h]);break}case"binary":{const a=i+n*this.bytesPerElement,l=r,c=this.bytesPerElement-4,u=Math.min(l.length,c);for(let f=0;f<c;f++)Atomics.store(this.uint8View,a+4+f,0);this.writeUint32(a,u);for(let f=0;f<u;f++)Atomics.store(this.uint8View,a+4+f,l[f]);break}}}getStoredLength(e){const n=e*this.bytesPerEntry;return this.readUint32(n)}getMaxLength(){return this.maxLength}getBuffer(){return this.buffer}getBytesPerEntry(){return this.bytesPerEntry}},x(fr,"LENGTH_BYTES",4),fr),fb=class extends gr{initializeStorage(t,e){const n=kh(this.fieldDef.elementDef),r=this.fieldDef.maxLength*n+vh.LENGTH_BYTES,o=Math.ceil(r/8)*8,s=new e(t*o),i=new vh(s,t,o,this.fieldDef.elementDef,this.fieldDef.maxLength);return{buffer:s,view:i}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>{const o=n[e],s=r(),i=new Set(["push","pop","shift","unshift","splice","reverse","sort","fill","copyWithin"]);return new Proxy([],{get(a,l){if(typeof l=="string"&&/^\d+$/.test(l)){const f=parseInt(l,10);return o.getElement(s,f)}if(l==="length")return o.getStoredLength(s);if(typeof l=="string"&&i.has(l))return(...f)=>{const h=o.get(s),p=h[l](...f);return o.set(s,h),p};const c=o.get(s),u=c[l];return typeof u=="function"?u.bind(c):u},set(a,l,c){if(typeof l=="string"&&/^\d+$/.test(l)){const u=parseInt(l,10);return o.setElement(s,u,c),!0}return!1},has(a,l){if(typeof l=="string"&&/^\d+$/.test(l)){const c=parseInt(l,10);return c>=0&&c<o.getStoredLength(s)}return l in[]},ownKeys(){const a=o.getStoredLength(s),l=[];for(let c=0;c<a;c++)l.push(String(c));return l.push("length"),l},getOwnPropertyDescriptor(a,l){if(typeof l=="string"&&/^\d+$/.test(l)){const c=parseInt(l,10);if(c>=0&&c<o.getStoredLength(s))return{value:o.getElement(s,c),writable:!0,enumerable:!0,configurable:!0}}if(l==="length")return{value:o.getStoredLength(s),writable:!1,enumerable:!1,configurable:!1}}})},set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){t.set(e,n)}},hb=256,bh=(Rr=class{constructor(e,n,r){x(this,"buffer");x(this,"bytesPerEntry");x(this,"capacity");this.buffer=new Uint8Array(e),this.bytesPerEntry=r,this.capacity=n}get length(){return this.capacity}get(e){const n=e*this.bytesPerEntry,r=Atomics.load(this.buffer,n),o=Atomics.load(this.buffer,n+1),s=Atomics.load(this.buffer,n+2),i=Atomics.load(this.buffer,n+3),a=r|o<<8|s<<16|i<<24;if(a===0)return new Uint8Array(0);const l=n+Rr.LENGTH_BYTES,c=new Uint8Array(a);for(let u=0;u<a;u++)c[u]=Atomics.load(this.buffer,l+u);return c}set(e,n){const r=e*this.bytesPerEntry,o=this.bytesPerEntry-Rr.LENGTH_BYTES,s=Math.min(n.length,o);Atomics.store(this.buffer,r,s&255),Atomics.store(this.buffer,r+1,s>>8&255),Atomics.store(this.buffer,r+2,s>>16&255),Atomics.store(this.buffer,r+3,s>>24&255);const i=r+Rr.LENGTH_BYTES;for(let a=0;a<o;a++)Atomics.store(this.buffer,i+a,0);for(let a=0;a<s;a++)Atomics.store(this.buffer,i+a,n[a])}getBuffer(){return this.buffer}},x(Rr,"LENGTH_BYTES",4),Rr),pb=class extends gr{initializeStorage(t,e){const r=(this.fieldDef.maxLength||hb)+bh.LENGTH_BYTES,o=new e(t*r),s=new bh(o,t,r);return{buffer:o,view:s}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){t.set(e,n)}},mb=class extends gr{initializeStorage(t,e){const n=new e(t),r=new Uint8Array(n,0,t);return{buffer:n,view:r}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>{const o=n[e];return!!Atomics.load(o,r())}})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>{const o=n[e];return!!Atomics.load(o,r())},set:o=>{const s=n[e];Atomics.store(s,r(),o?1:0)}})}setValue(t,e,n){Atomics.store(t,e,n?1:0)}};function gb(t,e,n,r){switch(t){case"float32":return new Float32Array(n,r,e);case"float64":return new Float64Array(n,r,e);case"int8":return new Int8Array(n,r,e);case"int16":return new Int16Array(n,r,e);case"int32":return new Int32Array(n,r,e);case"uint8":return new Uint8Array(n,r,e);case"uint16":return new Uint16Array(n,r,e);case"uint32":return new Uint32Array(n,r,e);default:throw new Error(`Unknown btype: ${t}`)}}var yb=class{constructor(t,e,n,r,o){x(this,"buffer");x(this,"bytesPerEntry");x(this,"bytesPerElement");x(this,"capacity");x(this,"bufferSize");x(this,"numberTypedArray");x(this,"elementsPerEntry");this.buffer=t,this.bytesPerEntry=n,this.bytesPerElement=fs(r.btype),this.capacity=e,this.bufferSize=o,this.elementsPerEntry=n/this.bytesPerElement,this.numberTypedArray=gb(r.btype,e*this.elementsPerEntry,t,0)}get length(){return this.capacity}get(t){const e=t*this.elementsPerEntry;return this.numberTypedArray.subarray(e,e+this.bufferSize)}set(t,e){const n=t*this.elementsPerEntry,r=Math.min(e.length,this.bufferSize);for(let o=0;o<r;o++)this.numberTypedArray[n+o]=e[o];for(let o=r;o<this.bufferSize;o++)this.numberTypedArray[n+o]=0}getBuffer(){return this.buffer}getBytesPerEntry(){return this.bytesPerEntry}getSize(){return this.bufferSize}},wb=class extends gr{initializeStorage(t,e){const n=fs(this.fieldDef.elementDef.btype),r=this.fieldDef.size*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new yb(s,t,o,this.fieldDef.elementDef,this.fieldDef.size);return{buffer:s,view:i}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){if(n&&typeof n=="object"&&!Array.isArray(n)&&n.length===void 0){const r=[];let o=0;for(;o in n;)r.push(n[o]),o++;n=r}t.set(e,n??[])}},kb=class extends gr{constructor(e){super(e);x(this,"sortedValues");x(this,"valueToIndex");this.sortedValues=[...e.values].sort(),this.valueToIndex=new Map,this.sortedValues.forEach((n,r)=>{this.valueToIndex.set(n,r)})}initializeStorage(e,n){const r=new n(e*2),o=new Uint16Array(r);return{buffer:r,view:o}}defineReadonly(e,n,r,o){const s=this.sortedValues;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n],a=Atomics.load(i,o());return s[a]??s[0]??""}})}defineWritable(e,n,r,o){const s=this.sortedValues,i=this.valueToIndex;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const a=r[n],l=Atomics.load(a,o());return s[l]??s[0]??""},set:a=>{const l=r[n],c=i.get(a);c!==void 0&&Atomics.store(l,o(),c)}})}setValue(e,n,r){if(typeof r=="string"){const o=this.valueToIndex.get(r);Atomics.store(e,n,o!==void 0?o:0)}else Atomics.store(e,n,r)}},Xn=4294967295,Sh=33554431,Eh=25;function Ch(t,e){return t&Sh|e<<Eh}function vb(t){return t&Sh}function bb(t){return t>>>Eh}function Rc(t,e,n=!0){if(t===Xn)return null;const r=vb(t),o=bb(t);return n&&!e.has(r)||e.getGeneration(r)!==o?null:r}var Sb=class extends gr{constructor(e,n){super(e);x(this,"entityBuffer");this.entityBuffer=n}initializeStorage(e,n){const r=new n(e*4),o=new Uint32Array(r);return o.fill(Xn),{buffer:r,view:o}}defineReadonly(e,n,r,o){const s=this.entityBuffer;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n],a=o(),l=Atomics.load(i,a),c=Rc(l,s);return l!==Xn&&c===null&&Atomics.store(i,a,Xn),c}})}defineWritable(e,n,r,o){const s=this.entityBuffer;Object.defineProperty(e,n,{enumerable:!0,configurable:!1,get:()=>{const i=r[n],a=o(),l=Atomics.load(i,a),c=Rc(l,s);return l!==Xn&&c===null&&Atomics.store(i,a,Xn),c},set:i=>{const a=r[n],l=o();if(i===null||i===Xn)Atomics.store(a,l,Xn);else{const c=s.getGeneration(i);Atomics.store(a,l,Ch(i,c))}}})}setValue(e,n,r){if(r===null||r===Xn)Atomics.store(e,n,Xn);else{const o=this.entityBuffer.getGeneration(r);Atomics.store(e,n,Ch(r,o))}}},Eb=512,Cb=new TextEncoder,xb=new TextDecoder,xh=(zr=class{constructor(e,n,r){x(this,"buffer");x(this,"bytesPerString");x(this,"capacity");this.buffer=new Uint8Array(e),this.bytesPerString=r,this.capacity=n}get length(){return this.capacity}get(e){const n=e*this.bytesPerString,r=Atomics.load(this.buffer,n),o=Atomics.load(this.buffer,n+1),s=Atomics.load(this.buffer,n+2),i=Atomics.load(this.buffer,n+3),a=r|o<<8|s<<16|i<<24;if(a===0)return"";const l=n+zr.LENGTH_BYTES,c=new Uint8Array(a);for(let u=0;u<a;u++)c[u]=Atomics.load(this.buffer,l+u);return xb.decode(c)}set(e,n){const r=e*this.bytesPerString,o=Cb.encode(n),s=this.bytesPerString-zr.LENGTH_BYTES,i=Math.min(o.length,s);Atomics.store(this.buffer,r,i&255),Atomics.store(this.buffer,r+1,i>>8&255),Atomics.store(this.buffer,r+2,i>>16&255),Atomics.store(this.buffer,r+3,i>>24&255);const a=r+zr.LENGTH_BYTES;for(let l=0;l<s;l++)Atomics.store(this.buffer,a+l,0);for(let l=0;l<i;l++)Atomics.store(this.buffer,a+l,o[l])}getBuffer(){return this.buffer}},x(zr,"LENGTH_BYTES",4),zr),Tb=class extends gr{initializeStorage(t,e){const r=(this.fieldDef.maxLength||Eb)+xh.LENGTH_BYTES,o=new e(t*r),s=new xh(o,t,r);return{buffer:o,view:s}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){t.set(e,n)}},Mb=512,Ab=256,_b=new TextEncoder,Ib=new TextDecoder;function Th(t){switch(t.type){case"number":return fs(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||Mb;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||Ab;return Math.ceil((e+4)/4)*4}}}function Bb(t,e,n,r){switch(t){case"float32":return new Float32Array(n,r,e);case"float64":return new Float64Array(n,r,e);case"int8":return new Int8Array(n,r,e);case"int16":return new Int16Array(n,r,e);case"int32":return new Int32Array(n,r,e);case"uint8":return new Uint8Array(n,r,e);case"uint16":return new Uint16Array(n,r,e);case"uint32":return new Uint32Array(n,r,e);default:throw new Error(`Unknown btype: ${t}`)}}var Nb=class{constructor(t,e,n,r,o){x(this,"buffer");x(this,"uint8View");x(this,"bytesPerEntry");x(this,"bytesPerElement");x(this,"capacity");x(this,"elementDef");x(this,"tupleLength");x(this,"numberTypedArray",null);x(this,"elementsPerEntry",0);if(this.buffer=t,this.uint8View=new Uint8Array(t),this.bytesPerEntry=n,this.bytesPerElement=Th(r),this.capacity=e,this.elementDef=r,this.tupleLength=o,r.type==="number"){const s=fs(r.btype);this.elementsPerEntry=n/s,this.numberTypedArray=Bb(r.btype,e*this.elementsPerEntry,t,0)}}get length(){return this.capacity}readUint32(t){const e=Atomics.load(this.uint8View,t),n=Atomics.load(this.uint8View,t+1),r=Atomics.load(this.uint8View,t+2),o=Atomics.load(this.uint8View,t+3);return e|n<<8|r<<16|o<<24}writeUint32(t,e){Atomics.store(this.uint8View,t,e&255),Atomics.store(this.uint8View,t+1,e>>8&255),Atomics.store(this.uint8View,t+2,e>>16&255),Atomics.store(this.uint8View,t+3,e>>24&255)}get(t){if(this.numberTypedArray!==null){const r=t*this.elementsPerEntry;return this.numberTypedArray.subarray(r,r+this.tupleLength)}const e=t*this.bytesPerEntry,n=[];switch(this.elementDef.type){case"boolean":{for(let r=0;r<this.tupleLength;r++)n.push(Atomics.load(this.uint8View,e+r)!==0);break}case"string":{for(let r=0;r<this.tupleLength;r++){const o=e+r*this.bytesPerElement,s=this.readUint32(o);if(s===0)n.push("");else{const i=new Uint8Array(s);for(let a=0;a<s;a++)i[a]=Atomics.load(this.uint8View,o+4+a);n.push(Ib.decode(i))}}break}case"binary":{for(let r=0;r<this.tupleLength;r++){const o=e+r*this.bytesPerElement,s=this.readUint32(o);if(s===0)n.push(new Uint8Array(0));else{const i=new Uint8Array(s);for(let a=0;a<s;a++)i[a]=Atomics.load(this.uint8View,o+4+a);n.push(i)}}break}}return n}set(t,e){if(this.numberTypedArray!==null){const s=t*this.elementsPerEntry,i=Math.min(e.length,this.tupleLength);for(let a=0;a<i;a++)this.numberTypedArray[s+a]=e[a];for(let a=i;a<this.tupleLength;a++)this.numberTypedArray[s+a]=0;return}const n=t*this.bytesPerEntry,r=Math.min(e.length,this.tupleLength),o=this.tupleLength*this.bytesPerElement;for(let s=0;s<o;s++)Atomics.store(this.uint8View,n+s,0);if(r!==0)switch(this.elementDef.type){case"boolean":{for(let s=0;s<r;s++)Atomics.store(this.uint8View,n+s,e[s]?1:0);break}case"string":{const s=this.bytesPerElement-4;for(let i=0;i<r;i++){const a=n+i*this.bytesPerElement,l=e[i],c=_b.encode(l),u=Math.min(c.length,s);this.writeUint32(a,u);for(let f=0;f<u;f++)Atomics.store(this.uint8View,a+4+f,c[f])}break}case"binary":{const s=this.bytesPerElement-4;for(let i=0;i<r;i++){const a=n+i*this.bytesPerElement,l=e[i],c=Math.min(l.length,s);this.writeUint32(a,c);for(let u=0;u<c;u++)Atomics.store(this.uint8View,a+4+u,l[u])}break}}}getBuffer(){return this.buffer}getBytesPerEntry(){return this.bytesPerEntry}},Pb=class extends gr{initializeStorage(t,e){const n=Th(this.fieldDef.elementDef),r=this.fieldDef.length*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new Nb(s,t,o,this.fieldDef.elementDef,this.fieldDef.length);return{buffer:s,view:i}}defineReadonly(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r())})}defineWritable(t,e,n,r){Object.defineProperty(t,e,{enumerable:!0,configurable:!1,get:()=>n[e].get(r()),set:o=>{n[e].set(r(),o)}})}setValue(t,e,n){if(n&&typeof n=="object"&&!Array.isArray(n)&&n.length===void 0){const r=new Array(this.fieldDef.length);for(let o=0;o<this.fieldDef.length;o++)r[o]=n[o];n=r}t.set(e,n)}},Db=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Ob={string:Tb,number:cb,boolean:mb,binary:pb,array:fb,tuple:Pb,buffer:wb,enum:kb},hs=4294967295,ps=0,Mh=0,Rb=(Nn=class{constructor(e,n=!1){x(this,"componentId",-1);x(this,"isSingleton");x(this,"initialized",!1);x(this,"eventBuffer",null);x(this,"entityBuffer",null);x(this,"schema");x(this,"fieldNames");x(this,"fields",{});x(this,"_buffer",null);x(this,"readonlyPool",[]);x(this,"writablePool",[]);x(this,"readPoolIndex",0);x(this,"writePoolIndex",0);this.isSingleton=n,this.schema={},this.fieldNames=[];for(const[r,o]of Object.entries(e)){const s=o,i=s.def||o;s[Zt]&&i.schemaDefault===void 0&&(i.schemaDefault=s[Zt]()),this.schema[r]=i,this.fieldNames.push(r)}}static fromDef(e){return new Nn(e.schema,e.isSingleton)}static fromTransfer(e,n,r,o){const s=new Nn(n.schema,n.isSingleton);return s.initialize(n.componentId,e,r,o,n.buffer),s}initialize(e,n,r,o,s){this.ensureNotInitialized(),this.initialized=!0,this.componentId=e,this.eventBuffer=r,this.entityBuffer=o;const i=this.isSingleton?1:n;for(const[a,l]of Object.entries(this.schema))this.fields[a]=this.createFieldInstance(l);if(s)this._buffer=s;else{const a={};for(const l of this.fieldNames){const c=this.fields[l],{view:u}=c.initializeStorage(i,Db);a[l]=u}this._buffer=a,this.isSingleton&&this.initializeSingletonDefaults()}this.initializeMasters()}ensureNotInitialized(){if(this.initialized)throw new Error("Component has already been initialized. Each component instance can only be registered with one World. If you need multiple worlds, define separate component instances for each.")}createFieldInstance(e){if(e.type==="ref")return new Sb(e,this.entityBuffer);const n=Ob[e.type];if(!n)throw new Error(`Unknown field type: ${e.type}`);return new n(e)}get buffer(){return this._buffer}initializeSingletonDefaults(){if(this._buffer===null)throw new Error("Component buffers not initialized");for(let e=0;e<this.fieldNames.length;e++){const n=this.fieldNames[e],r=this._buffer[n],o=this.fields[n],s=o.getDefaultValue();o.setValue(r,ps,s)}}initializeMasters(){if(this._buffer===null)throw new Error("Component buffers not initialized");for(let e=0;e<Nn.POOL_SIZE;e++){const n={view:{},entityId:0};for(const r of this.fieldNames)this.fields[r].defineReadonly(n.view,r,this._buffer,()=>n.entityId);this.readonlyPool.push(n)}for(let e=0;e<Nn.POOL_SIZE;e++){const n={view:{},entityId:0};for(const r of this.fieldNames)this.fields[r].defineWritable(n.view,r,this._buffer,()=>n.entityId);this.writablePool.push(n)}}copy(e,n){var o;for(let s=0;s<this.fieldNames.length;s++){const i=this.fieldNames[s],a=this.buffer[i],l=this.fields[i],u=n&&i in n?n[i]:l.getDefaultValue();l.setValue(a,e,u)}const r=this.isSingleton?hs:e;(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId)}patch(e,n){var o;for(const s in n){const i=this.fields[s];if(!i)continue;const a=this.buffer[s];i.setValue(a,e,n[s])}const r=this.isSingleton?hs:e;(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId)}read(e){const n=this.readonlyPool[this.readPoolIndex];return this.readPoolIndex=(this.readPoolIndex+1)%Nn.POOL_SIZE,n.entityId=e,n.view}write(e){var o;const n=this.writablePool[this.writePoolIndex];this.writePoolIndex=(this.writePoolIndex+1)%Nn.POOL_SIZE,n.entityId=e;const r=this.isSingleton?hs:e;return(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId),n.view}snapshot(e){const n=this.read(e),r={};for(let o=0;o<this.fieldNames.length;o++){const s=this.fieldNames[o];let i=n[s];ArrayBuffer.isView(i)&&(i=Array.from(i)),r[s]=i}return r}},x(Nn,"POOL_SIZE",8),Nn),zc=class{constructor(t,e=!1){x(this,"_defId");x(this,"schema");x(this,"isSingleton");this._defId=Mh++,this.schema=t,this.isSingleton=e}_getInstance(t){const e=t.components[this._defId];if(!e)throw new Error(`Component "${this.constructor.name}" is not registered with this World.`);return e}_getComponentId(t){return this._getInstance(t).componentId}read(t,e){return this._getInstance(t).read(e)}write(t,e){return this._getInstance(t).write(e)}copy(t,e,n){this._getInstance(t).copy(e,n)}patch(t,e,n){this._getInstance(t).patch(e,n)}snapshot(t,e){return this._getInstance(t).snapshot(e)}default(){const t={};for(const[e,n]of Object.entries(this.schema))t[e]=n[Zt]();return t}};function $c(t){return new zc(t,!1)}var Ah=class{constructor(t){x(this,"_defId");x(this,"schema");x(this,"isSingleton",!0);this._defId=Mh++,this.schema=t}_getInstance(t){const e=t.components[this._defId];if(!e)throw new Error(`Singleton "${this.constructor.name}" is not registered with this World.`);if(!e.isSingleton)throw new Error(`Component "${this.constructor.name}" is not a singleton. Use defineSingleton() to create singletons.`);return e}_getComponentId(t){return this._getInstance(t).componentId}read(t){return this._getInstance(t).read(ps)}write(t){return this._getInstance(t).write(ps)}copy(t,e){this._getInstance(t).copy(ps,e)}patch(t,e){this._getInstance(t).patch(ps,e)}snapshot(t){return this._getInstance(t).snapshot(ps)}default(){const t={};for(const[e,n]of Object.entries(this.schema))t[e]=n[Zt]();return t}},zb=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Ie={ADDED:1,REMOVED:2,CHANGED:4,COMPONENT_ADDED:8,COMPONENT_REMOVED:16},$b=8,Lc=4,Vc=0,Lb=class Ov{constructor(e){x(this,"buffer");x(this,"headerView");x(this,"dataView");x(this,"maxEvents");x(this,"reusableSet",new Set);this.maxEvents=e;const n=Lc+e*$b;this.buffer=new zb(n),this.headerView=new Uint32Array(this.buffer,0,1),this.dataView=new Uint32Array(this.buffer,Lc),Atomics.store(this.headerView,Vc,0)}static fromTransfer(e,n){const r=Object.create(Ov.prototype);return r.buffer=e,r.headerView=new Uint32Array(e,0,1),r.dataView=new Uint32Array(e,Lc),r.maxEvents=n,r.reusableSet=new Set,r}getBuffer(){return this.buffer}getDataView(){return this.dataView}push(e,n,r=0){const s=Atomics.add(this.headerView,Vc,1)%this.maxEvents*2,i=n|r<<16;Atomics.store(this.dataView,s,e),Atomics.store(this.dataView,s+1,i)}pushAdded(e){this.push(e,Ie.ADDED,0)}pushRemoved(e){this.push(e,Ie.REMOVED,0)}pushChanged(e,n){this.push(e,Ie.CHANGED,n)}pushComponentAdded(e,n){this.push(e,Ie.COMPONENT_ADDED,n)}pushComponentRemoved(e,n){this.push(e,Ie.COMPONENT_REMOVED,n)}readEvent(e){const n=e*2,r=Atomics.load(this.dataView,n),o=Atomics.load(this.dataView,n+1);return{entityId:r,eventType:o&255,componentId:o>>16&65535}}getWriteIndex(){return Atomics.load(this.headerView,Vc)}collectEntitiesInRange(e,n,r,o){const s=o??this.getWriteIndex();s-e>this.maxEvents&&(e=s-this.maxEvents,console.warn("EventBuffer: Missed events due to buffer overflow, adjusting read index. Increase the maxEvents size to prevent this from happening."));const i=this.reusableSet;i.clear();const a=e%this.maxEvents,l=s%this.maxEvents;if(a===l)return{entities:i,newIndex:s};let c;l>=a?c=l-a:c=this.maxEvents-a+l,c>this.maxEvents&&(c=this.maxEvents);const u=this.dataView,f=this.maxEvents;for(let h=0;h<c;h++){const m=(a+h)%f*2,g=Atomics.load(u,m+1),y=g&255;if(!(y&n))continue;if(r!==void 0&&y===Ie.CHANGED){const k=g>>16&65535,b=k>>3,S=k&7;if(b>=r.length||!(r[b]&1<<S))continue}const w=Atomics.load(u,m);i.add(w)}return{entities:i,newIndex:s}}readEvents(e){const n=this.getWriteIndex(),r=[];n-e>this.maxEvents&&(e=n-this.maxEvents);const o=e%this.maxEvents,s=n%this.maxEvents;if(o===s)return{events:r,newIndex:n};let i;s>=o?i=s-o:i=this.maxEvents-o+s,i>this.maxEvents&&(i=this.maxEvents);const a=this.dataView,l=this.maxEvents;for(let c=0;c<i;c++){const f=(o+c)%l*2,h=Atomics.load(a,f+1),p=h&255,m=h>>16&65535,g=Atomics.load(a,f);r.push({entityId:g,eventType:p,componentId:m})}return{events:r,newIndex:n}}},Vb=class{constructor(t,e,n,r,o,s,i,a){x(this,"tracking");x(this,"with");x(this,"without");x(this,"any");x(this,"hasTracking");x(this,"hasWith");x(this,"hasWithout");x(this,"hasAny");this.tracking=t,this.with=e,this.without=n,this.any=r,this.hasTracking=o,this.hasWith=s,this.hasWithout=i,this.hasAny=a}usesSingleton(t){const{components:e}=t;if(!this.hasTracking)return!1;for(let n=0;n<this.tracking.length;n++){const r=this.tracking[n];if(r!==0){for(let o=0;o<8;o++)if(r&1<<o){const s=n*8+o,i=Object.values(e).find(a=>a.componentId===s);if(i&&!i.isSingleton)return!1}}}return!0}},Fc=Symbol("buildQuery");function ha(t){return new Uint8Array(t)}function ai(t,e){const n=Math.floor(e/8),r=e%8;n<t.length&&(t[n]|=1<<r)}var _h=class{constructor(t,e){x(this,"withMask");x(this,"withoutMask");x(this,"anyMask");x(this,"trackingMask");x(this,"ctx");const n=Math.ceil(t/8);this.withMask=ha(n),this.withoutMask=ha(n),this.anyMask=ha(n),this.trackingMask=ha(n),this.ctx=e}_getComponentId(t){const e=this.ctx.components[t._defId];if(!e)throw new Error(`Component "${t.constructor.name}" is not registered with this World.`);return e.componentId}with(...t){for(const e of t)ai(this.withMask,this._getComponentId(e));return this}without(...t){for(const e of t)ai(this.withoutMask,this._getComponentId(e));return this}any(...t){for(const e of t)ai(this.anyMask,this._getComponentId(e));return this}tracking(...t){for(const e of t){const n=this._getComponentId(e);ai(this.withMask,n),ai(this.trackingMask,n)}return this}[Fc](){const t=!this.trackingMask.every(o=>o===0),e=!this.withMask.every(o=>o===0),n=!this.withoutMask.every(o=>o===0),r=!this.anyMask.every(o=>o===0);return new Vb(this.trackingMask,this.withMask,this.withoutMask,this.anyMask,t,e,n,r)}},Ih=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Gn=0,Fr=1,ms=4294967295,Bh=class{constructor(t){x(this,"denseBuffer");x(this,"sparseBuffer");x(this,"dense");x(this,"sparse");x(this,"maxEntities");this.maxEntities=t,this.denseBuffer=new Ih((Fr+t)*4),this.dense=new Uint32Array(this.denseBuffer),this.dense[Gn]=0,this.sparseBuffer=new Ih(t*4),this.sparse=new Uint32Array(this.sparseBuffer),this.sparse.fill(ms)}get count(){return this.dense[Gn]}add(t){const e=this.sparse;if(e[t]!==ms)return;const n=this.dense,r=n[Gn];if(r>=this.maxEntities)throw new Error("QueryCache is full");n[Fr+r]=t,e[t]=r,n[Gn]=r+1}remove(t){const e=this.sparse,n=e[t];if(n===ms)return;const r=this.dense,s=r[Gn]-1;if(n!==s){const i=r[Fr+s];r[Fr+n]=i,e[i]=n}e[t]=ms,r[Gn]=s}has(t){return this.sparse[t]!==ms}clear(){const t=this.dense[Gn];for(let e=0;e<t;e++){const n=this.dense[Fr+e];this.sparse[n]=ms}this.dense[Gn]=0}toArray(){const t=this.dense[Gn],e=new Array(t);for(let n=0;n<t;n++)e[n]=this.dense[Fr+n];return e}getDenseView(){const t=this.dense[Gn];return this.dense.subarray(Fr,Fr+t)}},Fb=class{constructor(t,e){x(this,"cache");x(this,"lastIndex",0);x(this,"masks");this.masks=e,this.cache=new Bh(t.maxEntities)}current(t){const e=t.currEventIndex??t.eventBuffer.getWriteIndex();if(e===this.lastIndex)return this.cache.getDenseView();const n=e-this.lastIndex,r=this.cache.count,o=t.maxEvents;return n>o||r===0||n>=r?this.rebuildFromEntityBuffer(t):this.processEvents(t,e),this.lastIndex=e,this.cache.getDenseView()}rebuildFromEntityBuffer(t){const e=t.entityBuffer,n=t.maxEntities,r=this.masks,o=this.cache;o.clear();for(let s=0;s<n;s++)e.has(s)&&e.matches(s,r)&&o.add(s)}processEvents(t,e){const n=t.maxEvents,r=t.entityBuffer,o=t.eventBuffer.getDataView(),s=this.masks,i=this.cache,l=this.lastIndex%n,c=e%n,u=c>=l?c-l:n-l+c;for(let f=0;f<u;f++){const p=(l+f)%n*2,m=Atomics.load(o,p),y=Atomics.load(o,p+1)&255;if(y===Ie.REMOVED)i.remove(m);else if(y===Ie.ADDED||y===Ie.COMPONENT_ADDED||y===Ie.COMPONENT_REMOVED){const k=r.has(m)&&r.matches(m,s),b=i.has(m);k&&!b?i.add(m):!k&&b&&i.remove(m)}}}},Wb=(as=class{constructor(e){x(this,"builder");x(this,"instances",{});x(this,"id");this.builder=e,this.id=`current_query_${as.queryCounter++}`}getName(e){return`${this.id}_${e.readerId}`}_getInstance(e){const n=this.getName(e);let r=this.instances[n];if(r)return r;const o=new _h(e.componentCount,e),i=this.builder(o)[Fc]();return r=new Fb(e,i),this.instances[n]=r,r}current(e){return this._getInstance(e).current(e)}},x(as,"queryCounter",0),as);function Ub(t){return new Wb(t)}var Nh=new Map;function Hb(t){const e=t._defId;let n=Nh.get(e);return n||(n=Ub(r=>r.with(t)),Nh.set(e,n)),n}function bt(t){const e=t.pool.get();return t.entityBuffer.create(e),t.eventBuffer.pushAdded(e),e}function Jn(t,e,n,r,o=!0){const s=n._getInstance(t),i=Hb(n),a=s.buffer[r],l=[];for(const c of i.current(t))Rc(a[c],t.entityBuffer,o)===e&&l.push(c);return l}function qe(t,e){t.entityBuffer.has(e)&&(t.eventBuffer.pushRemoved(e),t.entityBuffer.markDead(e))}function J(t,e,n,r={},o=!0){if(o&&!t.entityBuffer.has(e))throw new Error(`Entity with ID ${e} does not exist.`);const s=n._getInstance(t);if(t.entityBuffer.hasComponent(e,s.componentId))throw new Error(`Entity ${e} already has component. Use removeComponent() first or update the existing component.`);t.entityBuffer.addComponentToEntity(e,s.componentId),t.eventBuffer.pushComponentAdded(e,s.componentId),s.copy(e,r)}function nn(t,e,n,r=!0){if(r&&!t.entityBuffer.has(e))throw new Error(`Entity with ID ${e} does not exist.`);const o=n._getInstance(t);t.entityBuffer.removeComponentFromEntity(e,o.componentId),t.eventBuffer.pushComponentRemoved(e,o.componentId)}function O(t,e,n,r=!0){if(r&&!t.entityBuffer.has(e))throw new Error(`Entity with ID ${e} does not exist.`);const o=n._getInstance(t);return t.entityBuffer.hasComponent(e,o.componentId)}function Ve(t){return t.resources}function jb(t,e){return t.entityBuffer.has(e)}var Zb=class{constructor(t){x(this,"lastIndex");x(this,"lastPrevEventIndex",-1);x(this,"lastCurrEventIndex",-1);x(this,"prevExecutionIndex",0);x(this,"prevFrameIndex",0);x(this,"toIndex",0);x(this,"added",[]);x(this,"removed",[]);x(this,"changed",[]);this.lastIndex=t}updateCache(t,e,n){const r=t.currEventIndex??t.eventBuffer.getWriteIndex(),o=t.prevEventIndex;o===this.lastPrevEventIndex&&r===this.lastCurrEventIndex||(this.added=[],this.removed=[],this.changed=[],this.lastPrevEventIndex=o,this.lastCurrEventIndex=r,this.prevExecutionIndex=this.lastIndex,this.prevFrameIndex=o,this.toIndex=r,this.lastIndex=r,this.processEventsAndComputeResults(t,e,n))}updateSingletonChanged(t,e){const n=t.currEventIndex??t.eventBuffer.getWriteIndex(),r=t.prevEventIndex;if(r===this.lastPrevEventIndex&&n===this.lastCurrEventIndex)return;this.changed=[],this.lastPrevEventIndex=r,this.lastCurrEventIndex=n,this.prevFrameIndex=r,this.toIndex=n,this.lastIndex=n,t.eventBuffer.collectEntitiesInRange(this.prevFrameIndex,Ie.CHANGED,e.tracking).entities.size>0&&this.changed.push(hs)}rebuildCacheFromEntityBuffer(t,e,n){const r=t.entityBuffer,o=t.maxEntities;e.clear();for(let s=0;s<o;s++)r.has(s)&&r.matches(s,n)&&e.add(s)}processEventsAndComputeResults(t,e,n){const r=t.maxEvents,o=t.entityBuffer,s=t.eventBuffer.getDataView(),i=this.prevExecutionIndex,a=this.toIndex;let l=this.prevFrameIndex;const c=a-i>r;c&&this.rebuildCacheFromEntityBuffer(t,e,n),a-l>r&&(console.warn(`[ECS] Event buffer overflow: ${a-l} events since last frame, but maxEvents is ${r}. Some added/removed/changed events may be missed. Consider increasing maxEvents in World constructor.`),l=a-r);const f=c?l:i,h=f%r,p=a%r;let m=p>=h?p-h:r-h+p;m>r&&(m=r);const g=this.added,y=this.removed,w=this.changed;g.length=0,y.length=0,w.length=0;const k={},b=1,S=2,v=3,E=n.hasTracking,T=n.tracking;for(let _=0;_<m;_++){const z=(h+_)%r*2,j=f+_>=l,M=Atomics.load(s,z),V=Atomics.load(s,z+1),K=V&255,se=e.has(M),Y=k[M];if(K===Ie.REMOVED){if(!c&&se&&e.remove(M),j)if(Y===b){const R=g.indexOf(M);R!==-1&&(g[R]=g[g.length-1],g.length--),k[M]=S}else if(Y===v&&se){const R=w.indexOf(M);R!==-1&&(w[R]=w[w.length-1],w.length--),k[M]=S,y.push(M)}else!Y&&se&&(k[M]=S,y.push(M))}else if(K===Ie.ADDED){const R=o.matches(M,n);!c&&!se&&R&&e.add(M),j&&!Y&&!se&&R&&(k[M]=b,g.push(M))}else if(K===Ie.COMPONENT_ADDED||K===Ie.COMPONENT_REMOVED){const W=o.has(M)&&o.matches(M,n);c||(W&&!se?e.add(M):!W&&se&&e.remove(M)),j&&!Y&&(!se&&W?(k[M]=b,g.push(M)):se&&!W&&(k[M]=S,y.push(M)))}else if(K===Ie.CHANGED&&E&&j&&!Y&&se){const R=V>>16&65535,W=R>>3,Q=R&7;W<T.length&&T[W]&1<<Q&&(k[M]=v,w.push(M))}}}},Wc=[],Kb=class{constructor(t,e){x(this,"masks");x(this,"cache",null);x(this,"reader");x(this,"isSingletonQuery");this.masks=e,this.isSingletonQuery=e.usesSingleton(t),this.isSingletonQuery||(this.cache=new Bh(t.maxEntities)),this.reader=new Zb(0)}current(t,e){if(this.isSingletonQuery)return[hs];this.reader.updateCache(t,this.cache,this.masks);const n=this.cache.getDenseView();return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}added(t,e){if(this.isSingletonQuery)return Wc;this.reader.updateCache(t,this.cache,this.masks);const n=this.reader.added;return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}removed(t,e){if(this.isSingletonQuery)return Wc;this.reader.updateCache(t,this.cache,this.masks);const n=this.reader.removed;return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}changed(t,e){if(this.isSingletonQuery)return this.reader.updateSingletonChanged(t,this.masks),this.reader.changed;this.reader.updateCache(t,this.cache,this.masks);const n=this.reader.changed;return e!=null&&e.partitioned?this.partitionEntities(n,t.threadIndex,t.threadCount):n}addedOrChanged(t,e){return[...this.added(t,e),...this.changed(t,e)]}addedOrRemoved(t,e){return[...this.added(t,e),...this.removed(t,e)]}removedOrChanged(t,e){return[...this.removed(t,e),...this.changed(t,e)]}addedOrChangedOrRemoved(t,e){return[...this.added(t,e),...this.removed(t,e),...this.changed(t,e)]}partitionEntities(t,e,n){if(t.length===0||n<=1)return t;const r=[];for(let o=0;o<t.length;o++)t[o]%n===e&&r.push(t[o]);return r.length>0?r:Wc}},Yb=(ls=class{constructor(e){x(this,"builder");x(this,"instances",{});x(this,"id");this.builder=e,this.id=`query_${ls.queryCounter++}`}getName(e){return`${this.id}_${e.readerId}`}_getInstance(e){const n=this.getName(e);let r=this.instances[n];if(r)return r;const o=this._getMasks(e);return r=new Kb(e,o),this.instances[n]=r,r}_getMasks(e){const n=new _h(e.componentCount,e);return this.builder(n)[Fc]()}current(e,n){return this._getInstance(e).current(e,n)}added(e,n){return this._getInstance(e).added(e,n)}removed(e,n){return this._getInstance(e).removed(e,n)}changed(e,n){return this._getInstance(e).changed(e,n)}addedOrChanged(e,n){return this._getInstance(e).addedOrChanged(e,n)}addedOrRemoved(e,n){return this._getInstance(e).addedOrRemoved(e,n)}removedOrChanged(e,n){return this._getInstance(e).removedOrChanged(e,n)}addedOrChangedOrRemoved(e,n){return this._getInstance(e).addedOrChangedOrRemoved(e,n)}},x(ls,"queryCounter",0),ls);function re(t){return new Yb(t)}var Ph=(cs=class{constructor(){x(this,"id");this.id=cs.systemCounter++}},x(cs,"systemCounter",0),cs),qb=class extends Ph{constructor(e){super();x(this,"type","main");x(this,"execute");this.execute=e}},Xb=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Gb=(Pt=class{constructor(e,n){x(this,"buffer");x(this,"view");x(this,"bytesPerEntity");const r=Math.ceil(n/8);this.bytesPerEntity=1+r;const o=e*this.bytesPerEntity;this.buffer=new Xb(o),this.view=new Uint8Array(this.buffer)}static fromTransfer(e,n){const r=Object.create(Pt.prototype);r.buffer=e,r.view=new Uint8Array(e);const o=Math.ceil(n/8);return r.bytesPerEntity=1+o,r}getBuffer(){return this.buffer}create(e){const n=e*this.bytesPerEntity,r=this.view,o=this.bytesPerEntity,a=((Atomics.load(r,n)&Pt.GENERATION_MASK)>>Pt.GENERATION_SHIFT)+1&127;for(let l=0;l<o;l++)Atomics.store(r,n+l,0);Atomics.store(r,n,Pt.ALIVE_FLAG|a<<Pt.GENERATION_SHIFT)}addComponentToEntity(e,n){const r=1+(n>>3),o=n&7,s=e*this.bytesPerEntity;Atomics.or(this.view,s+r,1<<o)}removeComponentFromEntity(e,n){const r=1+(n>>3),o=n&7,s=e*this.bytesPerEntity;Atomics.and(this.view,s+r,~(1<<o))}hasComponent(e,n){const r=1+(n>>3),o=n&7,s=e*this.bytesPerEntity;return(Atomics.load(this.view,s+r)&1<<o)!==0}matches(e,n){const r=this.bytesPerEntity,o=e*r,s=this.view;if(!(Atomics.load(s,o)&Pt.ALIVE_FLAG))return!1;const i=o+1;if(n.hasWith){const a=n.with,l=a.length;for(let c=0;c<l;c++){const u=a[c];if(u!==0&&(Atomics.load(s,i+c)&u)!==u)return!1}}if(n.hasWithout){const a=n.without,l=a.length;for(let c=0;c<l;c++){const u=a[c];if(u!==0&&Atomics.load(s,i+c)&u)return!1}}if(n.hasAny){const a=n.any,l=a.length;let c=!1;for(let u=0;u<l;u++){const f=a[u];if(f!==0&&Atomics.load(s,i+u)&f){c=!0;break}}if(!c)return!1}return!0}delete(e){const n=e*this.bytesPerEntity,r=this.view,o=this.bytesPerEntity;for(let s=0;s<o;s++)Atomics.store(r,n+s,0)}markDead(e){const n=e*this.bytesPerEntity;Atomics.and(this.view,n,-2)}has(e){const n=e*this.bytesPerEntity;return(Atomics.load(this.view,n)&Pt.ALIVE_FLAG)!==0}getGeneration(e){const n=e*this.bytesPerEntity;return(Atomics.load(this.view,n)&Pt.GENERATION_MASK)>>Pt.GENERATION_SHIFT}*getComponentIds(e){const n=e*this.bytesPerEntity,r=this.view,o=this.bytesPerEntity-1;for(let s=0;s<o;s++){const i=Atomics.load(r,n+1+s);if(i!==0)for(let a=0;a<8;a++)i&1<<a&&(yield s*8+a)}}},x(Pt,"ALIVE_FLAG",1),x(Pt,"GENERATION_MASK",254),x(Pt,"GENERATION_SHIFT",1),Pt),Jb=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function Qb(t){return t===0?-1:31-Math.clz32(t&-t)}var eS=(De=class{constructor(e,n,r){x(this,"buffer");x(this,"view");x(this,"bucketCount");x(this,"size");this.buffer=e,this.view=new Int32Array(e),this.bucketCount=n,this.size=r}static create(e){const n=Math.ceil(e/32),r=new Jb((n+1)*4),o=new Int32Array(r);for(let i=De.DATA_OFFSET;i<n+De.DATA_OFFSET;i++)o[i]=-1;const s=e%32;if(s!==0){const i=n-1+De.DATA_OFFSET,a=(1<<s)-1;o[i]=a}return o[De.HINT_INDEX]=0,new De(r,n,e)}static fromTransfer(e,n,r){return new De(e,n,r)}getBuffer(){return this.buffer}getBucketCount(){return this.bucketCount}getSize(){return this.size}free(e){const n=(e>>5)+De.DATA_OFFSET,r=1<<(e&31);Atomics.or(this.view,n,r);const o=Atomics.load(this.view,De.HINT_INDEX),s=n-De.DATA_OFFSET;(o===-1||s<o)&&Atomics.store(this.view,De.HINT_INDEX,s)}get(){for(let e=0;e<this.bucketCount*2;e++){let n=Atomics.load(this.view,De.HINT_INDEX);n===-1&&(n=0);for(let r=0;r<this.bucketCount;r++){const o=(n+r)%this.bucketCount+De.DATA_OFFSET,s=Atomics.load(this.view,o);if(s===0)continue;const i=Qb(s);if(i===-1)continue;const a=1<<i;if(Atomics.compareExchange(this.view,o,s,s&~a)===s)return(s&~a)===0&&this.updateHint(o-De.DATA_OFFSET),(o-De.DATA_OFFSET<<5)+i}}throw Atomics.store(this.view,De.HINT_INDEX,-1),new Error(`Entity pool exhausted: maximum of ${this.size} entities reached`)}updateHint(e){for(let n=0;n<this.bucketCount;n++){const r=(e+n)%this.bucketCount+De.DATA_OFFSET;if(Atomics.load(this.view,r)!==0){Atomics.store(this.view,De.HINT_INDEX,r-De.DATA_OFFSET);return}}Atomics.store(this.view,De.HINT_INDEX,-1)}},x(De,"HINT_INDEX",0),x(De,"DATA_OFFSET",1),De),Dh=3,tS=.75,nS=class{constructor(t){x(this,"systems",new Map);x(this,"lastReclaimIndex",0);x(this,"maxEvents");x(this,"warnedStaleSystems",new Set);this.maxEvents=t}recordExecution(t,e){let n=this.systems.get(t);return n||(n={prev:0,curr:0,history:[]},this.systems.set(t,n)),n.prev=n.curr,n.curr=e,n.history.push(e),n.history.length>Dh&&n.history.shift(),n.prev}getPrevIndex(t){var e;return((e=this.systems.get(t))==null?void 0:e.prev)??0}calculateWatermark(t){if(this.systems.size===0)return null;const r=this.calculateEventsInFlight(t)/this.maxEvents>tS;let o=0;if(r){const a=Math.floor(this.maxEvents*.25);o=this.wrapAwareSubtract(t,a)}let s=null,i=!1;for(const[a,l]of this.systems){if(l.history.length<Dh){if(r)continue;i=!0;continue}if(r){const u=l.history[l.history.length-1];if(this.isOlderThan(u,o)){this.warnedStaleSystems.has(a)||(this.warnedStaleSystems.add(a),console.warn(`[History] Stale system detected (id: ${a}). System queries will miss some events. Consider increasing maxEvents or running the system more frequently.`));continue}}const c=l.history[0];(s===null||this.isOlderThan(c,s))&&(s=c)}return i&&!r?null:s!==null&&this.isNewerThan(s,this.lastReclaimIndex)?s:null}markReclaimed(t){this.lastReclaimIndex=t}getLastReclaimIndex(){return this.lastReclaimIndex}calculateEventsInFlight(t){return t>=this.lastReclaimIndex?t-this.lastReclaimIndex:this.maxEvents-this.lastReclaimIndex+t}wrapAwareSubtract(t,e){const n=t-e;return n<0?this.maxEvents+n:n}isOlderThan(t,e){const n=e-t,r=this.maxEvents/2;return Math.abs(n)<r?t<e:t>e}isNewerThan(t,e){return t===e?!1:!this.isOlderThan(t,e)}clear(){this.systems.clear(),this.lastReclaimIndex=0,this.warnedStaleSystems.clear()}},rS=class{constructor(t){x(this,"maxWorkers");x(this,"workerPool",new Map);x(this,"initializedWorkers",new Set);x(this,"taskQueue",new Map);x(this,"busyWorkers",0);this.maxWorkers=t}async execute(t,e,n){const r=[],o=t.threads;if(o>this.maxWorkers)throw new Error(`Worker system requests ${o} threads, but World was configured with only ${this.maxWorkers} max workers. Increase the 'threads' option in World constructor or reduce the worker system's thread count.`);for(let s=0;s<o;s++)r.push(this.executeTask(e,t.path,s,o,n));await Promise.all(r)}async initializeWorker(t,e,n,r){return new Promise((o,s)=>{const i=setTimeout(()=>{s(new Error(`Worker ${n} initialization timed out`))},5e3),a=u=>{u.data.threadIndex===n&&(clearTimeout(i),e.removeEventListener("message",a),"error"in u.data?s(new Error(u.data.error)):o())};e.addEventListener("message",a);const l={};for(const[u,f]of Object.entries(t.components))l[Number(u)]={componentId:f.componentId,buffer:f.buffer,schema:f.schema,isSingleton:f.isSingleton};const c={type:"init",entitySAB:t.entityBuffer.getBuffer(),eventSAB:t.eventBuffer.getBuffer(),poolSAB:t.pool.getBuffer(),poolBucketCount:t.pool.getBucketCount(),poolSize:t.pool.getSize(),componentTransferMap:l,maxEntities:t.maxEntities,maxEvents:t.maxEvents,componentCount:t.componentCount,threadIndex:n,threadCount:r};e.postMessage(c)})}async executeTask(t,e,n,r,o){const s=await this.getWorker(e);return this.initializedWorkers.has(s)||(await this.initializeWorker(t,s,n,r),this.initializedWorkers.add(s)),new Promise((i,a)=>{const l=setTimeout(()=>{s.terminate(),this.removeWorker(e,s),a(new Error(`Task ${n} timed out`))},5e3);s.onmessage=u=>{clearTimeout(l),"error"in u.data?a(new Error(u.data.error)):i(!0),this.releaseWorker(e,s)},s.onerror=u=>{clearTimeout(l),a(u),this.removeWorker(e,s)};const c={type:"execute",threadIndex:n,currEventIndex:o};s.postMessage(c)})}async getWorker(t){let e=this.workerPool.get(t);return e||(e=[],this.workerPool.set(t,e)),e.length>0?(this.busyWorkers++,e.pop()):this.busyWorkers>=this.maxWorkers?new Promise(n=>{let r=this.taskQueue.get(t);r||(r=[],this.taskQueue.set(t,r)),r.push(n)}):(this.busyWorkers++,this.createWorker(t))}createWorker(t){return new Worker(t,{type:"module"})}releaseWorker(t,e){const n=this.taskQueue.get(t);if(n&&n.length>0){const o=n.shift();if(o){o(e);return}}for(const[o,s]of this.taskQueue.entries())if(o!==t&&s.length>0){const i=this.workerPool.get(t);i&&i.push(e),this.busyWorkers--;let a=this.workerPool.get(o);a||(a=[],this.workerPool.set(o,a));const l=s.shift();if(l)if(a.length>0)this.busyWorkers++,l(a.pop());else{this.busyWorkers++;const c=this.createWorker(o);l(c)}return}this.busyWorkers--;const r=this.workerPool.get(t);r&&r.push(e)}removeWorker(t,e){this.busyWorkers--,this.initializedWorkers.delete(e);const n=this.workerPool.get(t);if(n){const r=n.indexOf(e);r>-1&&n.splice(r,1)}}dispose(){for(const t of this.workerPool.values())for(const e of t)e.terminate();this.workerPool.clear(),this.initializedWorkers.clear(),this.busyWorkers=0,this.taskQueue.clear()}},Oh={high:2,medium:1,low:0},oS=(us=class{constructor(e,n={}){x(this,"componentIndex",0);x(this,"workerManager");x(this,"context");x(this,"worldId");x(this,"subscriberCounter",0);x(this,"subscribers",[]);x(this,"componentIdToDef",new Map);x(this,"nextSyncCallbacks",[]);x(this,"prevSyncEventIndex",0);x(this,"history");const r=n.threads??(typeof navigator<"u"?Math.max(1,navigator.hardwareConcurrency??4):3),o=n.maxEntities??1e4,s=n.maxEvents??131072,i=e.length;this.workerManager=new rS(r);const a=new Lb(s),l=new Gb(o,i),c={};for(const u of e){const f=Rb.fromDef(u);f.initialize(this.componentIndex++,o,a,l),c[u._defId]=f,this.componentIdToDef.set(this.componentIndex-1,u)}this.worldId=us.worldCounter++,this.history=new nS(s),this.context={entityBuffer:l,eventBuffer:a,components:c,maxEntities:o,maxEvents:s,componentCount:i,pool:eS.create(o),threadIndex:0,threadCount:1,readerId:`world_${this.worldId}`,prevEventIndex:0,resources:n.resources}}_getContext(){return this.context}async execute(...e){const n=this.context,r=n.eventBuffer.getWriteIndex(),o=[],s=[];for(const f of e)f instanceof Ph?o.push(f):s.push(f);for(const f of s)f({...n,prevEventIndex:this.prevSyncEventIndex,currEventIndex:r});for(const f of o)this.history.recordExecution(f.id,r);const i=o.filter(f=>f.type==="worker"),a=o.filter(f=>f.type==="main"),c=[...i].sort((f,h)=>Oh[h.priority]-Oh[f.priority]).map(f=>this.workerManager.execute(f,n,r));for(const f of a){const h=`world_${this.worldId}_system_${f.id}`,p=this.history.getPrevIndex(f.id);f.execute({...n,readerId:h,prevEventIndex:p,currEventIndex:r})}await Promise.all(c);const u=this.history.calculateWatermark(r);u!==null&&(this.reclaimRemovedEntityIds(this.history.getLastReclaimIndex(),u),this.history.markReclaimed(u))}reclaimRemovedEntityIds(e,n){if(e===n)return;const r=this.context,{entities:o}=r.eventBuffer.collectEntitiesInRange(e,Ie.REMOVED,void 0,n);for(const s of o)r.entityBuffer.has(s)||(r.pool.free(s),r.entityBuffer.delete(s))}subscribe(e,n){const r=this.context,o=this.subscriberCounter++,s=`world_${this.worldId}_subscriber_${o}`;let i;return e._getInstance({...r,readerId:s}),i={queryDef:e,callback:n,readerId:s,prevEventIndex:r.eventBuffer.getWriteIndex()},this.subscribers.push(i),()=>{const a=this.subscribers.indexOf(i);a!==-1&&this.subscribers.splice(a,1)}}sync(){const e=this.context.eventBuffer.getWriteIndex();if(this.nextSyncCallbacks.length>0){const n=this.nextSyncCallbacks;this.nextSyncCallbacks=[];for(const r of n)r({...this.context,prevEventIndex:this.prevSyncEventIndex,currEventIndex:e});this.prevSyncEventIndex=e}if(this.subscribers.length!==0)for(const n of this.subscribers){const r={...this.context,readerId:n.readerId,prevEventIndex:n.prevEventIndex,currEventIndex:e};n.prevEventIndex=e;const o=n.queryDef,s={added:o.added(r),removed:o.removed(r),changed:o.changed(r)};s.added.length===0&&s.removed.length===0&&s.changed.length===0||n.callback(r,s)}}nextSync(e){return this.nextSyncCallbacks.push(e),()=>{const n=this.nextSyncCallbacks.indexOf(e);n!==-1&&this.nextSyncCallbacks.splice(n,1)}}dispose(){this.workerManager.dispose(),this.subscribers=[],this.nextSyncCallbacks=[],this.componentIdToDef.clear(),this.history.clear()}},x(us,"worldCounter",0),us);function Rh(t){const e=new Set,n=new Map;for(const r of t){if(e.has(r.name))throw new Error(`Duplicate migration name: "${r.name}"`);if(e.add(r.name),r.supersedes!=null){if(!e.has(r.supersedes))throw new Error(`Migration "${r.name}" supersedes "${r.supersedes}", which ${t.some(o=>o.name===r.supersedes)?"must come before it":"does not exist"}`);if(n.has(r.supersedes))throw new Error(`Migration "${r.supersedes}" is already superseded by "${n.get(r.supersedes)}"`);n.set(r.supersedes,r.name)}}}var Kt=class extends zc{constructor(n,r){super(r,!1);x(this,"name");x(this,"sync");x(this,"migrations");x(this,"excludeFromHistory");this.name=n.name,this.sync=n.sync??"none",this.migrations=n.migrations??[],this.excludeFromHistory=n.excludeFromHistory??[],this.migrations.length>0&&Rh(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(n,r){return{...super.snapshot(n,r),_exists:!0,_version:this.currentVersion}}};function Ze(t,e){return new Kt(t,e)}var St=class extends Ah{constructor(n,r){super(r);x(this,"name");x(this,"sync");x(this,"migrations");x(this,"excludeFromHistory");this.name=n.name,this.sync=n.sync??"none",this.migrations=n.migrations??[],this.excludeFromHistory=n.excludeFromHistory??[],this.migrations.length>0&&Rh(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(n){return{...super.snapshot(n),_exists:!0,_version:this.currentVersion}}};function zh(t,e){return new St(t,e)}var de=$c({id:C.string().max(36)}),ve=0,be=1,Se=2,Ee=3,ee;(t=>{t.create=(e,n,r,o)=>[e,n,r,o],t.zero=()=>[0,0,0,0],t.clone=e=>[e[0],e[1],e[2],e[3]],t.fromPoints=e=>{if(e.length===0)return(0,t.zero)();let n=e[0][0],r=e[0][1],o=e[0][0],s=e[0][1];for(let i=1;i<e.length;i++){const[a,l]=e[i];a<n&&(n=a),l<r&&(r=l),a>o&&(o=a),l>s&&(s=l)}return[n,r,o,s]},t.fromPositionSize=(e,n,r,o)=>[e,n,e+r,n+o],t.left=e=>e[ve],t.top=e=>e[be],t.right=e=>e[Se],t.bottom=e=>e[Ee],t.width=e=>e[Se]-e[ve],t.height=e=>e[Ee]-e[be],t.center=e=>[(e[ve]+e[Se])/2,(e[be]+e[Ee])/2],t.size=e=>[(0,t.width)(e),(0,t.height)(e)],t.corners=e=>[[e[ve],e[be]],[e[Se],e[be]],[e[Se],e[Ee]],[e[ve],e[Ee]]],t.containsPoint=(e,n,r=!0)=>r?n[0]>=e[ve]&&n[0]<=e[Se]&&n[1]>=e[be]&&n[1]<=e[Ee]:n[0]>e[ve]&&n[0]<e[Se]&&n[1]>e[be]&&n[1]<e[Ee],t.intersects=(e,n)=>!(e[Se]<n[ve]||e[ve]>n[Se]||e[Ee]<n[be]||e[be]>n[Ee]),t.contains=(e,n)=>e[ve]<=n[ve]&&e[be]<=n[be]&&e[Se]>=n[Se]&&e[Ee]>=n[Ee],t.distanceToPoint=(e,n)=>{const r=Math.max(e[ve]-n[0],0,n[0]-e[Se]),o=Math.max(e[be]-n[1],0,n[1]-e[Ee]);return Math.hypot(r,o)},t.set=(e,n,r,o,s)=>{e[ve]=n,e[be]=r,e[Se]=o,e[Ee]=s},t.copy=(e,n)=>{e[ve]=n[ve],e[be]=n[be],e[Se]=n[Se],e[Ee]=n[Ee]},t.expand=(e,n)=>{e[ve]=Math.min(e[ve],n[0]),e[be]=Math.min(e[be],n[1]),e[Se]=Math.max(e[Se],n[0]),e[Ee]=Math.max(e[Ee],n[1])},t.union=(e,n)=>{e[ve]=Math.min(e[ve],n[ve]),e[be]=Math.min(e[be],n[be]),e[Se]=Math.max(e[Se],n[Se]),e[Ee]=Math.max(e[Ee],n[Ee])},t.intersection=(e,n)=>{e[ve]=Math.max(e[ve],n[ve]),e[be]=Math.max(e[be],n[be]),e[Se]=Math.min(e[Se],n[Se]),e[Ee]=Math.min(e[Ee],n[Ee])},t.pad=(e,n)=>{e[ve]-=n,e[be]-=n,e[Se]+=n,e[Ee]+=n},t.setFromPoints=(e,n)=>{if(n.length===0){e[ve]=0,e[be]=0,e[Se]=0,e[Ee]=0;return}e[ve]=n[0][0],e[be]=n[0][1],e[Se]=n[0][0],e[Ee]=n[0][1];for(let r=1;r<n.length;r++){const[o,s]=n[r];o<e[ve]&&(e[ve]=o),s<e[be]&&(e[be]=s),o>e[Se]&&(e[Se]=o),s>e[Ee]&&(e[Ee]=s)}},t.translate=(e,n)=>{e[ve]+=n[0],e[be]+=n[1],e[Se]+=n[0],e[Ee]+=n[1]},t.scale=(e,n)=>{e[ve]*=n,e[be]*=n,e[Se]*=n,e[Ee]*=n}})(ee||(ee={}));var rn=0,on=1,yr=2,wr=3,sn=4,an=5,Qn=6,Me;(t=>{t.create=(e,n,r,o,s,i,a)=>[e,n,r,o,s,i,a],t.zero=()=>[0,0,0,0,0,0,0],t.clone=e=>[e[0],e[1],e[2],e[3],e[4],e[5],e[6]],t.a=e=>[e[rn],e[on]],t.b=e=>[e[yr],e[wr]],t.c=e=>[e[sn],e[an]],t.thickness=e=>e[Qn],t.isCollinear=e=>{const n=(e[rn]-e[sn])*(e[wr]-e[an])-(e[yr]-e[sn])*(e[on]-e[an]);return Math.abs(n)<1e-8},t.computeCenter=e=>{const n=e[rn],r=e[on],o=e[yr],s=e[wr],i=e[sn],a=e[an],l=(n-i)*(s-a)-(o-i)*(r-a);if(Math.abs(l)<1e-10)return null;const c=2*(n*(s-a)+o*(a-r)+i*(r-s));if(Math.abs(c)<1e-10)return null;const u=((n*n+r*r)*(s-a)+(o*o+s*s)*(a-r)+(i*i+a*a)*(r-s))/c,f=((n*n+r*r)*(i-o)+(o*o+s*s)*(n-i)+(i*i+a*a)*(o-n))/c;return[u,f]},t.compute=e=>{const n=(0,t.computeCenter)(e);if(!n)return null;const r=e[rn],o=e[on],s=e[yr],i=e[wr],a=e[sn],l=e[an],c=Math.hypot(s-n[0],i-n[1]),u=(s-r)*(l-o)-(i-o)*(a-r)<0,f=sS(e,n);let h=Math.atan2(o-n[1],r-n[0]);h=Co(h);let p=h+f*(u?-1:1);return p=Co(p),{center:n,radius:c,clockwise:u,arcAngle:f,startAngle:h,endAngle:p}},t.inArcAngle=(e,n,r,o)=>(e=Co(e),o?n<r?e>=r||e<=n:e>=r&&e<=n:n>r?e>=n||e<=r:e>=n&&e<=r),t.containsPoint=(e,n)=>{const r=(0,t.compute)(e);if(!r)return!1;const{center:o,radius:s,startAngle:i,endAngle:a,clockwise:l}=r,c=e[Qn]/2,u=n[0]-o[0],f=n[1]-o[1],h=Math.hypot(u,f);if(Math.abs(h-s)>c)return!1;const m=Math.atan2(f,u);return(0,t.inArcAngle)(m,i,a,l)},t.intersectsAabb=(e,n)=>{const r=(0,t.compute)(e);if(!r)return!1;const{center:o,radius:s,startAngle:i,endAngle:a,clockwise:l}=r,c=e[Qn]/2,u=(0,t.a)(e),f=(0,t.b)(e),h=(0,t.c)(e);if(Uc(n,u)||Uc(n,f)||Uc(n,h))return!0;const p=s-c,m=s+c;if(!iS(o,m,n))return!1;const g=[[n[0],n[1]],[n[2],n[1]],[n[2],n[3]],[n[0],n[3]]];for(const y of[m,p])for(let w=0;w<g.length;w++){const k=g[w],b=g[(w+1)%g.length],S=Lh(k,b,o,y);for(const v of S){const E=Math.atan2(v[1]-o[1],v[0]-o[0]);if((0,t.inArcAngle)(E,i,a,l))return!0}}return!1},t.intersectsCapsule=(e,n,r,o)=>{const s=(0,t.compute)(e);if(!s)return!1;const{center:i,radius:a,startAngle:l,endAngle:c,clockwise:u}=s,f=e[Qn]/2,h=a-f,p=a+f;for(const m of[p,h]){const g=$h(i,m,n),y=$h(i,m,r);if(g!==y){const w=Math.atan2(n[1]-i[1],n[0]-i[0]);if((0,t.inArcAngle)(w,l,c,u))return!0}}return!1},t.intersectSegment=(e,n,r)=>{const o=(0,t.compute)(e);if(!o)return[];const{center:s,radius:i,startAngle:a,endAngle:l,clockwise:c}=o;return Lh(n,r,s,i).filter(f=>{const h=Math.atan2(f[1]-s[1],f[0]-s[0]);return(0,t.inArcAngle)(h,a,l,c)})},t.intersectRect=(e,n)=>{const r=[];for(let o=0;o<n.length;o++){const s=n[o],i=n[(o+1)%n.length],a=(0,t.intersectSegment)(e,s,i);r.push(...a)}return r},t.pointToParametric=(e,n)=>{const r=(0,t.compute)(e);if(!r)return null;const{center:o,startAngle:s,arcAngle:i,clockwise:a}=r;let l=Math.atan2(n[1]-o[1],n[0]-o[0]);if(l=Co(l),!(0,t.inArcAngle)(l,r.startAngle,r.endAngle,a))return null;let c=(l-s)*(a?-1:1);return c<0&&(c+=2*Math.PI),c/i},t.parametricToPoint=(e,n)=>{const r=(0,t.compute)(e);if(!r)return[e[rn]+n*(e[sn]-e[rn]),e[on]+n*(e[an]-e[on])];const{center:o,radius:s,startAngle:i,arcAngle:a,clockwise:l}=r,c=i+n*a*(l?-1:1);return[o[0]+Math.cos(c)*s,o[1]+Math.sin(c)*s]},t.length=e=>{const n=(0,t.compute)(e);return n?n.arcAngle*n.radius:Math.hypot(e[sn]-e[rn],e[an]-e[on])},t.directionAt=(e,n)=>{const r=(0,t.compute)(e);if(!r){const c=e[sn]-e[rn],u=e[an]-e[on],f=Math.hypot(c,u);return f>0?[c/f,u/f]:[0,0]}const o=(0,t.parametricToPoint)(e,n),{center:s,clockwise:i}=r,a=[o[0]-s[0],o[1]-s[1]],l=Math.hypot(a[0],a[1]);return l===0?[0,0]:i?[a[1]/l,-a[0]/l]:[-a[1]/l,a[0]/l]},t.extremaPoints=(e,n=0)=>{const r=(0,t.compute)(e),o=[(0,t.a)(e),(0,t.c)(e)];if(!r)return o;const{center:s,radius:i,startAngle:a,endAngle:l,clockwise:c}=r;for(let u=0;u<4;u++){const f=u*Math.PI/2+n;(0,t.inArcAngle)(f,a,l,c)&&o.push([s[0]+Math.cos(f)*i,s[1]+Math.sin(f)*i])}return o},t.getExtrema=e=>{const n=(0,t.extremaPoints)(e),r=e[Qn]/2,o=[];for(const s of n)o.push([s[0]-r,s[1]-r]),o.push([s[0]-r,s[1]+r]),o.push([s[0]+r,s[1]-r]),o.push([s[0]+r,s[1]+r]);return o},t.set=(e,n,r,o,s,i,a,l)=>{e[rn]=n,e[on]=r,e[yr]=o,e[wr]=s,e[sn]=i,e[an]=a,e[Qn]=l},t.copy=(e,n)=>{e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6]},t.setA=(e,n,r)=>{e[rn]=n,e[on]=r},t.setB=(e,n,r)=>{e[yr]=n,e[wr]=r},t.setC=(e,n,r)=>{e[sn]=n,e[an]=r},t.setThickness=(e,n)=>{e[Qn]=n},t.setFromPoints=(e,n,r,o,s)=>{e[rn]=n[0],e[on]=n[1],e[yr]=r[0],e[wr]=r[1],e[sn]=o[0],e[an]=o[1],e[Qn]=s},t.trim=(e,n,r)=>{const o=(0,t.parametricToPoint)(e,n),s=(0,t.parametricToPoint)(e,(n+r)/2),i=(0,t.parametricToPoint)(e,r),a=e[Qn];e[rn]=o[0],e[on]=o[1],e[yr]=s[0],e[wr]=s[1],e[sn]=i[0],e[an]=i[1],e[Qn]=a}})(Me||(Me={}));function Co(t){for(;t<0;)t+=2*Math.PI;for(;t>=2*Math.PI;)t-=2*Math.PI;return t}function sS(t,e){const n=t[rn],r=t[on],o=t[yr],s=t[wr],i=t[sn],a=t[an],l=Co(Math.atan2(r-e[1],n-e[0])),c=Co(Math.atan2(s-e[1],o-e[0])),u=Co(Math.atan2(a-e[1],i-e[0]));let f=Math.abs(u-l);f>Math.PI&&(f=2*Math.PI-f);const h=Math.min(l,u),p=Math.max(l,u);let m;return p-h>Math.PI?m=c>=p||c<=h:m=c>=h&&c<=p,m?f:2*Math.PI-f}function Uc(t,e){return e[0]>=t[0]&&e[0]<=t[2]&&e[1]>=t[1]&&e[1]<=t[3]}function $h(t,e,n){const r=n[0]-t[0],o=n[1]-t[1];return r*r+o*o<=e*e}function iS(t,e,n){const r=Math.max(n[0],Math.min(t[0],n[2])),o=Math.max(n[1],Math.min(t[1],n[3])),s=t[0]-r,i=t[1]-o;return s*s+i*i<=e*e}function Lh(t,e,n,r){const o=[e[0]-t[0],e[1]-t[1]],s=[t[0]-n[0],t[1]-n[1]],i=o[0]*o[0]+o[1]*o[1],a=2*(s[0]*o[0]+s[1]*o[1]),l=s[0]*s[0]+s[1]*s[1]-r*r;if(i===0){const m=s[0]*s[0]+s[1]*s[1];return Math.abs(m-r*r)<=1e-12?[[t[0],t[1]]]:[]}let c=a*a-4*i*l;const u=1e-12;if(c<-u)return[];c=Math.sqrt(Math.max(0,c));const f=(-a-c)/(2*i),h=(-a+c)/(2*i),p=[];return f>=0&&f<=1&&p.push([t[0]+f*o[0],t[1]+f*o[1]]),h>=0&&h<=1&&Math.abs(h-f)>u&&p.push([t[0]+h*o[0],t[1]+h*o[1]]),p}var L;(t=>{t.create=(e,n)=>[e,n],t.zero=()=>[0,0],t.clone=e=>[e[0],e[1]],t.dot=(e,n)=>e[0]*n[0]+e[1]*n[1],t.lengthSq=e=>e[0]*e[0]+e[1]*e[1],t.length=e=>Math.hypot(e[0],e[1]),t.distance=(e,n)=>{const r=n[0]-e[0],o=n[1]-e[1];return Math.hypot(r,o)},t.distanceSq=(e,n)=>{const r=n[0]-e[0],o=n[1]-e[1];return r*r+o*o},t.midPoint=(e,n)=>[(e[0]+n[0])/2,(e[1]+n[1])/2],t.angleTo=(e,n)=>Math.atan2(n[1]-e[1],n[0]-e[0]),t.angle=e=>Math.atan2(e[1],e[0]),t.fromPolar=(e,n,r=[0,0])=>[r[0]+Math.cos(n)*e,r[1]+Math.sin(n)*e],t.set=(e,n,r)=>{e[0]=n,e[1]=r},t.copy=(e,n)=>{e[0]=n[0],e[1]=n[1]},t.add=(e,n)=>{e[0]+=n[0],e[1]+=n[1]},t.addScalar=(e,n)=>{e[0]+=n,e[1]+=n},t.sub=(e,n)=>{e[0]-=n[0],e[1]-=n[1]},t.scale=(e,n)=>{e[0]*=n,e[1]*=n},t.multiply=(e,n)=>{e[0]*=n[0],e[1]*=n[1]},t.divide=(e,n)=>{(n[0]===0||n[1]===0)&&console.warn("Vec2.divide: division by zero, using 1 as divisor"),e[0]/=n[0]||1,e[1]/=n[1]||1},t.negate=e=>{e[0]=-e[0],e[1]=-e[1]},t.normalize=e=>{const n=(0,t.length)(e);n>0&&(e[0]/=n,e[1]/=n)},t.rotate=(e,n)=>{const r=Math.cos(n),o=Math.sin(n),s=e[0]*r-e[1]*o,i=e[0]*o+e[1]*r;e[0]=s,e[1]=i},t.rotateAround=(e,n,r)=>{(0,t.sub)(e,n),(0,t.rotate)(e,r),(0,t.add)(e,n)}})(L||(L={}));var Xe=0,Ge=1,Et=2,Ct=3,er=4,ot;(t=>{t.create=(e,n,r,o,s)=>[e,n,r,o,s],t.fromPoints=(e,n,r)=>[e[0],e[1],n[0],n[1],r],t.clone=e=>[e[0],e[1],e[2],e[3],e[4]],t.pointA=e=>[e[Xe],e[Ge]],t.pointB=e=>[e[Et],e[Ct]],t.radius=e=>e[er],t.center=e=>[(e[Xe]+e[Et])/2,(e[Ge]+e[Ct])/2],t.length=e=>{const n=e[Et]-e[Xe],r=e[Ct]-e[Ge];return Math.hypot(n,r)},t.bounds=e=>{const n=e[er];return[Math.min(e[Xe],e[Et])-n,Math.min(e[Ge],e[Ct])-n,Math.max(e[Xe],e[Et])+n,Math.max(e[Ge],e[Ct])+n]},t.getExtrema=e=>{const n=e[Xe],r=e[Ge],o=e[Et],s=e[Ct],i=e[er];return[[n-i,r-i],[n-i,r+i],[n+i,r-i],[n+i,r+i],[o-i,s-i],[o-i,s+i],[o+i,s-i],[o+i,s+i]]},t.closestPointOnSegmentParam=(e,n,r,o,s,i)=>{const a=r-e,l=o-n,c=a*a+l*l;if(c===0)return 0;const u=((s-e)*a+(i-n)*l)/c;return Math.max(0,Math.min(1,u))},t.closestPointOnCenterLine=(e,n)=>{const r=(0,t.closestPointOnSegmentParam)(e[Xe],e[Ge],e[Et],e[Ct],n[0],n[1]);return[e[Xe]+r*(e[Et]-e[Xe]),e[Ge]+r*(e[Ct]-e[Ge])]},t.distanceToPoint=(e,n)=>{const r=(0,t.closestPointOnCenterLine)(e,n);return L.distance(r,n)},t.containsPoint=(e,n)=>(0,t.distanceToPoint)(e,n)<=e[er],t.intersectsAabb=(e,n)=>{const r=e[er],o=(0,t.bounds)(e);if(!ee.intersects(o,n))return!1;const s=e[Et]-e[Xe],i=e[Ct]-e[Ge],a=s*s+i*i;if(a===0)return ee.distanceToPoint(n,[e[Xe],e[Ge]])<=r;n[0],n[1],n[2],n[3];const l=Math.max(1,Math.ceil(Math.sqrt(a)/r));for(let c=0;c<=l;c++){const u=c/l,f=e[Xe]+u*s,h=e[Ge]+u*i;if(ee.distanceToPoint(n,[f,h])<=r)return!0}return!1},t.intersectsCapsule=(e,n)=>(0,t.segmentToSegmentDistance)(e[Xe],e[Ge],e[Et],e[Ct],n[Xe],n[Ge],n[Et],n[Ct])<=e[er]+n[er],t.segmentToSegmentDistance=(e,n,r,o,s,i,a,l)=>{const c=r-e,u=o-n,f=a-s,h=l-i,p=e-s,m=n-i,g=c*c+u*u,y=c*f+u*h,w=f*f+h*h,k=c*p+u*m,b=f*p+h*m,S=g*w-y*y;let v,E;S<1e-10?(v=0,E=b/w):(v=(y*b-w*k)/S,E=(g*b-y*k)/S),v=Math.max(0,Math.min(1,v)),E=Math.max(0,Math.min(1,E)),(v<0||v>1)&&(E=(y*v+b)/w,E=Math.max(0,Math.min(1,E)),v=(y*E-k)/g,v=Math.max(0,Math.min(1,v)));const T=e+v*c,_=n+v*u,I=s+E*f,z=i+E*h;return Math.hypot(I-T,z-_)},t.set=(e,n,r,o,s,i)=>{e[Xe]=n,e[Ge]=r,e[Et]=o,e[Ct]=s,e[er]=i},t.copy=(e,n)=>{e[Xe]=n[Xe],e[Ge]=n[Ge],e[Et]=n[Et],e[Ct]=n[Ct],e[er]=n[er]},t.translate=(e,n)=>{e[Xe]+=n[0],e[Ge]+=n[1],e[Et]+=n[0],e[Ct]+=n[1]},t.trim=(e,n,r)=>{const o=e[Xe],s=e[Ge],i=e[Et],a=e[Ct],l=i-o,c=a-s;e[Xe]=o+n*l,e[Ge]=s+n*c,e[Et]=o+r*l,e[Ct]=s+r*c}})(ot||(ot={}));var Ae;(t=>{t.create=(a,l,c,u,f,h)=>[a,l,c,u,f,h],t.identity=()=>[1,0,0,1,0,0],t.clone=a=>[a[0],a[1],a[2],a[3],a[4],a[5]],t.fromTranslation=(a,l)=>[1,0,0,1,a,l],t.fromScale=(a,l)=>[a,0,0,l??a,0,0],t.fromRotation=a=>{const l=Math.cos(a),c=Math.sin(a);return[l,c,-c,l,0,0]},t.fromSkew=(a,l)=>[1,Math.tan(l),Math.tan(a),1,0,0],t.getTranslation=a=>[a[4],a[5]],t.getScale=a=>{const l=Math.sqrt(a[0]*a[0]+a[1]*a[1]),c=Math.sqrt(a[2]*a[2]+a[3]*a[3]);return[l,c]},t.getRotation=a=>Math.atan2(a[1],a[0]),t.determinant=a=>a[0]*a[3]-a[1]*a[2],t.set=(a,l,c,u,f,h,p)=>{a[0]=l,a[1]=c,a[2]=u,a[3]=f,a[4]=h,a[5]=p},t.copy=(a,l)=>{a[0]=l[0],a[1]=l[1],a[2]=l[2],a[3]=l[3],a[4]=l[4],a[5]=l[5]},t.setIdentity=a=>{a[0]=1,a[1]=0,a[2]=0,a[3]=1,a[4]=0,a[5]=0},t.multiply=(a,l)=>{const c=a[0]*l[0]+a[2]*l[1],u=a[1]*l[0]+a[3]*l[1],f=a[0]*l[2]+a[2]*l[3],h=a[1]*l[2]+a[3]*l[3],p=a[0]*l[4]+a[2]*l[5]+a[4],m=a[1]*l[4]+a[3]*l[5]+a[5];a[0]=c,a[1]=u,a[2]=f,a[3]=h,a[4]=p,a[5]=m},t.premultiply=(a,l)=>{const c=l[0]*a[0]+l[2]*a[1],u=l[1]*a[0]+l[3]*a[1],f=l[0]*a[2]+l[2]*a[3],h=l[1]*a[2]+l[3]*a[3],p=l[0]*a[4]+l[2]*a[5]+l[4],m=l[1]*a[4]+l[3]*a[5]+l[5];a[0]=c,a[1]=u,a[2]=f,a[3]=h,a[4]=p,a[5]=m},t.invert=a=>{const l=(0,t.determinant)(a);if(l===0)return!1;const c=1/l,u=a[3]*c,f=-a[1]*c,h=-a[2]*c,p=a[0]*c,m=(a[2]*a[5]-a[3]*a[4])*c,g=(a[1]*a[4]-a[0]*a[5])*c;return a[0]=u,a[1]=f,a[2]=h,a[3]=p,a[4]=m,a[5]=g,!0},t.translate=(a,l,c)=>{a[4]+=a[0]*l+a[2]*c,a[5]+=a[1]*l+a[3]*c},t.scale=(a,l,c)=>{const u=c??l;a[0]*=l,a[1]*=l,a[2]*=u,a[3]*=u},t.rotate=(a,l)=>{const c=Math.cos(l),u=Math.sin(l),f=a[0]*c+a[2]*u,h=a[1]*c+a[3]*u,p=a[0]*-u+a[2]*c,m=a[1]*-u+a[3]*c;a[0]=f,a[1]=h,a[2]=p,a[3]=m},t.skew=(a,l,c)=>{const u=Math.tan(l),f=Math.tan(c),h=a[0]+a[2]*f,p=a[1]+a[3]*f,m=a[0]*u+a[2],g=a[1]*u+a[3];a[0]=h,a[1]=p,a[2]=m,a[3]=g},t.transformPoint=(a,l)=>{const c=a[0]*l[0]+a[2]*l[1]+a[4],u=a[1]*l[0]+a[3]*l[1]+a[5];l[0]=c,l[1]=u},t.transformVector=(a,l)=>{const c=a[0]*l[0]+a[2]*l[1],u=a[1]*l[0]+a[3]*l[1];l[0]=c,l[1]=u},t.inverseTransformPoint=(a,l)=>{const c=(0,t.determinant)(a);if(c===0)return!1;const u=1/c,f=l[0]-a[4],h=l[1]-a[5];return l[0]=(a[3]*f-a[2]*h)*u,l[1]=(a[0]*h-a[1]*f)*u,!0},t.equals=(a,l,c=1e-6)=>Math.abs(a[0]-l[0])<c&&Math.abs(a[1]-l[1])<c&&Math.abs(a[2]-l[2])<c&&Math.abs(a[3]-l[3])<c&&Math.abs(a[4]-l[4])<c&&Math.abs(a[5]-l[5])<c,t.isIdentity=(a,l=1e-6)=>Math.abs(a[0]-1)<l&&Math.abs(a[1])<l&&Math.abs(a[2])<l&&Math.abs(a[3]-1)<l&&Math.abs(a[4])<l&&Math.abs(a[5])<l,t.toCssMatrix=a=>`matrix(${a[0]}, ${a[1]}, ${a[2]}, ${a[3]}, ${a[4]}, ${a[5]})`,t.fromCssMatrix=a=>{const l=a.match(/matrix\(\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^,]+),\s*([^)]+)\s*\)/);if(!l)return null;const c=l.slice(1).map(Number);return c.some(Number.isNaN)?null:c}})(Ae||(Ae={}));var q=0,X=1,st;(t=>{t.getCenter=(e,n,r)=>{r[q]=e[q]+n[q]/2,r[X]=e[X]+n[X]/2},t.getCorners=(e,n,r,o)=>{const s=n[q]/2,i=n[X]/2,a=e[q]+s,l=e[X]+i,c=Math.cos(r),u=Math.sin(r);o[0][q]=a+-s*c- -i*u,o[0][X]=l+-s*u+-i*c,o[1][q]=a+s*c- -i*u,o[1][X]=l+s*u+-i*c,o[2][q]=a+s*c-i*u,o[2][X]=l+s*u+i*c,o[3][q]=a+-s*c-i*u,o[3][X]=l+-s*u+i*c},t.getAabb=(e,n,r,o)=>{const s=n[q]/2,i=n[X]/2,a=e[q]+s,l=e[X]+i,c=Math.cos(r),u=Math.sin(r),f=a+-s*c- -i*u,h=l+-s*u+-i*c,p=a+s*c- -i*u,m=l+s*u+-i*c,g=a+s*c-i*u,y=l+s*u+i*c,w=a+-s*c-i*u,k=l+-s*u+i*c;o[0]=Math.min(f,p,g,w),o[1]=Math.min(h,m,y,k),o[2]=Math.max(f,p,g,w),o[3]=Math.max(h,m,y,k)},t.uvToWorld=(e,n,r,o)=>{const s=[(o[q]-.5)*n[q],(o[X]-.5)*n[X]];L.rotate(s,r);const i=[0,0];return(0,t.getCenter)(e,n,i),L.add(s,i),s},t.worldToUv=(e,n,r,o)=>{const s=[0,0];(0,t.getCenter)(e,n,s);const i=L.clone(o);return L.sub(i,s),L.rotate(i,-r),L.divide(i,n),L.addScalar(i,.5),i},t.getUvToWorldMatrix=(e,n,r,o)=>{const s=Math.cos(r),i=Math.sin(r),a=n[q],l=n[X],c=e[q]+a/2,u=e[X]+l/2;o[0]=a*s,o[1]=a*i,o[2]=-l*i,o[3]=l*s,o[4]=c-.5*(a*s-l*i),o[5]=u-.5*(a*i+l*s)},t.containsPoint=(e,n,r,o)=>{const s=n[q]/2,i=n[X]/2,a=e[q]+s,l=e[X]+i,c=o[q]-a,u=o[X]-l,f=Math.cos(-r),h=Math.sin(-r),p=c*f-u*h,m=c*h+u*f;return p>=-s&&p<=s&&m>=-i&&m<=i},t.intersectsAabb=(e,n,r,o,s,i,a)=>{const l=n[q]/2,c=n[X]/2,u=e[q]+l,f=e[X]+c,h=Math.cos(r),p=Math.sin(r);i[0][q]=o[0],i[0][X]=o[1],i[1][q]=o[2],i[1][X]=o[1],i[2][q]=o[2],i[2][X]=o[3],i[3][q]=o[0],i[3][X]=o[3],s[0][q]=u+-l*h- -c*p,s[0][X]=f+-l*p+-c*h,s[1][q]=u+l*h- -c*p,s[1][X]=f+l*p+-c*h,s[2][q]=u+l*h-c*p,s[2][X]=f+l*p+c*h,s[3][q]=u+-l*h-c*p,s[3][X]=f+-l*p+c*h;const m=s[1][q]-s[0][q],g=s[1][X]-s[0][X],y=Math.sqrt(m*m+g*g);y>0&&(a[0][q]=-g/y,a[0][X]=m/y);const w=s[2][q]-s[1][q],k=s[2][X]-s[1][X],b=Math.sqrt(w*w+k*k);return b>0&&(a[1][q]=-k/b,a[1][X]=w/b),!(pa(i,s,1,0)||pa(i,s,0,1)||pa(i,s,a[0][q],a[0][X])||pa(i,s,a[1][q],a[1][X]))},t.setCenter=(e,n,r)=>{e[q]=r[q]-n[q]/2,e[X]=r[X]-n[X]/2},t.translate=(e,n)=>{e[q]+=n[q],e[X]+=n[X]},t.scaleBy=(e,n,r)=>{const o=e[q]+n[q]/2,s=e[X]+n[X]/2;n[q]*=r,n[X]*=r,e[q]=o-n[q]/2,e[X]=s-n[X]/2},t.scaleAround=(e,n,r,o)=>{const s=e[q]+n[q]/2,i=e[X]+n[X]/2,a=r[q]+(s-r[q])*o,l=r[X]+(i-r[X])*o;n[q]*=o,n[X]*=o,e[q]=a-n[q]/2,e[X]=l-n[X]/2},t.rotateAround=(e,n,r,o,s)=>{const i=e[q]+n[q]/2,a=e[X]+n[X]/2,l=i-o[q],c=a-o[X],u=Math.cos(s),f=Math.sin(s),h=o[q]+l*u-c*f,p=o[X]+l*f+c*u;return e[q]=h-n[q]/2,e[X]=p-n[X]/2,r+s},t.boundPoints=(e,n,r,o)=>{if(o.length===0)return;if(r===0){let b=o[0][q],S=o[0][X],v=b,E=S;for(let T=1;T<o.length;T++){const _=o[T][q],I=o[T][X];_<b&&(b=_),I<S&&(S=I),_>v&&(v=_),I>E&&(E=I)}e[q]=b,e[X]=S,n[q]=v-b,n[X]=E-S;return}const s=Math.cos(-r),i=Math.sin(-r);let a=Number.POSITIVE_INFINITY,l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY;for(const b of o){const S=b[q]*s-b[X]*i,v=b[q]*i+b[X]*s;S<a&&(a=S),v<l&&(l=v),S>c&&(c=S),v>u&&(u=v)}const f=(a+c)/2,h=(l+u)/2,p=c-a,m=u-l,g=Math.cos(r),y=Math.sin(r),w=f*g-h*y,k=f*y+h*g;e[q]=w-p/2,e[X]=k-m/2,n[q]=p,n[X]=m}})(st||(st={}));function pa(t,e,n,r){let o=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let l=0;l<4;l++){const c=t[l][0]*n+t[l][1]*r;c<o&&(o=c),c>s&&(s=c);const u=e[l][0]*n+e[l][1]*r;u<i&&(i=u),u>a&&(a=u)}return s<i||a<o}var kr=0,vr=1,Wr=2,Ur=3,ut;(t=>{t.create=(n,r,o,s)=>[n,r,o,s],t.fromPoints=(n,r)=>[n[0],n[1],r[0],r[1]],t.zero=()=>[0,0,0,0],t.clone=n=>[n[0],n[1],n[2],n[3]],t.origin=n=>[n[kr],n[vr]],t.direction=n=>[n[Wr],n[Ur]],t.set=(n,r,o,s,i)=>{n[kr]=r,n[vr]=o,n[Wr]=s,n[Ur]=i},t.copy=(n,r)=>{n[0]=r[0],n[1]=r[1],n[2]=r[2],n[3]=r[3]},t.setOrigin=(n,r)=>{n[kr]=r[0],n[vr]=r[1]},t.setDirection=(n,r)=>{n[Wr]=r[0],n[Ur]=r[1]},t.pointAt=(n,r)=>[n[kr]+n[Wr]*r,n[vr]+n[Ur]*r],t.intersectSegment=(n,r,o)=>{const s=n[kr],i=n[vr],a=n[Wr],l=n[Ur],c=r[0],u=r[1],f=o[0],h=o[1],p=f-c,m=h-u,g=a*m-l*p;if(Math.abs(g)<1e-10)return aS(n,r,o);const y=c-s,w=u-i,k=(y*m-w*p)/g,b=(y*l-w*a)/g;if(k>=0&&b>=0&&b<=1){const S=s+k*a,v=i+k*l;return{point:[S,v],distance:k*Math.sqrt(a*a+l*l)}}return null},t.intersectAabb=(n,r)=>{const o=[],s=n[kr],i=n[vr],a=n[Wr],l=n[Ur],c=r[0],u=r[1],f=r[2],h=r[3];if(s>=c&&s<=f){if(i<h&&l>0||i>u&&l<0){const p=u-i;o.push({point:[s,u],distance:p})}if(i>u&&l<0||i<h&&l>0){const p=h-i;o.push({point:[s,h],distance:p})}}if(i>=u&&i<=h){if(s<c&&a>0||s>c&&a<0){const p=c-s;o.push({point:[c,i],distance:p})}if(s>c&&a<0||s<f&&a>0){const p=f-s;o.push({point:[f,i],distance:p})}}return o.sort((p,m)=>p.distance-m.distance),o};const e=[[0,0],[0,0],[0,0],[0,0]];t.intersectRect=(n,r,o,s=0)=>{st.getCorners(r,o,s,e);const i=[];for(let a=0;a<4;a++){const l=(0,t.intersectSegment)(n,e[a],e[(a+1)%4]);l&&i.push(l)}return i.sort((a,l)=>a.distance-l.distance),i}})(ut||(ut={}));function aS(t,e,n){const r=t[kr],o=t[vr],s=t[Wr],i=t[Ur];return e[0]===n[0]&&e[1]===n[1]?r===e[0]&&o===e[1]?{point:[r,o],distance:0}:null:i===0&&e[1]===n[1]&&o===e[1]?Vh(t,e,n,0):s===0&&e[0]===n[0]&&r===e[0]?Vh(t,e,n,1):null}function Vh(t,e,n,r){const o=r===0?t[kr]:t[vr],s=r===0?t[Wr]:t[Ur],i=Math.min(e[r],n[r]),a=Math.max(e[r],n[r]);if(o>=i&&o<=a)return{point:[t[kr],t[vr]],distance:0};const l=[];return s>0?(e[r]>=o&&l.push({point:e,distance:e[r]-o}),n[r]>=o&&l.push({point:n,distance:n[r]-o})):s<0&&(e[r]<=o&&l.push({point:e,distance:o-e[r]}),n[r]<=o&&l.push({point:n,distance:o-n[r]})),l.length===0?null:l.reduce((c,u)=>u.distance<c.distance?u:c)}var Hc=Math.PI*2,xt;(t=>{t.clamp=(e,n,r)=>Math.min(r,Math.max(n,e)),t.lerp=(e,n,r)=>e+(n-e)*r,t.normalizeAngle=e=>{const n=e%Hc;return n<0?n+Hc:n},t.normalizeAngleSigned=e=>{const n=(0,t.normalizeAngle)(e);return n>Math.PI?n-Hc:n},t.anglesApproxEqual=(e,n,r=1e-4)=>Math.abs((0,t.normalizeAngleSigned)(e-n))<r,t.approxEqual=(e,n,r=1e-4)=>Math.abs(e-n)<r})(xt||(xt={}));function B(t,e,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,l);const c=i.prototype,u=Object.keys(c);for(let f=0;f<u.length;f++){const h=u[f];h in a||(a[h]=c[h].bind(a))}}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var l;const c=n!=null&&n.Parent?new s:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>{var l,c;return n!=null&&n.Parent&&a instanceof n.Parent?!0:(c=(l=a==null?void 0:a._zod)==null?void 0:l.traits)==null?void 0:c.has(t)}}),Object.defineProperty(i,"name",{value:t}),i}class gs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Fh extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const Wh={};function Hr(t){return Wh}function Uh(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function jc(t,e){return typeof e=="bigint"?e.toString():e}function Zc(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Kc(t){return t==null}function Yc(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function lS(t,e){const n=(t.toString().split(".")[1]||"").length,r=e.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const l=r.match(/\d?e-(\d?)/);l!=null&&l[1]&&(o=Number.parseInt(l[1]))}const s=n>o?n:o,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}const Hh=Symbol("evaluating");function xe(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==Hh)return r===void 0&&(r=Hh,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function xo(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jr(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function jh(t){return JSON.stringify(t)}function cS(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Zh="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ma(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const uS=Zc(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ys(t){if(ma(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(ma(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Kh(t){return ys(t)?{...t}:Array.isArray(t)?[...t]:t}const dS=new Set(["string","number","symbol"]);function ga(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zr(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(r._zod.parent=t),r}function te(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function fS(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const hS={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pS(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=jr(t._zod.def,{get shape(){const i={};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=n.shape[a])}return xo(this,"shape",i),i},checks:[]});return Zr(t,s)}function mS(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=jr(t._zod.def,{get shape(){const i={...t._zod.def.shape};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return xo(this,"shape",i),i},checks:[]});return Zr(t,s)}function gS(t,e){if(!ys(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0){const s=t._zod.def.shape;for(const i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=jr(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return xo(this,"shape",s),s}});return Zr(t,o)}function yS(t,e){if(!ys(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=jr(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return xo(this,"shape",r),r}});return Zr(t,n)}function wS(t,e){const n=jr(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return xo(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Zr(t,n)}function kS(t,e,n){const o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=jr(e._zod.def,{get shape(){const a=e._zod.def.shape,l={...a};if(n)for(const c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=t?new t({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)l[c]=t?new t({type:"optional",innerType:a[c]}):a[c];return xo(this,"shape",l),l},checks:[]});return Zr(e,i)}function vS(t,e,n){const r=jr(e._zod.def,{get shape(){const o=e._zod.def.shape,s={...o};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(const i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return xo(this,"shape",s),s}});return Zr(e,r)}function ws(t,e=0){var n;if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(((n=t.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function To(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function ya(t){return typeof t=="string"?t:t==null?void 0:t.message}function Kr(t,e,n){var o,s,i,a,l,c;const r={...t,path:t.path??[]};if(!t.message){const u=ya((i=(s=(o=t.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,t))??ya((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??ya((l=n.customError)==null?void 0:l.call(n,t))??ya((c=n.localeError)==null?void 0:c.call(n,t))??"Invalid input";r.message=u}return delete r.inst,delete r.continue,e!=null&&e.reportInput||delete r.input,r}function qc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function li(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Yh=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,jc,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qh=B("$ZodError",Yh),wa=B("$ZodError",Yh,{Parent:Error});function bS(t,e=n=>n.message){const n={},r=[];for(const o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function SS(t,e=n=>n.message){const n={_errors:[]},r=o=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>r({issues:i}));else if(s.code==="invalid_key")r({issues:s.issues});else if(s.code==="invalid_element")r({issues:s.issues});else if(s.path.length===0)n._errors.push(e(s));else{let i=n,a=0;for(;a<s.path.length;){const l=s.path[a];a===s.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(e(s))):i[l]=i[l]||{_errors:[]},i=i[l],a++}}};return r(t),n}const ka=t=>(e,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new gs;if(i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>Kr(l,s,Hr())));throw Zh(a,o==null?void 0:o.callee),a}return i.value},Xh=ka(wa),va=t=>async(e,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>Kr(l,s,Hr())));throw Zh(a,o==null?void 0:o.callee),a}return i.value},Gh=va(wa),ba=t=>(e,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new gs;return s.issues.length?{success:!1,error:new(t??qh)(s.issues.map(i=>Kr(i,o,Hr())))}:{success:!0,data:s.value}},ES=ba(wa),Sa=t=>async(e,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Kr(i,o,Hr())))}:{success:!0,data:s.value}},CS=Sa(wa),xS=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ka(t)(e,n,o)},TS=t=>(e,n,r)=>ka(t)(e,n,r),MS=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return va(t)(e,n,o)},AS=t=>async(e,n,r)=>va(t)(e,n,r),_S=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return ba(t)(e,n,o)},IS=t=>(e,n,r)=>ba(t)(e,n,r),BS=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Sa(t)(e,n,o)},NS=t=>async(e,n,r)=>Sa(t)(e,n,r),PS=/^[cC][^\s-]{8,}$/,DS=/^[0-9a-z]+$/,OS=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RS=/^[0-9a-vA-V]{20}$/,zS=/^[A-Za-z0-9]{27}$/,$S=/^[a-zA-Z0-9_-]{21}$/,LS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,VS=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Jh=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,FS=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,WS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function US(){return new RegExp(WS,"u")}const HS=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,jS=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ZS=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,KS=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,YS=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qh=/^[A-Za-z0-9_-]*$/,qS=/^\+[1-9]\d{6,14}$/,ep="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",XS=new RegExp(`^${ep}$`);function tp(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function GS(t){return new RegExp(`^${tp(t)}$`)}function JS(t){const e=tp({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${ep}T(?:${r})$`)}const QS=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},eE=/^-?\d+$/,np=/^-?\d+(?:\.\d+)?$/,tE=/^(?:true|false)$/i,nE=/^[^A-Z]*$/,rE=/^[^a-z]*$/,Yt=B("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),rp={number:"number",bigint:"bigint",object:"date"},op=B("$ZodCheckLessThan",(t,e)=>{Yt.init(t,e);const n=rp[typeof e.value];t._zod.onattach.push(r=>{const o=r._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),sp=B("$ZodCheckGreaterThan",(t,e)=>{Yt.init(t,e);const n=rp[typeof e.value];t._zod.onattach.push(r=>{const o=r._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),oE=B("$ZodCheckMultipleOf",(t,e)=>{Yt.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):lS(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),sE=B("$ZodCheckNumberFormat",(t,e)=>{var i;Yt.init(t,e),e.format=e.format||"float64";const n=(i=e.format)==null?void 0:i.includes("int"),r=n?"int":"number",[o,s]=hS[e.format];t._zod.onattach.push(a=>{const l=a._zod.bag;l.format=e.format,l.minimum=o,l.maximum=s,n&&(l.pattern=eE)}),t._zod.check=a=>{const l=a.value;if(n){if(!Number.isInteger(l)){a.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?a.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):a.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}l<o&&a.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),l>s&&a.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}}),iE=B("$ZodCheckMaxLength",(t,e)=>{var n;Yt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!Kc(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const o=r.value;if(o.length<=e.maximum)return;const i=qc(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),aE=B("$ZodCheckMinLength",(t,e)=>{var n;Yt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!Kc(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const o=r.value;if(o.length>=e.minimum)return;const i=qc(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),lE=B("$ZodCheckLengthEquals",(t,e)=>{var n;Yt.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!Kc(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{const o=r.value,s=o.length;if(s===e.length)return;const i=qc(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Ea=B("$ZodCheckStringFormat",(t,e)=>{var n,r;Yt.init(t,e),t._zod.onattach.push(o=>{const s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),cE=B("$ZodCheckRegex",(t,e)=>{Ea.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),uE=B("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=nE),Ea.init(t,e)}),dE=B("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=rE),Ea.init(t,e)}),fE=B("$ZodCheckIncludes",(t,e)=>{Yt.init(t,e);const n=ga(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),hE=B("$ZodCheckStartsWith",(t,e)=>{Yt.init(t,e);const n=new RegExp(`^${ga(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),pE=B("$ZodCheckEndsWith",(t,e)=>{Yt.init(t,e);const n=new RegExp(`.*${ga(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),mE=B("$ZodCheckOverwrite",(t,e)=>{Yt.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class gE{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
2
2
  `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const e=Function,n=this==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`
3
- `))}}const lE={major:4,minor:3,patch:6},De=I("$ZodType",(t,e)=>{var o;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=lE;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const i of s._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),(o=t._zod.deferred)==null||o.push(()=>{t._zod.run=t._zod.parse});else{const s=(a,l,c)=>{let u=hs(a),d;for(const h of l){if(h._zod.def.when){if(!h._zod.def.when(a))continue}else if(u)continue;const p=a.issues.length,m=h._zod.check(a);if(m instanceof Promise&&(c==null?void 0:c.async)===!1)throw new ds;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,a.issues.length!==p&&(u||(u=hs(a,p)))});else{if(a.issues.length===p)continue;u||(u=hs(a,p))}}return d?d.then(()=>a):a},i=(a,l,c)=>{if(hs(a))return a.aborted=!0,a;const u=s(l,r,c);if(u instanceof Promise){if(c.async===!1)throw new ds;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(a,l)=>{if(l.skipChecks)return t._zod.parse(a,l);if(l.direction==="backward"){const u=t._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(d=>i(d,a,l)):i(u,a,l)}const c=t._zod.parse(a,l);if(c instanceof Promise){if(l.async===!1)throw new ds;return c.then(u=>s(u,r,l))}return s(c,r,l)}}Ee(t,"~standard",()=>({validate:s=>{var i;try{const a=pS(t,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return mS(t,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}))}),Fc=I("$ZodString",(t,e)=>{var n;De.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??HS(t._zod.bag),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Fe=I("$ZodStringFormat",(t,e)=>{ya.init(t,e),Fc.init(t,e)}),cE=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=BS),Fe.init(t,e)}),uE=I("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Fh(r))}else e.pattern??(e.pattern=Fh());Fe.init(t,e)}),dE=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=PS),Fe.init(t,e)}),fE=I("$ZodURL",(t,e)=>{Fe.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),hE=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=DS()),Fe.init(t,e)}),pE=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=AS),Fe.init(t,e)}),mE=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=CS),Fe.init(t,e)}),gE=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=xS),Fe.init(t,e)}),yE=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=TS),Fe.init(t,e)}),wE=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=MS),Fe.init(t,e)}),kE=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=_S),Fe.init(t,e)}),vE=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=US(e)),Fe.init(t,e)}),bE=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=VS),Fe.init(t,e)}),SE=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=WS(e)),Fe.init(t,e)}),EE=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=IS),Fe.init(t,e)}),CE=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=OS),Fe.init(t,e),t._zod.bag.format="ipv4"}),xE=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=RS),Fe.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),TE=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=zS),Fe.init(t,e)}),ME=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=$S),Fe.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,s]=r;if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Yh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const _E=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=LS),Fe.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{Yh(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function AE(t){if(!Vh.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Yh(n)}const IE=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Vh),Fe.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{AE(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),BE=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=FS),Fe.init(t,e)});function PE(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}const NE=I("$ZodJWT",(t,e)=>{Fe.init(t,e),t._zod.check=n=>{PE(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),qh=I("$ZodNumber",(t,e)=>{De.init(t,e),t._zod.pattern=t._zod.bag.pattern??Hh,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),DE=I("$ZodNumberFormat",(t,e)=>{JS.init(t,e),qh.init(t,e)}),OE=I("$ZodBoolean",(t,e)=>{De.init(t,e),t._zod.pattern=ZS,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),RE=I("$ZodUnknown",(t,e)=>{De.init(t,e),t._zod.parse=n=>n}),zE=I("$ZodNever",(t,e)=>{De.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Jh(t,e,n){t.issues.length&&e.issues.push(...Eo(n,t.issues)),e.value[n]=t.value}const $E=I("$ZodArray",(t,e)=>{De.init(t,e),t._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);const s=[];for(let i=0;i<o.length;i++){const a=o[i],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?s.push(l.then(c=>Jh(c,n,i))):Jh(l,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function wa(t,e,n,r,o){if(t.issues.length){if(o&&!(n in r))return;e.issues.push(...Eo(n,t.issues))}t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Xh(t){var r,o,s,i;const e=Object.keys(t.shape);for(const a of e)if(!((i=(s=(o=(r=t.shape)==null?void 0:r[a])==null?void 0:o._zod)==null?void 0:s.traits)!=null&&i.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=rS(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Gh(t,e,n,r,o,s){const i=[],a=o.keySet,l=o.catchall._zod,c=l.def.type,u=l.optout==="optional";for(const d in e){if(a.has(d))continue;if(c==="never"){i.push(d);continue}const h=l.run({value:e[d],issues:[]},r);h instanceof Promise?t.push(h.then(p=>wa(p,n,d,e,u))):wa(h,n,d,e,u)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}const LE=I("$ZodObject",(t,e)=>{De.init(t,e);const n=Object.getOwnPropertyDescriptor(e,"shape");if(!(n!=null&&n.get)){const a=e.shape;Object.defineProperty(e,"shape",{get:()=>{const l={...a};return Object.defineProperty(e,"shape",{value:l}),l}})}const r=Rc(()=>Xh(e));Ee(t._zod,"propValues",()=>{const a=e.shape,l={};for(const c in a){const u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(const d of u.values)l[c].add(d)}}return l});const o=ca,s=e.catchall;let i;t._zod.parse=(a,l)=>{i??(i=r.value);const c=a.value;if(!o(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),a;a.value={};const u=[],d=i.shape;for(const h of i.keys){const p=d[h],m=p._zod.optout==="optional",g=p._zod.run({value:c[h],issues:[]},l);g instanceof Promise?u.push(g.then(y=>wa(y,a,h,c,m))):wa(g,a,h,c,m)}return s?Gh(u,c,a,l,r.value,t):u.length?Promise.all(u).then(()=>a):a}}),FE=I("$ZodObjectJIT",(t,e)=>{LE.init(t,e);const n=t._zod.parse,r=Rc(()=>Xh(e)),o=h=>{var b;const p=new aE(["shape","payload","ctx"]),m=r.value,g=S=>{const v=Nh(S);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let w=0;for(const S of m.keys)y[S]=`key_${w++}`;p.write("const newResult = {};");for(const S of m.keys){const v=y[S],x=Nh(S),T=h[S],A=((b=T==null?void 0:T._zod)==null?void 0:b.optout)==="optional";p.write(`const ${v} = ${g(S)};`),A?p.write(`
3
+ `))}}const yE={major:4,minor:3,patch:6},Oe=B("$ZodType",(t,e)=>{var o;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=yE;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const i of s._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),(o=t._zod.deferred)==null||o.push(()=>{t._zod.run=t._zod.parse});else{const s=(a,l,c)=>{let u=ws(a),f;for(const h of l){if(h._zod.def.when){if(!h._zod.def.when(a))continue}else if(u)continue;const p=a.issues.length,m=h._zod.check(a);if(m instanceof Promise&&(c==null?void 0:c.async)===!1)throw new gs;if(f||m instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await m,a.issues.length!==p&&(u||(u=ws(a,p)))});else{if(a.issues.length===p)continue;u||(u=ws(a,p))}}return f?f.then(()=>a):a},i=(a,l,c)=>{if(ws(a))return a.aborted=!0,a;const u=s(l,r,c);if(u instanceof Promise){if(c.async===!1)throw new gs;return u.then(f=>t._zod.parse(f,c))}return t._zod.parse(u,c)};t._zod.run=(a,l)=>{if(l.skipChecks)return t._zod.parse(a,l);if(l.direction==="backward"){const u=t._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(f=>i(f,a,l)):i(u,a,l)}const c=t._zod.parse(a,l);if(c instanceof Promise){if(l.async===!1)throw new gs;return c.then(u=>s(u,r,l))}return s(c,r,l)}}xe(t,"~standard",()=>({validate:s=>{var i;try{const a=ES(t,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return CS(t,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}))}),Xc=B("$ZodString",(t,e)=>{var n;Oe.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??QS(t._zod.bag),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Fe=B("$ZodStringFormat",(t,e)=>{Ea.init(t,e),Xc.init(t,e)}),wE=B("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=VS),Fe.init(t,e)}),kE=B("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Jh(r))}else e.pattern??(e.pattern=Jh());Fe.init(t,e)}),vE=B("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=FS),Fe.init(t,e)}),bE=B("$ZodURL",(t,e)=>{Fe.init(t,e),t._zod.check=n=>{try{const r=n.value.trim(),o=new URL(r);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),SE=B("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=US()),Fe.init(t,e)}),EE=B("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=$S),Fe.init(t,e)}),CE=B("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=PS),Fe.init(t,e)}),xE=B("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=DS),Fe.init(t,e)}),TE=B("$ZodULID",(t,e)=>{e.pattern??(e.pattern=OS),Fe.init(t,e)}),ME=B("$ZodXID",(t,e)=>{e.pattern??(e.pattern=RS),Fe.init(t,e)}),AE=B("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=zS),Fe.init(t,e)}),_E=B("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=JS(e)),Fe.init(t,e)}),IE=B("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=XS),Fe.init(t,e)}),BE=B("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=GS(e)),Fe.init(t,e)}),NE=B("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=LS),Fe.init(t,e)}),PE=B("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=HS),Fe.init(t,e),t._zod.bag.format="ipv4"}),DE=B("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=jS),Fe.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),OE=B("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ZS),Fe.init(t,e)}),RE=B("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=KS),Fe.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[o,s]=r;if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function ip(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const zE=B("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=YS),Fe.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{ip(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function $E(t){if(!Qh.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return ip(n)}const LE=B("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Qh),Fe.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{$E(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),VE=B("$ZodE164",(t,e)=>{e.pattern??(e.pattern=qS),Fe.init(t,e)});function FE(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}const WE=B("$ZodJWT",(t,e)=>{Fe.init(t,e),t._zod.check=n=>{FE(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),ap=B("$ZodNumber",(t,e)=>{Oe.init(t,e),t._zod.pattern=t._zod.bag.pattern??np,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),UE=B("$ZodNumberFormat",(t,e)=>{sE.init(t,e),ap.init(t,e)}),HE=B("$ZodBoolean",(t,e)=>{Oe.init(t,e),t._zod.pattern=tE,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),jE=B("$ZodUnknown",(t,e)=>{Oe.init(t,e),t._zod.parse=n=>n}),ZE=B("$ZodNever",(t,e)=>{Oe.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function lp(t,e,n){t.issues.length&&e.issues.push(...To(n,t.issues)),e.value[n]=t.value}const KE=B("$ZodArray",(t,e)=>{Oe.init(t,e),t._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);const s=[];for(let i=0;i<o.length;i++){const a=o[i],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?s.push(l.then(c=>lp(c,n,i))):lp(l,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Ca(t,e,n,r,o){if(t.issues.length){if(o&&!(n in r))return;e.issues.push(...To(n,t.issues))}t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function cp(t){var r,o,s,i;const e=Object.keys(t.shape);for(const a of e)if(!((i=(s=(o=(r=t.shape)==null?void 0:r[a])==null?void 0:o._zod)==null?void 0:s.traits)!=null&&i.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=fS(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function up(t,e,n,r,o,s){const i=[],a=o.keySet,l=o.catchall._zod,c=l.def.type,u=l.optout==="optional";for(const f in e){if(a.has(f))continue;if(c==="never"){i.push(f);continue}const h=l.run({value:e[f],issues:[]},r);h instanceof Promise?t.push(h.then(p=>Ca(p,n,f,e,u))):Ca(h,n,f,e,u)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}const YE=B("$ZodObject",(t,e)=>{Oe.init(t,e);const n=Object.getOwnPropertyDescriptor(e,"shape");if(!(n!=null&&n.get)){const a=e.shape;Object.defineProperty(e,"shape",{get:()=>{const l={...a};return Object.defineProperty(e,"shape",{value:l}),l}})}const r=Zc(()=>cp(e));xe(t._zod,"propValues",()=>{const a=e.shape,l={};for(const c in a){const u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(const f of u.values)l[c].add(f)}}return l});const o=ma,s=e.catchall;let i;t._zod.parse=(a,l)=>{i??(i=r.value);const c=a.value;if(!o(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),a;a.value={};const u=[],f=i.shape;for(const h of i.keys){const p=f[h],m=p._zod.optout==="optional",g=p._zod.run({value:c[h],issues:[]},l);g instanceof Promise?u.push(g.then(y=>Ca(y,a,h,c,m))):Ca(g,a,h,c,m)}return s?up(u,c,a,l,r.value,t):u.length?Promise.all(u).then(()=>a):a}}),qE=B("$ZodObjectJIT",(t,e)=>{YE.init(t,e);const n=t._zod.parse,r=Zc(()=>cp(e)),o=h=>{var b;const p=new gE(["shape","payload","ctx"]),m=r.value,g=S=>{const v=jh(S);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let w=0;for(const S of m.keys)y[S]=`key_${w++}`;p.write("const newResult = {};");for(const S of m.keys){const v=y[S],E=jh(S),T=h[S],_=((b=T==null?void 0:T._zod)==null?void 0:b.optout)==="optional";p.write(`const ${v} = ${g(S)};`),_?p.write(`
4
4
  if (${v}.issues.length) {
5
- if (${x} in input) {
5
+ if (${E} in input) {
6
6
  payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
7
7
  ...iss,
8
- path: iss.path ? [${x}, ...iss.path] : [${x}]
8
+ path: iss.path ? [${E}, ...iss.path] : [${E}]
9
9
  })));
10
10
  }
11
11
  }
12
12
 
13
13
  if (${v}.value === undefined) {
14
- if (${x} in input) {
15
- newResult[${x}] = undefined;
14
+ if (${E} in input) {
15
+ newResult[${E}] = undefined;
16
16
  }
17
17
  } else {
18
- newResult[${x}] = ${v}.value;
18
+ newResult[${E}] = ${v}.value;
19
19
  }
20
20
 
21
21
  `):p.write(`
22
22
  if (${v}.issues.length) {
23
23
  payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
24
24
  ...iss,
25
- path: iss.path ? [${x}, ...iss.path] : [${x}]
25
+ path: iss.path ? [${E}, ...iss.path] : [${E}]
26
26
  })));
27
27
  }
28
28
 
29
29
  if (${v}.value === undefined) {
30
- if (${x} in input) {
31
- newResult[${x}] = undefined;
30
+ if (${E} in input) {
31
+ newResult[${E}] = undefined;
32
32
  }
33
33
  } else {
34
- newResult[${x}] = ${v}.value;
34
+ newResult[${E}] = ${v}.value;
35
35
  }
36
36
 
37
- `)}p.write("payload.value = newResult;"),p.write("return payload;");const k=p.compile();return(S,v)=>k(h,S,v)};let s;const i=ca,a=!Ih.jitless,c=a&&tS.value,u=e.catchall;let d;t._zod.parse=(h,p)=>{d??(d=r.value);const m=h.value;return i(m)?a&&c&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(s||(s=o(e.shape)),h=s(h,p),u?Gh([],m,h,p,d,t):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),h)}});function Qh(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;const o=t.filter(s=>!hs(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>Hr(i,r,Vr())))}),e)}const VE=I("$ZodUnion",(t,e)=>{De.init(t,e),Ee(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ee(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ee(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),Ee(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){const o=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>$c(s.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(o,s)=>{if(n)return r(o,s);let i=!1;const a=[];for(const l of e.options){const c=l._zod.run({value:o.value,issues:[]},s);if(c instanceof Promise)a.push(c),i=!0;else{if(c.issues.length===0)return c;a.push(c)}}return i?Promise.all(a).then(l=>Qh(l,o,t,s)):Qh(a,o,t,s)}}),WE=I("$ZodIntersection",(t,e)=>{De.init(t,e),t._zod.parse=(n,r)=>{const o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>ep(n,l,c)):ep(n,s,i)}});function Vc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(fs(t)&&fs(e)){const n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(const s of r){const i=Vc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const o=t[r],s=e[r],i=Vc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ep(t,e,n){const r=new Map;let o;for(const a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(const l of a.keys)r.has(l)||r.set(l,{}),r.get(l).l=!0}else t.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const l of a.keys)r.has(l)||r.set(l,{}),r.get(l).r=!0;else t.issues.push(a);const s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),hs(t))return t;const i=Vc(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}const tp=I("$ZodTuple",(t,e)=>{De.init(t,e);const n=e.items;t._zod.parse=(r,o)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),r;r.value=[];const i=[],a=[...n].reverse().findIndex(u=>u._zod.optin!=="optional"),l=a===-1?0:n.length-a;if(!e.rest){const u=s.length>n.length,d=s.length<l-1;if(u||d)return r.issues.push({...u?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:s,inst:t,origin:"array"}),r}let c=-1;for(const u of n){if(c++,c>=s.length&&c>=l)continue;const d=u._zod.run({value:s[c],issues:[]},o);d instanceof Promise?i.push(d.then(h=>ka(h,r,c))):ka(d,r,c)}if(e.rest){const u=s.slice(n.length);for(const d of u){c++;const h=e.rest._zod.run({value:d,issues:[]},o);h instanceof Promise?i.push(h.then(p=>ka(p,r,c))):ka(h,r,c)}}return i.length?Promise.all(i).then(()=>r):r}});function ka(t,e,n){t.issues.length&&e.issues.push(...Eo(n,t.issues)),e.value[n]=t.value}const UE=I("$ZodRecord",(t,e)=>{De.init(t,e),t._zod.parse=(n,r)=>{const o=n.value;if(!fs(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;const s=[],i=e.keyType._zod.values;if(i){n.value={};const a=new Set;for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);const u=e.valueType._zod.run({value:o[c],issues:[]},r);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&n.issues.push(...Eo(c,d.issues)),n.value[c]=d.value})):(u.issues.length&&n.issues.push(...Eo(c,u.issues)),n.value[c]=u.value)}let l;for(const c in o)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:l})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;let l=e.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Hh.test(a)&&l.issues.length){const d=e.keyType._zod.run({value:Number(a),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(l=d)}if(l.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(d=>Hr(d,r,Vr())),input:a,path:[a],inst:t});continue}const u=e.valueType._zod.run({value:o[a],issues:[]},r);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&n.issues.push(...Eo(a,d.issues)),n.value[l.value]=d.value})):(u.issues.length&&n.issues.push(...Eo(a,u.issues)),n.value[l.value]=u.value)}}return s.length?Promise.all(s).then(()=>n):n}}),HE=I("$ZodEnum",(t,e)=>{De.init(t,e);const n=Bh(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>nS.has(typeof o)).map(o=>typeof o=="string"?ua(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{const i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),jE=I("$ZodTransform",(t,e)=>{De.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ah(t.constructor.name);const o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new ds;return n.value=o,n}});function np(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const rp=I("$ZodOptional",(t,e)=>{De.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ee(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ee(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${$c(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>np(s,n.value)):np(o,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),ZE=I("$ZodExactOptional",(t,e)=>{rp.init(t,e),Ee(t._zod,"values",()=>e.innerType._zod.values),Ee(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),KE=I("$ZodNullable",(t,e)=>{De.init(t,e),Ee(t._zod,"optin",()=>e.innerType._zod.optin),Ee(t._zod,"optout",()=>e.innerType._zod.optout),Ee(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${$c(n.source)}|null)$`):void 0}),Ee(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),YE=I("$ZodDefault",(t,e)=>{De.init(t,e),t._zod.optin="optional",Ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>op(s,e)):op(o,e)}});function op(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const qE=I("$ZodPrefault",(t,e)=>{De.init(t,e),t._zod.optin="optional",Ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),JE=I("$ZodNonOptional",(t,e)=>{De.init(t,e),Ee(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>sp(s,t)):sp(o,t)}});function sp(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const XE=I("$ZodCatch",(t,e)=>{De.init(t,e),Ee(t._zod,"optin",()=>e.innerType._zod.optin),Ee(t._zod,"optout",()=>e.innerType._zod.optout),Ee(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>Hr(i,r,Vr()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>Hr(s,r,Vr()))},input:n.value}),n.issues=[]),n)}}),GE=I("$ZodPipe",(t,e)=>{De.init(t,e),Ee(t._zod,"values",()=>e.in._zod.values),Ee(t._zod,"optin",()=>e.in._zod.optin),Ee(t._zod,"optout",()=>e.out._zod.optout),Ee(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>va(i,e.in,r)):va(s,e.in,r)}const o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>va(s,e.out,r)):va(o,e.out,r)}});function va(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const QE=I("$ZodReadonly",(t,e)=>{De.init(t,e),Ee(t._zod,"propValues",()=>e.innerType._zod.propValues),Ee(t._zod,"values",()=>e.innerType._zod.values),Ee(t._zod,"optin",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Ee(t._zod,"optout",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(ip):ip(o)}});function ip(t){return t.value=Object.freeze(t.value),t}const eC=I("$ZodFunction",(t,e)=>(De.init(t,e),t._def=e,t._zod.def=e,t.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...r){const o=t._def.input?$h(t._def.input,r):r,s=Reflect.apply(n,this,o);return t._def.output?$h(t._def.output,s):s}},t.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...r){const o=t._def.input?await Lh(t._def.input,r):r,s=await Reflect.apply(n,this,o);return t._def.output?await Lh(t._def.output,s):s}},t._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:t}),n):(t._def.output&&t._def.output._zod.def.type==="promise"?n.value=t.implementAsync(n.value):n.value=t.implement(n.value),n),t.input=(...n)=>{const r=t.constructor;return Array.isArray(n[0])?new r({type:"function",input:new tp({type:"tuple",items:n[0],rest:n[1]}),output:t._def.output}):new r({type:"function",input:n[0],output:t._def.output})},t.output=n=>{const r=t.constructor;return new r({type:"function",input:t._def.input,output:n})},t)),tC=I("$ZodCustom",(t,e)=>{Yt.init(t,e),De.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>ap(s,n,r,t));ap(o,n,r,t)}});function ap(t,e,n,r){if(!t){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(Gs(o))}}var lp;class nC{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function rC(){return new nC}(lp=globalThis).__zod_globalRegistry??(lp.__zod_globalRegistry=rC());const Qs=globalThis.__zod_globalRegistry;function oC(t,e){return new t({type:"string",...ee(e)})}function sC(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ee(e)})}function cp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ee(e)})}function iC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(e)})}function aC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(e)})}function lC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(e)})}function cC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(e)})}function uC(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ee(e)})}function dC(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(e)})}function fC(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(e)})}function hC(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(e)})}function pC(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(e)})}function mC(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(e)})}function gC(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ee(e)})}function yC(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(e)})}function wC(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(e)})}function kC(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(e)})}function vC(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(e)})}function bC(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(e)})}function SC(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ee(e)})}function EC(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(e)})}function CC(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ee(e)})}function xC(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(e)})}function TC(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(e)})}function MC(t,e){return new t({type:"string",format:"date",check:"string_format",...ee(e)})}function _C(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ee(e)})}function AC(t,e){return new t({type:"string",format:"duration",check:"string_format",...ee(e)})}function IC(t,e){return new t({type:"number",checks:[],...ee(e)})}function BC(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(e)})}function PC(t,e){return new t({type:"boolean",...ee(e)})}function NC(t){return new t({type:"unknown"})}function DC(t,e){return new t({type:"never",...ee(e)})}function up(t,e){return new Zh({check:"less_than",...ee(e),value:t,inclusive:!1})}function Wc(t,e){return new Zh({check:"less_than",...ee(e),value:t,inclusive:!0})}function dp(t,e){return new Kh({check:"greater_than",...ee(e),value:t,inclusive:!1})}function Uc(t,e){return new Kh({check:"greater_than",...ee(e),value:t,inclusive:!0})}function fp(t,e){return new qS({check:"multiple_of",...ee(e),value:t})}function hp(t,e){return new XS({check:"max_length",...ee(e),maximum:t})}function ba(t,e){return new GS({check:"min_length",...ee(e),minimum:t})}function pp(t,e){return new QS({check:"length_equals",...ee(e),length:t})}function OC(t,e){return new eE({check:"string_format",format:"regex",...ee(e),pattern:t})}function RC(t){return new tE({check:"string_format",format:"lowercase",...ee(t)})}function zC(t){return new nE({check:"string_format",format:"uppercase",...ee(t)})}function $C(t,e){return new rE({check:"string_format",format:"includes",...ee(e),includes:t})}function LC(t,e){return new oE({check:"string_format",format:"starts_with",...ee(e),prefix:t})}function FC(t,e){return new sE({check:"string_format",format:"ends_with",...ee(e),suffix:t})}function ps(t){return new iE({check:"overwrite",tx:t})}function VC(t){return ps(e=>e.normalize(t))}function WC(){return ps(t=>t.trim())}function UC(){return ps(t=>t.toLowerCase())}function HC(){return ps(t=>t.toUpperCase())}function jC(){return ps(t=>eS(t))}function ZC(t,e,n){return new t({type:"array",element:e,...ee(n)})}function KC(t,e,n){const r=ee(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function YC(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ee(n)})}function qC(t){const e=JC(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Gs(r,n.value,e._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(Gs(o))}},t(n.value,n)));return e}function JC(t,e){const n=new Yt({check:"custom",...ee(e)});return n._zod.check=t,n}function mp(t){let e=(t==null?void 0:t.target)??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:(t==null?void 0:t.metadata)??Qs,target:e,unrepresentable:(t==null?void 0:t.unrepresentable)??"throw",override:(t==null?void 0:t.override)??(()=>{}),io:(t==null?void 0:t.io)??"output",counter:0,seen:new Map,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0}}function je(t,e,n={path:[],schemaPath:[]}){var u,d;var r;const o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);const a=(d=(u=t._zod).toJSONSchema)==null?void 0:d.call(u);if(a)i.schema=a;else{const h={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,h);else{const m=i.schema,g=e.processors[o.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);g(t,e,m,h)}const p=t._zod.parent;p&&(i.ref||(i.ref=p),je(p,e,h),e.seen.get(p).isParent=!0)}const l=e.metadataRegistry.get(t);return l&&Object.assign(i.schema,l),e.io==="input"&&$t(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function gp(t,e){var i,a,l,c;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of t.seen.entries()){const d=(i=t.metadataRegistry.get(u[0]))==null?void 0:i.id;if(d){const h=r.get(d);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(d,u[0])}}const o=u=>{var g;const d=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const y=(g=t.external.registry.get(u[0]))==null?void 0:g.id,w=t.external.uri??(b=>b);if(y)return{ref:w(y)};const k=u[1].defId??u[1].schema.id??`schema${t.counter++}`;return u[1].defId=k,{defId:k,ref:`${w("__shared")}#/${d}/${k}`}}if(u[1]===n)return{ref:"#"};const p=`#/${d}/`,m=u[1].schema.id??`__schema${t.counter++}`;return{defId:m,ref:p+m}},s=u=>{if(u[1].schema.$ref)return;const d=u[1],{ref:h,defId:p}=o(u);d.def={...d.schema},p&&(d.defId=p);const m=d.schema;for(const g in m)delete m[g];m.$ref=h};if(t.cycles==="throw")for(const u of t.seen.entries()){const d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${(a=d.cycle)==null?void 0:a.join("/")}/<root>
37
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");const k=p.compile();return(S,v)=>k(h,S,v)};let s;const i=ma,a=!Wh.jitless,c=a&&uS.value,u=e.catchall;let f;t._zod.parse=(h,p)=>{f??(f=r.value);const m=h.value;return i(m)?a&&c&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(s||(s=o(e.shape)),h=s(h,p),u?up([],m,h,p,f,t):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),h)}});function dp(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;const o=t.filter(s=>!ws(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>Kr(i,r,Hr())))}),e)}const XE=B("$ZodUnion",(t,e)=>{Oe.init(t,e),xe(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),xe(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),xe(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),xe(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){const o=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>Yc(s.source)).join("|")})$`)}});const n=e.options.length===1,r=e.options[0]._zod.run;t._zod.parse=(o,s)=>{if(n)return r(o,s);let i=!1;const a=[];for(const l of e.options){const c=l._zod.run({value:o.value,issues:[]},s);if(c instanceof Promise)a.push(c),i=!0;else{if(c.issues.length===0)return c;a.push(c)}}return i?Promise.all(a).then(l=>dp(l,o,t,s)):dp(a,o,t,s)}}),GE=B("$ZodIntersection",(t,e)=>{Oe.init(t,e),t._zod.parse=(n,r)=>{const o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,c])=>fp(n,l,c)):fp(n,s,i)}});function Gc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ys(t)&&ys(e)){const n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(const s of r){const i=Gc(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const o=t[r],s=e[r],i=Gc(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function fp(t,e,n){const r=new Map;let o;for(const a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(const l of a.keys)r.has(l)||r.set(l,{}),r.get(l).l=!0}else t.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const l of a.keys)r.has(l)||r.set(l,{}),r.get(l).r=!0;else t.issues.push(a);const s=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),ws(t))return t;const i=Gc(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}const hp=B("$ZodTuple",(t,e)=>{Oe.init(t,e);const n=e.items;t._zod.parse=(r,o)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),r;r.value=[];const i=[],a=[...n].reverse().findIndex(u=>u._zod.optin!=="optional"),l=a===-1?0:n.length-a;if(!e.rest){const u=s.length>n.length,f=s.length<l-1;if(u||f)return r.issues.push({...u?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:s,inst:t,origin:"array"}),r}let c=-1;for(const u of n){if(c++,c>=s.length&&c>=l)continue;const f=u._zod.run({value:s[c],issues:[]},o);f instanceof Promise?i.push(f.then(h=>xa(h,r,c))):xa(f,r,c)}if(e.rest){const u=s.slice(n.length);for(const f of u){c++;const h=e.rest._zod.run({value:f,issues:[]},o);h instanceof Promise?i.push(h.then(p=>xa(p,r,c))):xa(h,r,c)}}return i.length?Promise.all(i).then(()=>r):r}});function xa(t,e,n){t.issues.length&&e.issues.push(...To(n,t.issues)),e.value[n]=t.value}const JE=B("$ZodRecord",(t,e)=>{Oe.init(t,e),t._zod.parse=(n,r)=>{const o=n.value;if(!ys(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;const s=[],i=e.keyType._zod.values;if(i){n.value={};const a=new Set;for(const c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);const u=e.valueType._zod.run({value:o[c],issues:[]},r);u instanceof Promise?s.push(u.then(f=>{f.issues.length&&n.issues.push(...To(c,f.issues)),n.value[c]=f.value})):(u.issues.length&&n.issues.push(...To(c,u.issues)),n.value[c]=u.value)}let l;for(const c in o)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:l})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;let l=e.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&np.test(a)&&l.issues.length){const f=e.keyType._zod.run({value:Number(a),issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(l=f)}if(l.issues.length){e.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(f=>Kr(f,r,Hr())),input:a,path:[a],inst:t});continue}const u=e.valueType._zod.run({value:o[a],issues:[]},r);u instanceof Promise?s.push(u.then(f=>{f.issues.length&&n.issues.push(...To(a,f.issues)),n.value[l.value]=f.value})):(u.issues.length&&n.issues.push(...To(a,u.issues)),n.value[l.value]=u.value)}}return s.length?Promise.all(s).then(()=>n):n}}),QE=B("$ZodEnum",(t,e)=>{Oe.init(t,e);const n=Uh(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>dS.has(typeof o)).map(o=>typeof o=="string"?ga(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{const i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:t}),o}}),eC=B("$ZodTransform",(t,e)=>{Oe.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Fh(t.constructor.name);const o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new gs;return n.value=o,n}});function pp(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const mp=B("$ZodOptional",(t,e)=>{Oe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",xe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),xe(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Yc(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>pp(s,n.value)):pp(o,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),tC=B("$ZodExactOptional",(t,e)=>{mp.init(t,e),xe(t._zod,"values",()=>e.innerType._zod.values),xe(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),nC=B("$ZodNullable",(t,e)=>{Oe.init(t,e),xe(t._zod,"optin",()=>e.innerType._zod.optin),xe(t._zod,"optout",()=>e.innerType._zod.optout),xe(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Yc(n.source)}|null)$`):void 0}),xe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),rC=B("$ZodDefault",(t,e)=>{Oe.init(t,e),t._zod.optin="optional",xe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>gp(s,e)):gp(o,e)}});function gp(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const oC=B("$ZodPrefault",(t,e)=>{Oe.init(t,e),t._zod.optin="optional",xe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),sC=B("$ZodNonOptional",(t,e)=>{Oe.init(t,e),xe(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>yp(s,t)):yp(o,t)}});function yp(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const iC=B("$ZodCatch",(t,e)=>{Oe.init(t,e),xe(t._zod,"optin",()=>e.innerType._zod.optin),xe(t._zod,"optout",()=>e.innerType._zod.optout),xe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>Kr(i,r,Hr()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>Kr(s,r,Hr()))},input:n.value}),n.issues=[]),n)}}),aC=B("$ZodPipe",(t,e)=>{Oe.init(t,e),xe(t._zod,"values",()=>e.in._zod.values),xe(t._zod,"optin",()=>e.in._zod.optin),xe(t._zod,"optout",()=>e.out._zod.optout),xe(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const s=e.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Ta(i,e.in,r)):Ta(s,e.in,r)}const o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Ta(s,e.out,r)):Ta(o,e.out,r)}});function Ta(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const lC=B("$ZodReadonly",(t,e)=>{Oe.init(t,e),xe(t._zod,"propValues",()=>e.innerType._zod.propValues),xe(t._zod,"values",()=>e.innerType._zod.values),xe(t._zod,"optin",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),xe(t._zod,"optout",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(wp):wp(o)}});function wp(t){return t.value=Object.freeze(t.value),t}const cC=B("$ZodFunction",(t,e)=>(Oe.init(t,e),t._def=e,t._zod.def=e,t.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...r){const o=t._def.input?Xh(t._def.input,r):r,s=Reflect.apply(n,this,o);return t._def.output?Xh(t._def.output,s):s}},t.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...r){const o=t._def.input?await Gh(t._def.input,r):r,s=await Reflect.apply(n,this,o);return t._def.output?await Gh(t._def.output,s):s}},t._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:t}),n):(t._def.output&&t._def.output._zod.def.type==="promise"?n.value=t.implementAsync(n.value):n.value=t.implement(n.value),n),t.input=(...n)=>{const r=t.constructor;return Array.isArray(n[0])?new r({type:"function",input:new hp({type:"tuple",items:n[0],rest:n[1]}),output:t._def.output}):new r({type:"function",input:n[0],output:t._def.output})},t.output=n=>{const r=t.constructor;return new r({type:"function",input:t._def.input,output:n})},t)),uC=B("$ZodCustom",(t,e)=>{Yt.init(t,e),Oe.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>kp(s,n,r,t));kp(o,n,r,t)}});function kp(t,e,n,r){if(!t){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(li(o))}}var vp;class dC{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function fC(){return new dC}(vp=globalThis).__zod_globalRegistry??(vp.__zod_globalRegistry=fC());const ci=globalThis.__zod_globalRegistry;function hC(t,e){return new t({type:"string",...te(e)})}function pC(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...te(e)})}function bp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...te(e)})}function mC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...te(e)})}function gC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...te(e)})}function yC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...te(e)})}function wC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...te(e)})}function kC(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...te(e)})}function vC(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...te(e)})}function bC(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...te(e)})}function SC(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...te(e)})}function EC(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...te(e)})}function CC(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...te(e)})}function xC(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...te(e)})}function TC(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...te(e)})}function MC(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...te(e)})}function AC(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...te(e)})}function _C(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...te(e)})}function IC(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...te(e)})}function BC(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...te(e)})}function NC(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...te(e)})}function PC(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...te(e)})}function DC(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...te(e)})}function OC(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...te(e)})}function RC(t,e){return new t({type:"string",format:"date",check:"string_format",...te(e)})}function zC(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...te(e)})}function $C(t,e){return new t({type:"string",format:"duration",check:"string_format",...te(e)})}function LC(t,e){return new t({type:"number",checks:[],...te(e)})}function VC(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...te(e)})}function FC(t,e){return new t({type:"boolean",...te(e)})}function WC(t){return new t({type:"unknown"})}function UC(t,e){return new t({type:"never",...te(e)})}function Sp(t,e){return new op({check:"less_than",...te(e),value:t,inclusive:!1})}function Jc(t,e){return new op({check:"less_than",...te(e),value:t,inclusive:!0})}function Ep(t,e){return new sp({check:"greater_than",...te(e),value:t,inclusive:!1})}function Qc(t,e){return new sp({check:"greater_than",...te(e),value:t,inclusive:!0})}function Cp(t,e){return new oE({check:"multiple_of",...te(e),value:t})}function xp(t,e){return new iE({check:"max_length",...te(e),maximum:t})}function Ma(t,e){return new aE({check:"min_length",...te(e),minimum:t})}function Tp(t,e){return new lE({check:"length_equals",...te(e),length:t})}function HC(t,e){return new cE({check:"string_format",format:"regex",...te(e),pattern:t})}function jC(t){return new uE({check:"string_format",format:"lowercase",...te(t)})}function ZC(t){return new dE({check:"string_format",format:"uppercase",...te(t)})}function KC(t,e){return new fE({check:"string_format",format:"includes",...te(e),includes:t})}function YC(t,e){return new hE({check:"string_format",format:"starts_with",...te(e),prefix:t})}function qC(t,e){return new pE({check:"string_format",format:"ends_with",...te(e),suffix:t})}function ks(t){return new mE({check:"overwrite",tx:t})}function XC(t){return ks(e=>e.normalize(t))}function GC(){return ks(t=>t.trim())}function JC(){return ks(t=>t.toLowerCase())}function QC(){return ks(t=>t.toUpperCase())}function ex(){return ks(t=>cS(t))}function tx(t,e,n){return new t({type:"array",element:e,...te(n)})}function nx(t,e,n){const r=te(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function rx(t,e,n){return new t({type:"custom",check:"custom",fn:e,...te(n)})}function ox(t){const e=sx(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(li(r,n.value,e._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(li(o))}},t(n.value,n)));return e}function sx(t,e){const n=new Yt({check:"custom",...te(e)});return n._zod.check=t,n}function Mp(t){let e=(t==null?void 0:t.target)??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:(t==null?void 0:t.metadata)??ci,target:e,unrepresentable:(t==null?void 0:t.unrepresentable)??"throw",override:(t==null?void 0:t.override)??(()=>{}),io:(t==null?void 0:t.io)??"output",counter:0,seen:new Map,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0}}function Ke(t,e,n={path:[],schemaPath:[]}){var u,f;var r;const o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,i);const a=(f=(u=t._zod).toJSONSchema)==null?void 0:f.call(u);if(a)i.schema=a;else{const h={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,h);else{const m=i.schema,g=e.processors[o.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);g(t,e,m,h)}const p=t._zod.parent;p&&(i.ref||(i.ref=p),Ke(p,e,h),e.seen.get(p).isParent=!0)}const l=e.metadataRegistry.get(t);return l&&Object.assign(i.schema,l),e.io==="input"&&$t(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Ap(t,e){var i,a,l,c;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of t.seen.entries()){const f=(i=t.metadataRegistry.get(u[0]))==null?void 0:i.id;if(f){const h=r.get(f);if(h&&h!==u[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(f,u[0])}}const o=u=>{var g;const f=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const y=(g=t.external.registry.get(u[0]))==null?void 0:g.id,w=t.external.uri??(b=>b);if(y)return{ref:w(y)};const k=u[1].defId??u[1].schema.id??`schema${t.counter++}`;return u[1].defId=k,{defId:k,ref:`${w("__shared")}#/${f}/${k}`}}if(u[1]===n)return{ref:"#"};const p=`#/${f}/`,m=u[1].schema.id??`__schema${t.counter++}`;return{defId:m,ref:p+m}},s=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:h,defId:p}=o(u);f.def={...f.schema},p&&(f.defId=p);const m=f.schema;for(const g in m)delete m[g];m.$ref=h};if(t.cycles==="throw")for(const u of t.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${(a=f.cycle)==null?void 0:a.join("/")}/<root>
38
38
 
39
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of t.seen.entries()){const d=u[1];if(e===u[0]){s(u);continue}if(t.external){const p=(l=t.external.registry.get(u[0]))==null?void 0:l.id;if(e!==u[0]&&p){s(u);continue}}if((c=t.metadataRegistry.get(u[0]))==null?void 0:c.id){s(u);continue}if(d.cycle){s(u);continue}if(d.count>1&&t.reused==="ref"){s(u);continue}}}function yp(t,e){var i,a,l;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=c=>{const u=t.seen.get(c);if(u.ref===null)return;const d=u.def??u.schema,h={...d},p=u.ref;if(u.ref=null,p){r(p);const g=t.seen.get(p),y=g.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(y)):Object.assign(d,y),Object.assign(d,h),c._zod.parent===p)for(const k in d)k==="$ref"||k==="allOf"||k in h||delete d[k];if(y.$ref&&g.def)for(const k in d)k==="$ref"||k==="allOf"||k in g.def&&JSON.stringify(d[k])===JSON.stringify(g.def[k])&&delete d[k]}const m=c._zod.parent;if(m&&m!==p){r(m);const g=t.seen.get(m);if(g!=null&&g.schema.$ref&&(d.$ref=g.schema.$ref,g.def))for(const y in d)y==="$ref"||y==="allOf"||y in g.def&&JSON.stringify(d[y])===JSON.stringify(g.def[y])&&delete d[y]}t.override({zodSchema:c,jsonSchema:d,path:u.path??[]})};for(const c of[...t.seen.entries()].reverse())r(c[0]);const o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,(i=t.external)!=null&&i.uri){const c=(a=t.external.registry.get(e))==null?void 0:a.id;if(!c)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(c)}Object.assign(o,n.def??n.schema);const s=((l=t.external)==null?void 0:l.defs)??{};for(const c of t.seen.entries()){const u=c[1];u.def&&u.defId&&(s[u.defId]=u.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...e["~standard"],jsonSchema:{input:Sa(e,"input",t.processors),output:Sa(e,"output",t.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function $t(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return $t(r.element,n);if(r.type==="set")return $t(r.valueType,n);if(r.type==="lazy")return $t(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return $t(r.innerType,n);if(r.type==="intersection")return $t(r.left,n)||$t(r.right,n);if(r.type==="record"||r.type==="map")return $t(r.keyType,n)||$t(r.valueType,n);if(r.type==="pipe")return $t(r.in,n)||$t(r.out,n);if(r.type==="object"){for(const o in r.shape)if($t(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if($t(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if($t(o,n))return!0;return!!(r.rest&&$t(r.rest,n))}return!1}const XC=(t,e={})=>n=>{const r=mp({...n,processors:e});return je(t,r),gp(r,t),yp(r,t)},Sa=(t,e,n={})=>r=>{const{libraryOptions:o,target:s}=r??{},i=mp({...o??{},target:s,io:e,processors:n});return je(t,i),gp(i,t),yp(i,t)},GC={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},QC=(t,e,n,r)=>{const o=n;o.type="string";const{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:c}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=GC[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){const u=[...l];u.length===1?o.pattern=u[0].source:u.length>1&&(o.allOf=[...u.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},ex=(t,e,n,r)=>{const o=n,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number",typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u),typeof s=="number"&&(o.minimum=s,typeof u=="number"&&e.target!=="draft-04"&&(u>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof c=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c),typeof i=="number"&&(o.maximum=i,typeof c=="number"&&e.target!=="draft-04"&&(c<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},tx=(t,e,n,r)=>{n.type="boolean"},nx=(t,e,n,r)=>{n.not={}},rx=(t,e,n,r)=>{},ox=(t,e,n,r)=>{const o=t._zod.def,s=Bh(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},sx=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},ix=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},ax=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},lx=(t,e,n,r)=>{const o=n,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=je(s.element,e,{...r,path:[...r.path,"items"]})},cx=(t,e,n,r)=>{var c;const o=n,s=t._zod.def;o.type="object",o.properties={};const i=s.shape;for(const u in i)o.properties[u]=je(i[u],e,{...r,path:[...r.path,"properties",u]});const a=new Set(Object.keys(i)),l=new Set([...a].filter(u=>{const d=s.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));l.size>0&&(o.required=Array.from(l)),((c=s.catchall)==null?void 0:c._zod.def.type)==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=je(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},ux=(t,e,n,r)=>{const o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,l)=>je(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",l]}));s?n.oneOf=i:n.anyOf=i},dx=(t,e,n,r)=>{const o=t._zod.def,s=je(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=je(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=l},fx=(t,e,n,r)=>{const o=n,s=t._zod.def;o.type="array";const i=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((h,p)=>je(h,e,{...r,path:[...r.path,i,p]})),c=s.rest?je(s.rest,e,{...r,path:[...r.path,a,...e.target==="openapi-3.0"?[s.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=l,c&&(o.items=c)):e.target==="openapi-3.0"?(o.items={anyOf:l},c&&o.items.anyOf.push(c),o.minItems=l.length,c||(o.maxItems=l.length)):(o.items=l,c&&(o.additionalItems=c));const{minimum:u,maximum:d}=t._zod.bag;typeof u=="number"&&(o.minItems=u),typeof d=="number"&&(o.maxItems=d)},hx=(t,e,n,r)=>{const o=n,s=t._zod.def;o.type="object";const i=s.keyType,a=i._zod.bag,l=a==null?void 0:a.patterns;if(s.mode==="loose"&&l&&l.size>0){const u=je(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const d of l)o.patternProperties[d.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=je(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=je(s.valueType,e,{...r,path:[...r.path,"additionalProperties"]});const c=i._zod.values;if(c){const u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(o.required=u)}},px=(t,e,n,r)=>{const o=t._zod.def,s=je(o.innerType,e,r),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},mx=(t,e,n,r)=>{const o=t._zod.def;je(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},gx=(t,e,n,r)=>{const o=t._zod.def;je(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},yx=(t,e,n,r)=>{const o=t._zod.def;je(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},wx=(t,e,n,r)=>{const o=t._zod.def;je(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},kx=(t,e,n,r)=>{const o=t._zod.def,s=e.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;je(s,e,r);const i=e.seen.get(t);i.ref=s},vx=(t,e,n,r)=>{const o=t._zod.def;je(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0},wp=(t,e,n,r)=>{const o=t._zod.def;je(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},bx=I("ZodISODateTime",(t,e)=>{vE.init(t,e),We.init(t,e)});function Sx(t){return TC(bx,t)}const Ex=I("ZodISODate",(t,e)=>{bE.init(t,e),We.init(t,e)});function Cx(t){return MC(Ex,t)}const xx=I("ZodISOTime",(t,e)=>{SE.init(t,e),We.init(t,e)});function Tx(t){return _C(xx,t)}const Mx=I("ZodISODuration",(t,e)=>{EE.init(t,e),We.init(t,e)});function _x(t){return AC(Mx,t)}const hn=I("ZodError",(t,e)=>{zh.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>hS(t,n)},flatten:{value:n=>fS(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Oc,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Oc,2)}},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),Ax=ha(hn),Ix=pa(hn),Bx=ma(hn),Px=ga(hn),Nx=gS(hn),Dx=yS(hn),Ox=wS(hn),Rx=kS(hn),zx=vS(hn),$x=bS(hn),Lx=SS(hn),Fx=ES(hn),Ve=I("ZodType",(t,e)=>(De.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Sa(t,"input"),output:Sa(t,"output")}}),t.toJSONSchema=XC(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(Wr(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),t.with=t.check,t.clone=(n,r)=>Ur(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>Ax(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Bx(t,n,r),t.parseAsync=async(n,r)=>Ix(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Px(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Nx(t,n,r),t.decode=(n,r)=>Dx(t,n,r),t.encodeAsync=async(n,r)=>Ox(t,n,r),t.decodeAsync=async(n,r)=>Rx(t,n,r),t.safeEncode=(n,r)=>zx(t,n,r),t.safeDecode=(n,r)=>$x(t,n,r),t.safeEncodeAsync=async(n,r)=>Lx(t,n,r),t.safeDecodeAsync=async(n,r)=>Fx(t,n,r),t.refine=(n,r)=>t.check(RT(n,r)),t.superRefine=n=>t.check(zT(n)),t.overwrite=n=>t.check(ps(n)),t.optional=()=>Cp(t),t.exactOptional=()=>ST(t),t.nullable=()=>xp(t),t.nullish=()=>Cp(xp(t)),t.nonoptional=n=>_T(t,n),t.array=()=>pn(t),t.or=n=>hT([t,n]),t.and=n=>mT(t,n),t.transform=n=>Mp(t,vT(n)),t.default=n=>xT(t,n),t.prefault=n=>MT(t,n),t.catch=n=>IT(t,n),t.pipe=n=>Mp(t,n),t.readonly=()=>NT(t),t.describe=n=>{const r=t.clone();return Qs.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=Qs.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Qs.get(t);const r=t.clone();return Qs.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),kp=I("_ZodString",(t,e)=>{Fc.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(r,o,s)=>QC(t,r,o);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(OC(...r)),t.includes=(...r)=>t.check($C(...r)),t.startsWith=(...r)=>t.check(LC(...r)),t.endsWith=(...r)=>t.check(FC(...r)),t.min=(...r)=>t.check(ba(...r)),t.max=(...r)=>t.check(hp(...r)),t.length=(...r)=>t.check(pp(...r)),t.nonempty=(...r)=>t.check(ba(1,...r)),t.lowercase=r=>t.check(RC(r)),t.uppercase=r=>t.check(zC(r)),t.trim=()=>t.check(WC()),t.normalize=(...r)=>t.check(VC(...r)),t.toLowerCase=()=>t.check(UC()),t.toUpperCase=()=>t.check(HC()),t.slugify=()=>t.check(jC())}),Vx=I("ZodString",(t,e)=>{Fc.init(t,e),kp.init(t,e),t.email=n=>t.check(sC(Wx,n)),t.url=n=>t.check(uC(Ux,n)),t.jwt=n=>t.check(xC(oT,n)),t.emoji=n=>t.check(dC(Hx,n)),t.guid=n=>t.check(cp(vp,n)),t.uuid=n=>t.check(iC(Ea,n)),t.uuidv4=n=>t.check(aC(Ea,n)),t.uuidv6=n=>t.check(lC(Ea,n)),t.uuidv7=n=>t.check(cC(Ea,n)),t.nanoid=n=>t.check(fC(jx,n)),t.guid=n=>t.check(cp(vp,n)),t.cuid=n=>t.check(hC(Zx,n)),t.cuid2=n=>t.check(pC(Kx,n)),t.ulid=n=>t.check(mC(Yx,n)),t.base64=n=>t.check(SC(tT,n)),t.base64url=n=>t.check(EC(nT,n)),t.xid=n=>t.check(gC(qx,n)),t.ksuid=n=>t.check(yC(Jx,n)),t.ipv4=n=>t.check(wC(Xx,n)),t.ipv6=n=>t.check(kC(Gx,n)),t.cidrv4=n=>t.check(vC(Qx,n)),t.cidrv6=n=>t.check(bC(eT,n)),t.e164=n=>t.check(CC(rT,n)),t.datetime=n=>t.check(Sx(n)),t.date=n=>t.check(Cx(n)),t.time=n=>t.check(Tx(n)),t.duration=n=>t.check(_x(n))});function ct(t){return oC(Vx,t)}const We=I("ZodStringFormat",(t,e)=>{Fe.init(t,e),kp.init(t,e)}),Wx=I("ZodEmail",(t,e)=>{dE.init(t,e),We.init(t,e)}),vp=I("ZodGUID",(t,e)=>{cE.init(t,e),We.init(t,e)}),Ea=I("ZodUUID",(t,e)=>{uE.init(t,e),We.init(t,e)}),Ux=I("ZodURL",(t,e)=>{fE.init(t,e),We.init(t,e)}),Hx=I("ZodEmoji",(t,e)=>{hE.init(t,e),We.init(t,e)}),jx=I("ZodNanoID",(t,e)=>{pE.init(t,e),We.init(t,e)}),Zx=I("ZodCUID",(t,e)=>{mE.init(t,e),We.init(t,e)}),Kx=I("ZodCUID2",(t,e)=>{gE.init(t,e),We.init(t,e)}),Yx=I("ZodULID",(t,e)=>{yE.init(t,e),We.init(t,e)}),qx=I("ZodXID",(t,e)=>{wE.init(t,e),We.init(t,e)}),Jx=I("ZodKSUID",(t,e)=>{kE.init(t,e),We.init(t,e)}),Xx=I("ZodIPv4",(t,e)=>{CE.init(t,e),We.init(t,e)}),Gx=I("ZodIPv6",(t,e)=>{xE.init(t,e),We.init(t,e)}),Qx=I("ZodCIDRv4",(t,e)=>{TE.init(t,e),We.init(t,e)}),eT=I("ZodCIDRv6",(t,e)=>{ME.init(t,e),We.init(t,e)}),tT=I("ZodBase64",(t,e)=>{_E.init(t,e),We.init(t,e)}),nT=I("ZodBase64URL",(t,e)=>{IE.init(t,e),We.init(t,e)}),rT=I("ZodE164",(t,e)=>{BE.init(t,e),We.init(t,e)}),oT=I("ZodJWT",(t,e)=>{NE.init(t,e),We.init(t,e)}),bp=I("ZodNumber",(t,e)=>{qh.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(r,o,s)=>ex(t,r,o),t.gt=(r,o)=>t.check(dp(r,o)),t.gte=(r,o)=>t.check(Uc(r,o)),t.min=(r,o)=>t.check(Uc(r,o)),t.lt=(r,o)=>t.check(up(r,o)),t.lte=(r,o)=>t.check(Wc(r,o)),t.max=(r,o)=>t.check(Wc(r,o)),t.int=r=>t.check(Sp(r)),t.safe=r=>t.check(Sp(r)),t.positive=r=>t.check(dp(0,r)),t.nonnegative=r=>t.check(Uc(0,r)),t.negative=r=>t.check(up(0,r)),t.nonpositive=r=>t.check(Wc(0,r)),t.multipleOf=(r,o)=>t.check(fp(r,o)),t.step=(r,o)=>t.check(fp(r,o)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Xe(t){return IC(bp,t)}const sT=I("ZodNumberFormat",(t,e)=>{DE.init(t,e),bp.init(t,e)});function Sp(t){return BC(sT,t)}const iT=I("ZodBoolean",(t,e)=>{OE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tx(t,n,r)});function Lt(t){return PC(iT,t)}const aT=I("ZodUnknown",(t,e)=>{RE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>rx()});function Ca(){return NC(aT)}const lT=I("ZodNever",(t,e)=>{zE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>nx(t,n,r)});function cT(t){return DC(lT,t)}const uT=I("ZodArray",(t,e)=>{$E.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>lx(t,n,r,o),t.element=e.element,t.min=(n,r)=>t.check(ba(n,r)),t.nonempty=n=>t.check(ba(1,n)),t.max=(n,r)=>t.check(hp(n,r)),t.length=(n,r)=>t.check(pp(n,r)),t.unwrap=()=>t.element});function pn(t,e){return ZC(uT,t,e)}const dT=I("ZodObject",(t,e)=>{FE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cx(t,n,r,o),Ee(t,"shape",()=>e.shape),t.keyof=()=>jc(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ca()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ca()}),t.strict=()=>t.clone({...t._zod.def,catchall:cT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>aS(t,n),t.safeExtend=n=>lS(t,n),t.merge=n=>cS(t,n),t.pick=n=>sS(t,n),t.omit=n=>iS(t,n),t.partial=(...n)=>uS(Ep,t,n[0]),t.required=(...n)=>dS(Tp,t,n[0])});function qt(t,e){const n={type:"object",shape:t??{},...ee(e)};return new dT(n)}const fT=I("ZodUnion",(t,e)=>{VE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ux(t,n,r,o),t.options=e.options});function hT(t,e){return new fT({type:"union",options:t,...ee(e)})}const pT=I("ZodIntersection",(t,e)=>{WE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>dx(t,n,r,o)});function mT(t,e){return new pT({type:"intersection",left:t,right:e})}const gT=I("ZodTuple",(t,e)=>{tp.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fx(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function xa(t,e,n){const r=e instanceof De,o=r?n:e,s=r?e:null;return new gT({type:"tuple",items:t,rest:s,...ee(o)})}const yT=I("ZodRecord",(t,e)=>{UE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hx(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function wT(t,e,n){return new yT({type:"record",keyType:t,valueType:e,...ee(n)})}const Hc=I("ZodEnum",(t,e)=>{HE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(r,o,s)=>ox(t,r,o),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{const s={};for(const i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Hc({...e,checks:[],...ee(o),entries:s})},t.exclude=(r,o)=>{const s={...e.entries};for(const i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Hc({...e,checks:[],...ee(o),entries:s})}});function jc(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Hc({type:"enum",entries:n,...ee(e)})}const kT=I("ZodTransform",(t,e)=>{jE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ax(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ah(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Gs(s,n.value,e));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(Gs(i))}};const o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function vT(t){return new kT({type:"transform",transform:t})}const Ep=I("ZodOptional",(t,e)=>{rp.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wp(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Cp(t){return new Ep({type:"optional",innerType:t})}const bT=I("ZodExactOptional",(t,e)=>{ZE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wp(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function ST(t){return new bT({type:"optional",innerType:t})}const ET=I("ZodNullable",(t,e)=>{KE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>px(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function xp(t){return new ET({type:"nullable",innerType:t})}const CT=I("ZodDefault",(t,e)=>{YE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function xT(t,e){return new CT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Oh(e)}})}const TT=I("ZodPrefault",(t,e)=>{qE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function MT(t,e){return new TT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Oh(e)}})}const Tp=I("ZodNonOptional",(t,e)=>{JE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function _T(t,e){return new Tp({type:"nonoptional",innerType:t,...ee(e)})}const AT=I("ZodCatch",(t,e)=>{XE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function IT(t,e){return new AT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const BT=I("ZodPipe",(t,e)=>{GE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>kx(t,n,r,o),t.in=e.in,t.out=e.out});function Mp(t,e){return new BT({type:"pipe",in:t,out:e})}const PT=I("ZodReadonly",(t,e)=>{QE.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function NT(t){return new PT({type:"readonly",innerType:t})}const DT=I("ZodFunction",(t,e)=>{eC.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ix(t,n)});function OT(t){return new DT({type:"function",input:Array.isArray(t==null?void 0:t.input)?xa(t==null?void 0:t.input):(t==null?void 0:t.input)??pn(Ca()),output:(t==null?void 0:t.output)??Ca()})}const _p=I("ZodCustom",(t,e)=>{tC.init(t,e),Ve.init(t,e),t._zod.processJSONSchema=(n,r,o)=>sx(t,n)});function mn(t,e){return KC(_p,()=>!0,e)}function RT(t,e={}){return YC(_p,t,e)}function zT(t){return qC(t)}function $T(t){const e=LT(t.chars),n=FT(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=VT(r,e.length);return{chars:t.chars,byChar:e.byChar,byCode:e.byCode,length:e.length,first:e.byCode[0],last:e.byCode[e.length-1],firstPositive:n.firstPositive,mostPositive:n.mostPositive,firstNegative:n.firstNegative,mostNegative:n.mostNegative,jitterRange:r,paddingDict:o}}function LT(t){const e={},n={},r=t.length;for(let o=0;o<r;o++){const s=t[o];e[o]=s,n[s]=o}return{byCode:e,byChar:n,length:r}}function FT(t,e,n,r){const o=t.byChar[e],s=t.byChar[n],i=t.byChar[r];if(o===void 0||s===void 0||i===void 0)throw new Error("invalid charSet");if(s-o<3)throw new Error("mostPositive must be at least 3 characters away from neutral");if(o-i<3)throw new Error("mostNegative must be at least 3 characters away from neutral");return{firstPositive:t.byCode[o],mostPositive:t.byCode[s],firstNegative:t.byCode[o-1],mostNegative:t.byCode[i]}}function VT(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var Zc=null;function Ap(){return Zc||(Zc=$T({chars:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",firstPositive:"a",mostPositive:"z",mostNegative:"A"}))}function jr(t,e,n){const r=n.byChar[t],o=n.byChar[e];return Math.abs(r-o)}function Kc(t,e){const n=t[0];if(n>e.mostPositive||n<e.mostNegative)throw new Error("invalid firstChar on key");return n===e.mostPositive?jr(n,e.firstPositive,e)+1+Ta(t.slice(1),"positive",e):n===e.mostNegative?jr(n,e.firstNegative,e)+1+Ta(t.slice(1),"negative",e):n>=e.firstPositive?jr(n,e.firstPositive,e)+2:jr(n,e.firstNegative,e)+2}function Ta(t,e,n){const r=t[0];if(r>n.mostPositive||r<n.mostNegative)throw new Error("invalid firstChar on key");return r===n.mostPositive&&e==="positive"?jr(r,n.mostNegative,n)+1+Ta(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?jr(r,n.mostPositive,n)+1+Ta(t.slice(1),e,n):e==="positive"?jr(r,n.mostNegative,n)+2:jr(r,n.mostPositive,n)+2}function Ma(t,e,n,r,o){const s=Math.max(t.length,e.length);return n==="start"?[t.padStart(s,r),e.padStart(s,r)]:[t.padEnd(s,r),e.padEnd(s,r)]}function WT(t,e,n){let[r,o]=Ma(t,e,"end",n.first),s=Yc(r,o,n);s===1&&(r=r.padEnd(r.length+1,n.first),s=n.length);const i=Pp(Math.floor(s/2),n);return qc(r,i,n)}function Yc(t,e,n){const[r,o]=Ma(t,e,"end",n.first).sort(),s=Ip(o,r,n);return UT(s,n)}function qc(t,e,n){const r=n.length,[o,s]=Ma(t,e,"start",n.first),i=[];let a=0;for(let l=o.length-1;l>=0;l--){const c=n.byChar[o[l]],u=n.byChar[s[l]],d=c+u+a;a=Math.floor(d/r);const h=d%r;i.unshift(n.byCode[h])}return a>0&&i.unshift(n.byCode[a]),i.join("")}function Ip(t,e,n,r=!0){const o=n.length,[s,i]=Ma(t,e,"start",n.first),a=[];let l=0;for(let c=s.length-1;c>=0;c--){let u=n.byChar[s[c]];const d=n.byChar[i[c]]+l;u<d?(l=1,u+=o):l=0;const h=u-d;a.unshift(n.byCode[h])}if(l>0)throw new Error("Subtraction result is negative. Ensure a is greater than or equal to b.");for(;r&&a.length>1&&a[0]===n.first;)a.shift();return a.join("")}function Bp(t,e){return qc(t,e.byCode[1],e)}function Jc(t,e){return Ip(t,e.byCode[1],e,!1)}function Pp(t,e){if(t===0)return e.byCode[0];let n="";const r=e.length;for(;t>0;)n=e.byCode[t%r]+n,t=Math.floor(t/r);return n}function UT(t,e){let n=0;const r=t.length,o=e.length;for(let s=0;s<r;s++)n+=e.byChar[t[s]]*Math.pow(o,r-s-1);return n}function HT(t){return t.firstPositive+t.byCode[0]}function jT(t,e){return Kc(t,e)===t.length}function Np(t,e){_a(t,e)}function _a(t,e){const n=Rp(t,e),r=Kc(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function Dp(t,e){if(!jT(t,e))throw new Error("invalid integer length: "+t)}function Op(t,e){Dp(t,e);const[n,r]=zp(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=Bp(r,e);return n+i}const s=KT(n,e);return $p(s,"lower",e)}function ZT(t,e){Dp(t,e);const[n,r]=zp(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=Jc(r,e);return n+i}const s=YT(n,e);return $p(s,"upper",e)}function Rp(t,e){let n=0;if(t[0]===e.mostPositive)for(;t[n]===e.mostPositive;)n=n+1;if(t[0]===e.mostNegative)for(;t[n]===e.mostNegative;)n=n+1;return t.slice(0,n+1)}function zp(t,e){const n=Rp(t,e),r=t.slice(n.length);return[n,r]}function KT(t,e){const n=t>=e.firstPositive,r=Bp(t,e),o=t[t.length-1]===e.mostPositive,s=r[r.length-1]===e.mostPositive;return n&&s?r+e.mostNegative:!n&&o?t.slice(0,t.length-1):r}function YT(t,e){const n=t>=e.firstPositive,r=t[t.length-1]===e.mostNegative;if(n&&r){const o=t.slice(0,t.length-1);return Jc(o,e)}return!n&&r?t+e.mostPositive:Jc(t,e)}function $p(t,e,n){const r=Kc(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function Lp(t,e){const n=Pp(Math.floor(Math.random()*e.jitterRange),e);return qc(t,n,e)}function qT(t,e,n){const r=t.padEnd(t.length+e,n.first);return Lp(r,n)}function JT(t,e,n){const r=_a(t,n),o=Op(r,n);let s=0;if(e!==null){const a=Yc(t,e,n);a<n.jitterRange+1&&(s=Math.max(s,Fp(a,n)))}const i=Yc(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,Fp(i,n))),s}function Fp(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function XT(t,e,n=Ap()){if(t!==null&&Np(t,n),e!==null&&Np(e,n),t===null&&e===null)return HT(n);if(t===null){const r=_a(e,n);return ZT(r,n)}if(e===null){const r=_a(t,n);return Op(r,n)}if(t>=e)throw new Error(t+" >= "+e);return WT(t,e,n)}function Aa(t,e,n=Ap()){const r=XT(t,e,n),o=JT(r,e,n);return o?qT(r,o,n):Lp(r,n)}function GT(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function QT(){const t=GT();if(t.__xstate__)return t.__xstate__}const eM=t=>{if(typeof window>"u")return;const e=QT();e&&e.register(t)};class Vp{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(e){const n={value:e,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const e=this._current;this._process(e.value),this._current=e.next}this._last=null}}const Wp=".",tM="",Up="",nM="#",rM="*",Hp="xstate.init",oM="xstate.error",Xc="xstate.stop";function sM(t,e){return{type:`xstate.after.${t}.${e}`}}function Gc(t,e){return{type:`xstate.done.state.${t}`,output:e}}function iM(t,e){return{type:`xstate.done.actor.${t}`,output:e,actorId:t}}function jp(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function Zp(t){return{type:Hp,input:t}}function Qn(t){setTimeout(()=>{throw t})}const aM=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Kp(t,e){const n=Yp(t),r=Yp(e);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(o=>o in r?Kp(n[o],r[o]):!1)}function Qc(t){if(Xp(t))return t;const e=[];let n="";for(let r=0;r<t.length;r++){switch(t.charCodeAt(r)){case 92:n+=t[r+1],r++;continue;case 46:e.push(n),n="";continue}n+=t[r]}return e.push(n),e}function Yp(t){if(WM(t))return t.value;if(typeof t!="string")return t;const e=Qc(t);return lM(e)}function lM(t){if(t.length===1)return t[0];const e={};let n=e;for(let r=0;r<t.length-1;r++)if(r===t.length-2)n[t[r]]=t[r+1];else{const o=n;n={},o[t[r]]=n}return e}function qp(t,e){const n={},r=Object.keys(t);for(let o=0;o<r.length;o++){const s=r[o];n[s]=e(t[s],s,t,o)}return n}function Jp(t){return Xp(t)?t:[t]}function Zr(t){return t===void 0?[]:Jp(t)}function eu(t,e,n,r){return typeof t=="function"?t({context:e,event:n,self:r}):t}function Xp(t){return Array.isArray(t)}function cM(t){return t.type.startsWith("xstate.error.actor")}function ms(t){return Jp(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function Gp(t){if(!(t===void 0||t===tM))return Zr(t)}function tu(t,e,n){var s,i,a;const r=typeof t=="object",o=r?t:void 0;return{next:(s=r?t.next:t)==null?void 0:s.bind(o),error:(i=r?t.error:e)==null?void 0:i.bind(o),complete:(a=r?t.complete:n)==null?void 0:a.bind(o)}}function Qp(t,e){return`${e}.${t}`}function nu(t,e){const n=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return t.implementations.actors[e];const[,r,o]=n,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[r]:i).src}function uM(t,e){if(e===t||e===rM)return!0;if(!e.endsWith(".*"))return!1;const n=e.split("."),r=t.split(".");for(let o=0;o<n.length;o++){const s=n[o],i=r[o];if(s==="*")return o===n.length-1;if(s!==i)return!1}return!0}function em(t,e){return`${t.sessionId}.${e}`}let dM=0;function fM(t,e){const n=new Map,r=new Map,o=new WeakMap,s=new Set,i={},{clock:a,logger:l}=e,c={schedule:(h,p,m,g,y=Math.random().toString(36).slice(2))=>{const w={source:h,target:p,event:m,delay:g,id:y,startedAt:Date.now()},k=em(h,y);d._snapshot._scheduledEvents[k]=w;const b=a.setTimeout(()=>{delete i[k],delete d._snapshot._scheduledEvents[k],d._relay(h,p,m)},g);i[k]=b},cancel:(h,p)=>{const m=em(h,p),g=i[m];delete i[m],delete d._snapshot._scheduledEvents[m],g!==void 0&&a.clearTimeout(g)},cancelAll:h=>{for(const p in d._snapshot._scheduledEvents){const m=d._snapshot._scheduledEvents[p];m.source===h&&c.cancel(h,m.id)}}},u=h=>{if(!s.size)return;const p={...h,rootId:t.sessionId};s.forEach(m=>{var g;return(g=m.next)==null?void 0:g.call(m,p)})},d={_snapshot:{_scheduledEvents:((e==null?void 0:e.snapshot)&&e.snapshot.scheduler)??{}},_bookId:()=>`x:${dM++}`,_register:(h,p)=>(n.set(h,p),h),_unregister:h=>{n.delete(h.sessionId);const p=o.get(h);p!==void 0&&(r.delete(p),o.delete(h))},get:h=>r.get(h),getAll:()=>Object.fromEntries(r.entries()),_set:(h,p)=>{const m=r.get(h);if(m&&m!==p)throw new Error(`Actor with system ID '${h}' already exists.`);r.set(h,p),o.set(p,h)},inspect:h=>{const p=tu(h);return s.add(p),{unsubscribe(){s.delete(p)}}},_sendInspectionEvent:u,_relay:(h,p,m)=>{d._sendInspectionEvent({type:"@xstate.event",sourceRef:h,actorRef:p,event:m}),p._send(m)},scheduler:c,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{const h=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(const p in h){const{source:m,target:g,event:y,delay:w,id:k}=h[p];c.schedule(m,g,y,w,k)}},_clock:a,_logger:l};return d}let ru=!1;const ou=1;let Jt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const hM={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class pM{constructor(e,n){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Vp(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Jt.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const r={...hM,...n},{clock:o,logger:s,parent:i,syncSnapshot:a,id:l,systemId:c,inspect:u}=r;this.system=i?i.system:fM(this,{clock:o,logger:s}),u&&!i&&this.system.inspect(tu(u)),this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=(n==null?void 0:n.logger)??this.system._logger,this.clock=(n==null?void 0:n.clock)??this.system._clock,this._parent=i,this._syncSnapshot=a,this.options=r,this.src=r.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:d=>{this._deferred.push(d)},system:this.system,stopChild:d=>{if(d._parent!==this)throw new Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:d=>{const h=this.eventListeners.get(d.type),p=this.eventListeners.get("*");if(!h&&!p)return;const m=[...h?h.values():[],...p?p.values():[]];for(const g of m)try{g(d)}catch(y){Qn(y)}},actionExecutor:d=>{const h=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:d.type,params:d.params}}),!d.exec)return;const p=ru;try{ru=!0,d.exec(d.info,d.params)}finally{ru=p}};this._processingStatus===Jt.Running?h():this._deferred.push(h)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),c&&(this.systemId=c,this.system._set(c,this)),this._initState((n==null?void 0:n.snapshot)??(n==null?void 0:n.state)),c&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(e){var n;try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,(n=this.options)==null?void 0:n.input)}catch(r){this._snapshot={status:"error",output:void 0,error:r}}}update(e,n){var o,s;this._snapshot=e;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...e,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{(o=i.next)==null||o.call(i,e)}catch(a){Qn(a)}break;case"done":for(const i of this.observers)try{(s=i.next)==null||s.call(i,e)}catch(a){Qn(a)}this._stopProcedure(),this._complete(),this._doneEvent=iM(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:e})}subscribe(e,n,r){var s;const o=tu(e,n,r);if(this._processingStatus!==Jt.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{(s=o.complete)==null||s.call(o)}catch(i){Qn(i)}break;case"error":{const i=this._snapshot.error;if(!o.error)Qn(i);else try{o.error(i)}catch(a){Qn(a)}break}}return{unsubscribe:()=>{this.observers.delete(o)}}}on(e,n){let r=this.eventListeners.get(e);r||(r=new Set,this.eventListeners.set(e,r));const o=n.bind(void 0);return r.add(o),{unsubscribe:()=>{r.delete(o)}}}start(){if(this._processingStatus===Jt.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=Jt.Running;const e=Zp(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case"done":return this.update(this._snapshot,e),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let n,r;try{n=this.logic.transition(this._snapshot,e,this._actorScope)}catch(o){r={err:o}}if(r){const{err:o}=r;this._snapshot={...this._snapshot,status:"error",error:o},this._error(o);return}this.update(n,e),e.type===Xc&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Jt.Stopped?this:(this.mailbox.clear(),this._processingStatus===Jt.NotStarted?(this._processingStatus=Jt.Stopped,this):(this.mailbox.enqueue({type:Xc}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var e;for(const n of this.observers)try{(e=n.complete)==null||e.call(n)}catch(r){Qn(r)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||Qn(e),this.eventListeners.clear();return}let n=!1;for(const r of this.observers){const o=r.error;n||(n=!o);try{o==null||o(e)}catch(s){Qn(s)}}this.observers.clear(),this.eventListeners.clear(),n&&Qn(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,jp(this.id,e))}_stopProcedure(){return this._processingStatus!==Jt.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Vp(this._process.bind(this)),this._processingStatus=Jt.Stopped,this.system._unregister(this),this)}_send(e){this._processingStatus!==Jt.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}attachDevTools(){const{devTools:e}=this.options;e&&(typeof e=="function"?e:eM)(this)}toJSON(){return{xstate$$type:ou,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[aM](){return this}getSnapshot(){return this._snapshot}}function ei(t,...[e]){return new pM(t,e)}function mM(t,e,n,r,{sendId:o}){const s=typeof o=="function"?o(n,r):o;return[e,{sendId:s},void 0]}function gM(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function su(t){function e(n,r){}return e.type="xstate.cancel",e.sendId=t,e.resolve=mM,e.execute=gM,e}function yM(t,e,n,r,{id:o,systemId:s,src:i,input:a,syncSnapshot:l}){const c=typeof i=="string"?nu(e.machine,i):i,u=typeof o=="function"?o(n):o;let d,h;return c&&(h=typeof a=="function"?a({context:e.context,event:n.event,self:t.self}):a,d=ei(c,{id:u,src:i,parent:t.self,syncSnapshot:l,systemId:s,input:h})),[Mo(e,{children:{...e.children,[u]:d}}),{id:o,systemId:s,actorRef:d,src:i,input:h},void 0]}function wM(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==Jt.Stopped&&e.start()})}function iu(...[t,{id:e,systemId:n,input:r,syncSnapshot:o=!1}={}]){function s(i,a){}return s.type="xstate.spawnChild",s.id=e,s.systemId=n,s.src=t,s.input=r,s.syncSnapshot=o,s.resolve=yM,s.execute=wM,s}function kM(t,e,n,r,{actorRef:o}){const s=typeof o=="function"?o(n,r):o,i=typeof s=="string"?e.children[s]:s;let a=e.children;return i&&(a={...a},delete a[i.id]),[Mo(e,{children:a}),i,void 0]}function tm(t,e){const n=e.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))tm(t,r);t.system._unregister(e)}function vM(t,e){if(e){if(tm(t,e),e._processingStatus!==Jt.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function Ia(t){function e(n,r){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=kM,e.execute=vM,e}function bM(t,{context:e,event:n},{guards:r}){return!gs(r[0],e,n,t)}function Co(t){function e(n,r){return!1}return e.check=bM,e.guards=[t],e}function SM(t,{context:e,event:n},{guards:r}){return r.every(o=>gs(o,e,n,t))}function ti(t){function e(n,r){return!1}return e.check=SM,e.guards=t,e}function gs(t,e,n,r){const{machine:o}=r,s=typeof t=="function",i=s?t:o.implementations.guards[typeof t=="string"?t:t.type];if(!s&&!i)throw new Error(`Guard '${typeof t=="string"?t:t.type}' is not implemented.'.`);if(typeof i!="function")return gs(i,e,n,r);const a={context:e,event:n},l=s||typeof t=="string"?void 0:"params"in t?typeof t.params=="function"?t.params({context:e,event:n}):t.params:void 0;return"check"in i?i.check(r,a,i):i(a,l)}const au=t=>t.type==="atomic"||t.type==="final";function ys(t){return Object.values(t.states).filter(e=>e.type!=="history")}function ni(t,e){const n=[];if(e===t)return n;let r=t.parent;for(;r&&r!==e;)n.push(r),r=r.parent;return n}function Ba(t){const e=new Set(t),n=rm(e);for(const r of e)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))im(r).forEach(o=>e.add(o));else if(r.type==="parallel"){for(const o of ys(r))if(o.type!=="history"&&!e.has(o)){const s=im(o);for(const i of s)e.add(i)}}for(const r of e){let o=r.parent;for(;o;)e.add(o),o=o.parent}return e}function nm(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const o=n[0];if(o){if(au(o))return o.key}else return{}}const r={};for(const o of n)r[o.key]=nm(o,e);return r}function rm(t){const e=new Map;for(const n of t)e.has(n)||e.set(n,[]),n.parent&&(e.has(n.parent)||e.set(n.parent,[]),e.get(n.parent).push(n));return e}function om(t,e){const n=Ba(e);return nm(t,rm(n))}function lu(t,e){return e.type==="compound"?ys(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?ys(e).every(n=>lu(t,n)):e.type==="final"}const Pa=t=>t[0]===nM;function EM(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(r=>uM(e,r)).sort((r,o)=>o.length-r.length).flatMap(r=>t.transitions.get(r))}function CM(t){const e=t.config.after;if(!e)return[];const n=o=>{const s=sM(o,t.id),i=s.type;return t.entry.push(Ra(s,{id:i,delay:o})),t.exit.push(su(i)),i};return Object.keys(e).flatMap(o=>{const s=e[o],i=typeof s=="string"?{target:s}:s,a=Number.isNaN(+o)?o:+o,l=n(a);return Zr(i).map(c=>({...c,event:l,delay:a}))}).map(o=>{const{delay:s}=o;return{...xo(t,o.event,o),delay:s}})}function xo(t,e,n){const r=Gp(n.target),o=n.reenter??!1,s=MM(t,r),i={...n,actions:Zr(n.actions),guard:n.guard,target:s,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:s?s.map(a=>`#${a.id}`):void 0})};return i}function xM(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===Up)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=t.config.on[n];e.set(n,ms(r).map(o=>xo(t,n,o)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,ms(t.config.onDone).map(r=>xo(t,n,r)))}for(const n of t.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;e.set(r,ms(n.onDone).map(o=>xo(t,r,o)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;e.set(r,ms(n.onError).map(o=>xo(t,r,o)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;e.set(r,ms(n.onSnapshot).map(o=>xo(t,r,o)))}}for(const n of t.after){let r=e.get(n.eventType);r||(r=[],e.set(n.eventType,r)),r.push(n)}return e}function TM(t,e){const n=typeof e=="string"?t.states[e]:e?t.states[e.target]:void 0;if(!n&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const r={source:t,actions:!e||typeof e=="string"?[]:Zr(e.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${t.id}`,target:n?[`#${n.id}`]:[]})};return r}function MM(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if(Pa(n))return t.machine.getStateNodeById(n);const r=n[0]===Wp;if(r&&!t.parent)return Na(t,n.slice(1));const o=r?t.key+n:n;if(t.parent)try{return Na(t.parent,o)}catch(s){throw new Error(`Invalid transition definition for state node '${t.id}':
40
- ${s.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function sm(t){const e=Gp(t.config.target);return e?{target:e.map(n=>typeof n=="string"?Na(t.parent,n):n)}:t.parent.initial}function To(t){return t.type==="history"}function im(t){const e=am(t);for(const n of e)for(const r of ni(n,t))e.add(r);return e}function am(t){const e=new Set;function n(r){if(!e.has(r)){if(e.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const o of ys(r))n(o)}}return n(t),e}function ws(t,e){if(Pa(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function Na(t,e){if(typeof e=="string"&&Pa(e))try{return t.machine.getStateNodeById(e)}catch{}const n=Qc(e).slice();let r=t;for(;n.length;){const o=n.shift();if(!o.length)break;r=ws(r,o)}return r}function Da(t,e){if(typeof e=="string"){const o=t.states[e];if(!o)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,o]}const n=Object.keys(e),r=n.map(o=>ws(t,o)).filter(Boolean);return[t.machine.root,t].concat(r,n.reduce((o,s)=>{const i=ws(t,s);if(!i)return o;const a=Da(i,e[s]);return o.concat(a)},[]))}function _M(t,e,n,r){const s=ws(t,e).next(n,r);return!s||!s.length?t.next(n,r):s}function AM(t,e,n,r){const o=Object.keys(e),s=ws(t,o[0]),i=cu(s,e[o[0]],n,r);return!i||!i.length?t.next(n,r):i}function IM(t,e,n,r){const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)continue;const a=ws(t,s),l=cu(a,i,n,r);l&&o.push(...l)}return o.length?o:t.next(n,r)}function cu(t,e,n,r){return typeof e=="string"?_M(t,e,n,r):Object.keys(e).length===1?AM(t,e,n,r):IM(t,e,n,r)}function BM(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function Kr(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function PM(t,e){const n=new Set(t),r=new Set(e);for(const o of n)if(r.has(o))return!0;for(const o of r)if(n.has(o))return!0;return!1}function lm(t,e,n){const r=new Set;for(const o of t){let s=!1;const i=new Set;for(const a of r)if(PM(du([o],e,n),du([a],e,n)))if(Kr(o.source,a.source))i.add(a);else{s=!0;break}if(!s){for(const a of i)r.delete(a);r.add(o)}}return Array.from(r)}function NM(t){const[e,...n]=t;for(const r of ni(e,void 0))if(n.every(o=>Kr(o,r)))return r}function uu(t,e){if(!t.target)return[];const n=new Set;for(const r of t.target)if(To(r))if(e[r.id])for(const o of e[r.id])n.add(o);else for(const o of uu(sm(r),e))n.add(o);else n.add(r);return[...n]}function cm(t,e){const n=uu(t,e);if(!n)return;if(!t.reenter&&n.every(o=>o===t.source||Kr(o,t.source)))return t.source;const r=NM(n.concat(t.source));if(r)return r;if(!t.reenter)return t.source.machine.root}function du(t,e,n){var o;const r=new Set;for(const s of t)if((o=s.target)!=null&&o.length){const i=cm(s,n);s.reenter&&s.source===i&&r.add(i);for(const a of e)Kr(a,i)&&r.add(a)}return[...r]}function DM(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function fu(t,e,n,r,o,s){if(!t.length)return e;const i=new Set(e._nodes);let a=e.historyValue;const l=lm(t,i,a);let c=e;o||([c,a]=$M(c,r,n,l,i,a,s,n.actionExecutor)),c=vs(c,r,n,l.flatMap(d=>d.actions),s,void 0),c=RM(c,r,n,l,i,s,a,o);const u=[...i];c.status==="done"&&(c=vs(c,r,n,u.sort((d,h)=>h.order-d.order).flatMap(d=>d.exit),s,void 0));try{return a===e.historyValue&&DM(e._nodes,i)?c:Mo(c,{_nodes:u,historyValue:a})}catch(d){throw d}}function OM(t,e,n,r,o){if(r.output===void 0)return;const s=Gc(o.id,o.output!==void 0&&o.parent?eu(o.output,t.context,e,n.self):void 0);return eu(r.output,t.context,s,n.self)}function RM(t,e,n,r,o,s,i,a){let l=t;const c=new Set,u=new Set;zM(r,i,u,c),a&&u.add(t.machine.root);const d=new Set;for(const h of[...c].sort((p,m)=>p.order-m.order)){o.add(h);const p=[];p.push(...h.entry);for(const m of h.invoke)p.push(iu(m.src,{...m,syncSnapshot:!!m.onSnapshot}));if(u.has(h)){const m=h.initial.actions;p.push(...m)}if(l=vs(l,e,n,p,s,h.invoke.map(m=>m.id)),h.type==="final"){const m=h.parent;let g=(m==null?void 0:m.type)==="parallel"?m:m==null?void 0:m.parent,y=g||h;for((m==null?void 0:m.type)==="compound"&&s.push(Gc(m.id,h.output!==void 0?eu(h.output,l.context,e,n.self):void 0));(g==null?void 0:g.type)==="parallel"&&!d.has(g)&&lu(o,g);)d.add(g),s.push(Gc(g.id)),y=g,g=g.parent;if(g)continue;l=Mo(l,{status:"done",output:OM(l,e,n,l.machine.root,y)})}}return l}function zM(t,e,n,r){for(const o of t){const s=cm(o,e);for(const a of o.target||[])!To(a)&&(o.source!==a||o.source!==s||o.reenter)&&(r.add(a),n.add(a)),ks(a,e,n,r);const i=uu(o,e);for(const a of i){const l=ni(a,s);(s==null?void 0:s.type)==="parallel"&&l.push(s),um(r,e,n,l,!o.source.parent&&o.reenter?void 0:s)}}}function ks(t,e,n,r){var o;if(To(t))if(e[t.id]){const s=e[t.id];for(const i of s)r.add(i),ks(i,e,n,r);for(const i of s)hu(i,t.parent,r,e,n)}else{const s=sm(t);for(const i of s.target)r.add(i),s===((o=t.parent)==null?void 0:o.initial)&&n.add(t.parent),ks(i,e,n,r);for(const i of s.target)hu(i,t.parent,r,e,n)}else if(t.type==="compound"){const[s]=t.initial.target;To(s)||(r.add(s),n.add(s)),ks(s,e,n,r),hu(s,t,r,e,n)}else if(t.type==="parallel")for(const s of ys(t).filter(i=>!To(i)))[...r].some(i=>Kr(i,s))||(To(s)||(r.add(s),n.add(s)),ks(s,e,n,r))}function um(t,e,n,r,o){for(const s of r)if((!o||Kr(s,o))&&t.add(s),s.type==="parallel")for(const i of ys(s).filter(a=>!To(a)))[...t].some(a=>Kr(a,i))||(t.add(i),ks(i,e,n,t))}function hu(t,e,n,r,o){um(n,r,o,ni(t,e))}function $M(t,e,n,r,o,s,i,a){let l=t;const c=du(r,o,s);c.sort((d,h)=>h.order-d.order);let u;for(const d of c)for(const h of BM(d)){let p;h.history==="deep"?p=m=>au(m)&&Kr(m,d):p=m=>m.parent===d,u??(u={...s}),u[h.id]=Array.from(o).filter(p)}for(const d of c)l=vs(l,e,n,[...d.exit,...d.invoke.map(h=>Ia(h.id))],i,void 0),o.delete(d);return[l,u||s]}function LM(t,e){return t.implementations.actions[e]}function dm(t,e,n,r,o,s){const{machine:i}=t;let a=t;for(const l of r){const c=typeof l=="function",u=c?l:LM(i,typeof l=="string"?l:l.type),d={context:a.context,event:e,self:n.self,system:n.system},h=c||typeof l=="string"?void 0:"params"in l?typeof l.params=="function"?l.params({context:a.context,event:e}):l.params:void 0;if(!u||!("resolve"in u)){n.actionExecutor({type:typeof l=="string"?l:typeof l=="object"?l.type:l.name||"(anonymous)",info:d,params:h,exec:u});continue}const p=u,[m,g,y]=p.resolve(n,a,d,h,u,o);a=m,"retryResolve"in p&&(s==null||s.push([p,g])),"execute"in p&&n.actionExecutor({type:p.type,info:d,params:g,exec:p.execute.bind(null,n,g)}),y&&(a=dm(a,e,n,y,o,s))}return a}function vs(t,e,n,r,o,s){const i=s?[]:void 0,a=dm(t,e,n,r,{internalQueue:o,deferredActorIds:s},i);return i==null||i.forEach(([l,c])=>{l.retryResolve(n,a,c)}),a}function pu(t,e,n,r){let o=t;const s=[];function i(c,u,d){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:u,snapshot:c,_transitions:d}),s.push(c)}if(e.type===Xc)return o=Mo(fm(o,e,n),{status:"stopped"}),i(o,e,[]),{snapshot:o,microstates:s};let a=e;if(a.type!==Hp){const c=a,u=cM(c),d=hm(c,o);if(u&&!d.length)return o=Mo(t,{status:"error",error:c.error}),i(o,c,[]),{snapshot:o,microstates:s};o=fu(d,t,n,a,!1,r),i(o,c,d)}let l=!0;for(;o.status==="active";){let c=l?FM(o,a):[];const u=c.length?o:void 0;if(!c.length){if(!r.length)break;a=r.shift(),c=hm(a,o)}o=fu(c,o,n,a,!1,r),l=o!==u,i(o,a,c)}return o.status!=="active"&&fm(o,a,n),{snapshot:o,microstates:s}}function fm(t,e,n){return vs(t,e,n,Object.values(t.children).map(r=>Ia(r)),[],void 0)}function hm(t,e){return e.machine.getTransitionData(e,t)}function FM(t,e){const n=new Set,r=t._nodes.filter(au);for(const o of r)e:for(const s of[o].concat(ni(o,void 0)))if(s.always){for(const i of s.always)if(i.guard===void 0||gs(i.guard,t.context,e,t)){n.add(i);break e}}return lm(Array.from(n),new Set(t._nodes),t.historyValue)}function VM(t,e){const n=Ba(Da(t,e));return om(t,[...n])}function WM(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const UM=function(e){return Kp(e,this.value)},HM=function(e){return this.tags.has(e)},jM=function(e){const n=this.machine.getTransitionData(this,e);return!!(n!=null&&n.length)&&n.some(r=>r.target!==void 0||r.actions.length)},ZM=function(){const{_nodes:e,tags:n,machine:r,getMeta:o,toJSON:s,can:i,hasTag:a,matches:l,...c}=this;return{...c,tags:Array.from(n)}},KM=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function Oa(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:om(e.root,t._nodes),tags:new Set(t._nodes.flatMap(n=>n.tags)),children:t.children,historyValue:t.historyValue||{},matches:UM,hasTag:HM,can:jM,getMeta:KM,toJSON:ZM}}function Mo(t,e={}){return Oa({...t,...e},t.machine)}function YM(t){if(typeof t!="object"||t===null)return{};const e={};for(const n in t){const r=t[n];Array.isArray(r)&&(e[n]=r.map(o=>({id:o.id})))}return e}function qM(t,e){const{_nodes:n,tags:r,machine:o,children:s,context:i,can:a,hasTag:l,matches:c,getMeta:u,toJSON:d,...h}=t,p={};for(const g in s){const y=s[g];p[g]={snapshot:y.getPersistedSnapshot(e),src:y.src,systemId:y.systemId,syncSnapshot:y._syncSnapshot}}return{...h,context:pm(i),children:p,historyValue:YM(h.historyValue)}}function pm(t){let e;for(const n in t){const r=t[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)e??(e=Array.isArray(t)?t.slice():{...t}),e[n]={xstate$$type:ou,id:r.id};else{const o=pm(r);o!==r&&(e??(e=Array.isArray(t)?t.slice():{...t}),e[n]=o)}}return e??t}function JM(t,e,n,r,{event:o,id:s,delay:i},{internalQueue:a}){const l=e.machine.implementations.delays;if(typeof o=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const c=typeof o=="function"?o(n,r):o;let u;if(typeof i=="string"){const d=l&&l[i];u=typeof d=="function"?d(n,r):d}else u=typeof i=="function"?i(n,r):i;return typeof u!="number"&&a.push(c),[e,{event:c,id:s,delay:u},void 0]}function XM(t,e){const{event:n,delay:r,id:o}=e;if(typeof r=="number"){t.defer(()=>{const s=t.self;t.system.scheduler.schedule(s,s,n,r,o)});return}}function Ra(t,e){function n(r,o){}return n.type="xstate.raise",n.event=t,n.id=e==null?void 0:e.id,n.delay=e==null?void 0:e.delay,n.resolve=JM,n.execute=XM,n}function GM(t,{machine:e,context:n},r,o){const s=(i,a)=>{if(typeof i=="string"){const l=nu(e,i);if(!l)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=ei(l,{id:a==null?void 0:a.id,parent:t.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:n,event:r,self:t.self}):a==null?void 0:a.input,src:i,systemId:a==null?void 0:a.systemId});return o[c.id]=c,c}else return ei(i,{id:a==null?void 0:a.id,parent:t.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:i,systemId:a==null?void 0:a.systemId})};return(i,a)=>{const l=s(i,a);return o[l.id]=l,t.defer(()=>{l._processingStatus!==Jt.Stopped&&l.start()}),l}}function QM(t,e,n,r,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const s={},i={context:e.context,event:n.event,spawn:GM(t,e,n.event,s),self:t.self,system:t.system};let a={};if(typeof o=="function")a=o(i,r);else for(const c of Object.keys(o)){const u=o[c];a[c]=typeof u=="function"?u(i,r):u}const l=Object.assign({},e.context,a);return[Mo(e,{context:l,children:Object.keys(s).length?{...e.children,...s}:e.children}),void 0,void 0]}function Oe(t){function e(n,r){}return e.type="xstate.assign",e.assignment=t,e.resolve=QM,e}const mm=new WeakMap;function bs(t,e,n){let r=mm.get(t);return r?e in r||(r[e]=n()):(r={[e]:n()},mm.set(t,r)),r[e]}const e_={},ri=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class za{constructor(e,n){if(this.config=e,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Wp),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?qp(this.config.states,(r,o)=>new za(r,{_parent:this,_key:o,_machine:this.machine})):e_,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=Zr(this.config.entry).slice(),this.exit=Zr(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=Zr(e.tags).slice()}_initialize(){this.transitions=xM(this),this.config.always&&(this.always=ms(this.config.always).map(e=>xo(this,Up,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ri),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ri),eventType:null})}:void 0,history:this.history,states:qp(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(ri)})),entry:this.entry.map(ri),exit:this.exit.map(ri),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return bs(this,"invoke",()=>Zr(this.config.invoke).map((e,n)=>{const{src:r,systemId:o}=e,s=e.id??Qp(this.id,n),i=typeof r=="string"?r:`xstate.invoke.${Qp(this.id,n)}`;return{...e,src:i,id:s,systemId:o,toJSON(){const{onDone:a,onError:l,...c}=e;return{...c,type:"xstate.invoke",src:i,id:s}}}}))}get on(){return bs(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(o=>[n,o])).reduce((n,[r,o])=>(n[r]=n[r]||[],n[r].push(o),n),{}))}get after(){return bs(this,"delayedTransitions",()=>CM(this))}get initial(){return bs(this,"initial",()=>TM(this,this.config.initial))}next(e,n){const r=n.type,o=[];let s;const i=bs(this,`candidates-${r}`,()=>EM(this,r));for(const a of i){const{guard:l}=a,c=e.context;let u=!1;try{u=!l||gs(l,c,n,e)}catch(d){const h=typeof l=="string"?l:typeof l=="object"?l.type:void 0;throw new Error(`Unable to evaluate guard ${h?`'${h}' `:""}in transition for event '${r}' in state node '${this.id}':
41
- ${d.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get events(){return bs(this,"events",()=>{const{states:e}=this,n=new Set(this.ownEvents);if(e)for(const r of Object.keys(e)){const o=e[r];if(o.states)for(const s of o.events)n.add(`${s}`)}return Array.from(n)})}get ownEvents(){const e=Object.keys(Object.fromEntries(this.transitions)),n=new Set(e.filter(r=>this.transitions.get(r).some(o=>!(!o.target&&!o.actions.length&&!o.reenter))));return Array.from(n)}}const t_="#";class mu{constructor(e,n){this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=e.id||"(machine)",this.implementations={actors:(n==null?void 0:n.actors)??{},actions:(n==null?void 0:n.actions)??{},delays:(n==null?void 0:n.delays)??{},guards:(n==null?void 0:n.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new za(e,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(e){const{actions:n,guards:r,actors:o,delays:s}=this.implementations;return new mu(this.config,{actions:{...n,...e.actions},guards:{...r,...e.guards},actors:{...o,...e.actors},delays:{...s,...e.delays}})}resolveState(e){const n=VM(this.root,e.value),r=Ba(Da(this.root,n));return Oa({_nodes:[...r],context:e.context||{},children:{},status:lu(r,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,r){return pu(e,n,r,[]).snapshot}microstep(e,n,r){return pu(e,n,r,[]).microstates}getTransitionData(e,n){return cu(this.root,e.value,e,n)||[]}getPreInitialState(e,n,r){const{context:o}=this.config,s=Oa({context:typeof o!="function"&&o?o:{},_nodes:[this.root],children:{},status:"active"},this);return typeof o=="function"?vs(s,n,e,[Oe(({spawn:a,event:l,self:c})=>o({spawn:a,input:l.input,self:c}))],r,void 0):s}getInitialSnapshot(e,n){const r=Zp(n),o=[],s=this.getPreInitialState(e,r,o),i=fu([{target:[...am(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],s,e,r,!0,o),{snapshot:a}=pu(i,r,e,o);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=Qc(e),r=n.slice(1),o=Pa(n[0])?n[0].slice(t_.length):n[0],s=this.idMap.get(o);if(!s)throw new Error(`Child state node '#${o}' does not exist on machine '${this.id}'`);return Na(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,n){return qM(e,n)}restoreSnapshot(e,n){const r={},o=e.children;Object.keys(o).forEach(d=>{const h=o[d],p=h.snapshot,m=h.src,g=typeof m=="string"?nu(this,m):m;if(!g)return;const y=ei(g,{id:d,parent:n.self,syncSnapshot:h.syncSnapshot,snapshot:p,src:m,systemId:h.systemId});r[d]=y});function s(d,h){if(h instanceof za)return h;try{return d.machine.getStateNodeById(h.id)}catch{}}function i(d,h){if(!h||typeof h!="object")return{};const p={};for(const m in h){const g=h[m];for(const y of g){const w=s(d,y);w&&(p[m]??(p[m]=[]),p[m].push(w))}}return p}const a=i(this.root,e.historyValue),l=Oa({...e,children:r,_nodes:Array.from(Ba(Da(this.root,e.value))),historyValue:a},this),c=new Set;function u(d,h){if(!c.has(d)){c.add(d);for(const p in d){const m=d[p];if(m&&typeof m=="object"){if("xstate$$type"in m&&m.xstate$$type===ou){d[p]=h[m.id];continue}u(m,h)}}}}return u(l.context,r),l}}function n_(t,e,n,r,{event:o}){const s=typeof o=="function"?o(n,r):o;return[e,{event:s},void 0]}function r_(t,{event:e}){t.defer(()=>t.emit(e))}function gm(t){function e(n,r){}return e.type="xstate.emit",e.event=t,e.resolve=n_,e.execute=r_,e}let gu=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function o_(t,e,n,r,{to:o,event:s,id:i,delay:a},l){var m;const c=e.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${s}" }) instead`);const u=typeof s=="function"?s(n,r):s;let d;if(typeof a=="string"){const g=c&&c[a];d=typeof g=="function"?g(n,r):g}else d=typeof a=="function"?a(n,r):a;const h=typeof o=="function"?o(n,r):o;let p;if(typeof h=="string"){if(h===gu.Parent?p=t.self._parent:h===gu.Internal?p=t.self:h.startsWith("#_")?p=e.children[h.slice(2)]:p=(m=l.deferredActorIds)!=null&&m.includes(h)?h:e.children[h],!p)throw new Error(`Unable to send event to actor '${h}' from machine '${e.machine.id}'.`)}else p=h||t.self;return[e,{to:p,targetId:typeof h=="string"?h:void 0,event:u,id:i,delay:d},void 0]}function s_(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function i_(t,e){t.defer(()=>{const{to:n,event:r,delay:o,id:s}=e;if(typeof o=="number"){t.system.scheduler.schedule(t.self,n,r,o,s);return}t.system._relay(t.self,n,r.type===oM?jp(t.self.id,r.data):r)})}function yu(t,e,n){function r(o,s){}return r.type="xstate.sendTo",r.to=t,r.event=e,r.id=n==null?void 0:n.id,r.delay=n==null?void 0:n.delay,r.resolve=o_,r.retryResolve=s_,r.execute=i_,r}function a_(t,e){return yu(gu.Parent,t,e)}function l_(t,e,n,r,{collect:o}){const s=[],i=function(l){s.push(l)};return i.assign=(...a)=>{s.push(Oe(...a))},i.cancel=(...a)=>{s.push(su(...a))},i.raise=(...a)=>{s.push(Ra(...a))},i.sendTo=(...a)=>{s.push(yu(...a))},i.sendParent=(...a)=>{s.push(a_(...a))},i.spawnChild=(...a)=>{s.push(iu(...a))},i.stopChild=(...a)=>{s.push(Ia(...a))},i.emit=(...a)=>{s.push(gm(...a))},o({context:n.context,event:n.event,enqueue:i,check:a=>gs(a,e.context,n.event,e),self:t.self,system:t.system},r),[e,void 0,s]}function c_(t){function e(n,r){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=l_,e}function u_(t,e,n,r,{value:o,label:s}){return[e,{value:typeof o=="function"?o(n,r):o,label:s},void 0]}function d_({logger:t},{value:e,label:n}){n?t(n,e):t(e)}function f_(t=({context:n,event:r})=>({context:n,event:r}),e){function n(r,o){}return n.type="xstate.log",n.value=t,n.label=e,n.resolve=u_,n.execute=d_,n}function h_(t,e){return new mu(t,e)}function p_(t){const e=ei(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}function yr({schemas:t,actors:e,actions:n,guards:r,delays:o}){return{assign:Oe,sendTo:yu,raise:Ra,log:f_,cancel:su,stopChild:Ia,enqueueActions:c_,emit:gm,spawnChild:iu,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>h_({...s,schemas:t},{actors:e,actions:n,guards:r,delays:o}),extend:s=>yr({schemas:t,actors:e,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...o,...s.delays}})}}function m_(t,e,n){const r=[],o=p_(t);return o.actionExecutor=i=>{r.push(i)},[t.transition(e,n,o),r]}var g_=Object.defineProperty,ym=(t,e)=>{for(var n in e)g_(t,n,{get:e[n],enumerable:!0})},wm={};ym(wm,{Aabb:()=>Ae,Asset:()=>_o,Block:()=>_,Color:()=>gn,Connector:()=>Re,Edited:()=>wr,Held:()=>xt,HitGeometry:()=>ye,Hovered:()=>Yr,Image:()=>oi,MAX_HIT_ARCS:()=>La,MAX_HIT_CAPSULES:()=>Ss,Opacity:()=>Ge,Pointer:()=>Pt,PointerButton:()=>ln,PointerType:()=>qr,ScaleWithZoom:()=>Jr,Shape:()=>yn,StrokeKind:()=>dt,Text:()=>ft,UploadState:()=>er,User:()=>vr,VerticalAlign:()=>Ao,addPointerSample:()=>Va});var y_=[[0,0],[0,0],[0,0],[0,0]],w_=[[0,0],[0,0],[0,0],[0,0]],k_=[[0,0],[0,0]],v_={tag:E.string().max(36).default("div"),position:E.tuple(E.float64(),2).default([0,0]),size:E.tuple(E.float64(),2).default([100,100]),rotateZ:E.float64().default(0),flip:E.tuple(E.boolean(),2).default([!1,!1]),rank:E.string().max(36).default("")},b_=class extends Kt{constructor(){super({name:"block",sync:"document"},v_)}getCenter(t,e,n){const{position:r,size:o}=this.read(t,e),s=n??[0,0];return ot.getCenter(r,o,s),s}setCenter(t,e,n){const r=this.write(t,e);ot.setCenter(r.position,r.size,n)}getCorners(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e),i=n??[[0,0],[0,0],[0,0],[0,0]];return ot.getCorners(r,o,s,i),i}containsPoint(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return ot.containsPoint(r,o,s,n)}translate(t,e,n){const r=this.write(t,e);ot.translate(r.position,n)}setPosition(t,e,n){const r=this.write(t,e);z.copy(r.position,n)}setSize(t,e,n){const r=this.write(t,e);z.copy(r.size,n)}rotateBy(t,e,n){const r=this.write(t,e);r.rotateZ+=n}rotateAround(t,e,n,r){const o=this.write(t,e);o.rotateZ=ot.rotateAround(o.position,o.size,o.rotateZ,n,r)}scaleBy(t,e,n){const r=this.write(t,e);ot.scaleBy(r.position,r.size,n)}scaleAround(t,e,n,r){const o=this.write(t,e);ot.scaleAround(o.position,o.size,n,r)}intersectsAabb(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return ot.intersectsAabb(r,o,s,n,w_,y_,k_)}worldToUv(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e),a=ot.worldToUv(r,o,s,n);return i[0]&&(a[0]=1-a[0]),i[1]&&(a[1]=1-a[1]),a}uvToWorld(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e),a=[i[0]?1-n[0]:n[0],i[1]?1-n[1]:n[1]];return ot.uvToWorld(r,o,s,a)}getUvToWorldMatrix(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e);ot.getUvToWorldMatrix(r,o,s,n),i[0]&&(n[0]=-n[0],n[2]=-n[2],n[4]+=o[0]*Math.cos(s),n[5]+=o[0]*Math.sin(s)),i[1]&&(n[1]=-n[1],n[3]=-n[3],n[4]-=o[1]*Math.sin(s),n[5]+=o[1]*Math.cos(s))}},_=new b_,km=0,vm=1,bm=2,Sm=3,S_={value:E.tuple(E.float32(),4).default([0,0,0,0])},E_=class extends Kt{constructor(){super({name:"aabb"},S_)}containsPoint(t,e,n,r=!0){const{value:o}=this.read(t,e);return Q.containsPoint(o,n,r)}expandByPoint(t,e,n){const{value:r}=this.write(t,e);Q.expand(r,n)}expandByBlock(t,e,n){const r=_.getCorners(t,n),{value:o}=this.write(t,e);for(const s of r)Q.expand(o,s)}expandByAabb(t,e,n){const{value:r}=this.write(t,e);Q.union(r,n)}copyFrom(t,e,n){const{value:r}=this.read(t,n),{value:o}=this.write(t,e);Q.copy(o,r)}setByPoints(t,e,n){if(n.length===0)return;const{value:r}=this.write(t,e);Q.setFromPoints(r,n)}getCenter(t,e){const{value:n}=this.read(t,e);return Q.center(n)}getWidth(t,e){const{value:n}=this.read(t,e);return Q.width(n)}getHeight(t,e){const{value:n}=this.read(t,e);return Q.height(n)}distanceToPoint(t,e,n){const{value:r}=this.read(t,e);return Q.distanceToPoint(r,n)}intersectsEntity(t,e,n){const{value:r}=this.read(t,e),{value:o}=this.read(t,n);return Q.intersects(r,o)}surroundsEntity(t,e,n){const{value:r}=this.read(t,e),{value:o}=this.read(t,n);return Q.contains(r,o)}getCorners(t,e,n){const{value:r}=this.read(t,e),o=n??[[0,0],[0,0],[0,0],[0,0]];return o[0][0]=r[km],o[0][1]=r[vm],o[1][0]=r[bm],o[1][1]=r[vm],o[2][0]=r[bm],o[2][1]=r[Sm],o[3][0]=r[km],o[3][1]=r[Sm],o}applyPadding(t,e,n){const{value:r}=this.write(t,e);Q.pad(r,n)}},Ae=new E_,er={Pending:"pending",Uploading:"uploading",Complete:"complete",Failed:"failed"},_o=He({name:"asset",sync:"document",excludeFromHistory:["uploadState"]},{identifier:E.string().max(512).default(""),uploadState:E.enum(er).default(er.Pending)}),C_={red:E.uint8().default(0),green:E.uint8().default(0),blue:E.uint8().default(0),alpha:E.uint8().default(255)},x_=class extends Kt{constructor(){super({name:"color",sync:"document"},C_)}toHex(t,e){const{red:n,green:r,blue:o,alpha:s}=this.read(t,e),i=n.toString(16).padStart(2,"0"),a=r.toString(16).padStart(2,"0"),l=o.toString(16).padStart(2,"0"),c=s.toString(16).padStart(2,"0");return`#${i}${a}${l}${c}`}fromHex(t,e,n){const r=this.write(t,e);r.red=Number.parseInt(n.slice(1,3),16),r.green=Number.parseInt(n.slice(3,5),16),r.blue=Number.parseInt(n.slice(5,7),16),r.alpha=n.length>7?Number.parseInt(n.slice(7,9),16):255}},gn=new x_,Re=He({name:"connector",sync:"document"},{startBlock:E.ref(),startBlockUv:E.tuple(E.float64(),2).default([0,0]),startUv:E.tuple(E.float64(),2).default([0,0]),endBlock:E.ref(),endBlockUv:E.tuple(E.float64(),2).default([0,0]),endUv:E.tuple(E.float64(),2).default([1,1])}),wr=He({name:"edited"},{}),xt=He({name:"held",sync:"ephemeral"},{sessionId:E.string().max(36).default("")}),ut=[1,0,0,1,0,0],Ss=64,$a=5,La=2,Fa=7,T_={hitCapsules:E.buffer(E.float32()).size(Ss*$a),capsuleCount:E.uint16().default(0),hitArcs:E.buffer(E.float32()).size(La*Fa),arcCount:E.uint16().default(0)},M_=class extends Kt{constructor(){super({name:"hitHeometry"},T_)}getCapsuleAt(t,e,n){const r=this.read(t,e),o=n*$a;return[r.hitCapsules[o],r.hitCapsules[o+1],r.hitCapsules[o+2],r.hitCapsules[o+3],r.hitCapsules[o+4]]}setCapsuleAt(t,e,n,r){const o=this.write(t,e),s=n*$a;for(let i=0;i<$a;i++)o.hitCapsules[s+i]=r[i]}getArcAt(t,e,n){const r=this.read(t,e),o=n*Fa;return[r.hitArcs[o],r.hitArcs[o+1],r.hitArcs[o+2],r.hitArcs[o+3],r.hitArcs[o+4],r.hitArcs[o+5],r.hitArcs[o+6]]}setArcAt(t,e,n,r){const o=this.write(t,e),s=n*Fa;for(let i=0;i<Fa;i++)o.hitArcs[s+i]=r[i]}containsPointWorld(t,e,n){const r=this.read(t,e);_.getUvToWorldMatrix(t,e,ut);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(ut,i);const a=[s[2],s[3]];Te.transformPoint(ut,a);const l=[s[4],s[5]];Te.transformPoint(ut,l);const c=s[6],u=xe.create(i[0],i[1],a[0],a[1],l[0],l[1],c);if(xe.containsPoint(u,n))return!0}for(let o=0;o<r.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(ut,i);const a=[s[2],s[3]];Te.transformPoint(ut,a);const l=s[4],c=rt.create(i[0],i[1],a[0],a[1],l);if(rt.containsPoint(c,n))return!0}return!1}intersectsAabbWorld(t,e,n){const r=this.read(t,e);_.getUvToWorldMatrix(t,e,ut);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(ut,i);const a=[s[2],s[3]];Te.transformPoint(ut,a);const l=[s[4],s[5]];Te.transformPoint(ut,l);const c=s[6],u=xe.create(i[0],i[1],a[0],a[1],l[0],l[1],c);if(xe.intersectsAabb(u,n))return!0}for(let o=0;o<r.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(ut,i);const a=[s[2],s[3]];Te.transformPoint(ut,a);const l=s[4],c=rt.create(i[0],i[1],a[0],a[1],l);if(rt.intersectsAabb(c,n))return!0}return!1}getExtremaWorld(t,e){const n=this.read(t,e),r=[];_.getUvToWorldMatrix(t,e,ut);for(let o=0;o<n.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(ut,i);const a=[s[2],s[3]];Te.transformPoint(ut,a);const l=s[4],c=rt.create(i[0],i[1],a[0],a[1],l);r.push(...rt.getExtrema(c))}for(let o=0;o<n.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(ut,i);const a=[s[2],s[3]];Te.transformPoint(ut,a);const l=[s[4],s[5]];Te.transformPoint(ut,l);const c=s[6],u=xe.create(i[0],i[1],a[0],a[1],l[0],l[1],c);r.push(...xe.getExtrema(u))}return r}addCapsule(t,e,n){const r=this.write(t,e),o=r.capsuleCount;if(o>=Ss){console.warn(`HitGeometry: Max capsules (${Ss}) reached`);return}this.setCapsuleAt(t,e,o,n),r.capsuleCount=o+1}addCapsuleUv(t,e,n,r,o){const s=[n[0],n[1],r[0],r[1],o];this.addCapsule(t,e,s)}addCapsuleWorld(t,e,n,r,o){const s=_.worldToUv(t,e,n),i=_.worldToUv(t,e,r);this.addCapsuleUv(t,e,s,i,o)}addArc(t,e,n){const r=this.write(t,e),o=r.arcCount;if(o>=La){console.warn(`HitGeometry: Max arcs (${La}) reached`);return}this.setArcAt(t,e,o,n),r.arcCount=o+1}addArcUv(t,e,n,r,o,s){const i=[n[0],n[1],r[0],r[1],o[0],o[1],s];this.addArc(t,e,i)}addArcWorld(t,e,n,r,o,s){const i=_.worldToUv(t,e,n),a=_.worldToUv(t,e,r),l=_.worldToUv(t,e,o);this.addArcUv(t,e,i,a,l,s)}clear(t,e){const n=this.write(t,e);n.capsuleCount=0,n.arcCount=0}},ye=new M_,Yr=He({name:"hovered"},{}),oi=He({name:"image",sync:"document"},{width:E.uint16().default(0),height:E.uint16().default(0),alt:E.string().max(256).default("")}),Ge=He({name:"opacity"},{value:E.uint8().default(255)}),ln={None:"none",Left:"left",Middle:"middle",Right:"right",Back:"back",Forward:"forward"},qr={Mouse:"mouse",Pen:"pen",Touch:"touch"},kr=6,__={pointerId:E.uint16().default(0),position:E.tuple(E.float32(),2).default([0,0]),downPosition:E.tuple(E.float32(),2).default([0,0]),downFrame:E.uint32().default(0),button:E.enum(ln).default(ln.None),pointerType:E.enum(qr).default(qr.Mouse),pressure:E.float32().default(0),obscured:E.boolean().default(!1),_prevPositions:E.array(E.float32(),kr*2),_prevTimes:E.array(E.float32(),kr),_sampleCount:E.int32().default(0),_velocity:E.tuple(E.float32(),2).default([0,0])},A_=class extends Kt{constructor(){super({name:"pointer"},__)}getVelocity(t,e){const n=this.read(t,e);return[n._velocity[0],n._velocity[1]]}getButton(t){switch(t){case 0:return ln.Left;case 1:return ln.Middle;case 2:return ln.Right;case 3:return ln.Back;case 4:return ln.Forward;default:return ln.None}}getType(t){switch(t){case"pen":return qr.Pen;case"touch":return qr.Touch;default:return qr.Mouse}}},Pt=new A_;function Va(t,e,n){const r=t._sampleCount%kr,o=t._prevTimes[r]||0;if(Math.abs(o-n)<.001)return;t.position=e,t._sampleCount++;const s=t._sampleCount%kr;t._prevPositions[s*2]=e[0],t._prevPositions[s*2+1]=e[1],t._prevTimes[s]=n;const i=Math.min(t._sampleCount,kr);if(i<=1){t._velocity=[0,0];return}const a=S=>(S%kr+kr)%kr,l=.04,c=1e-6;let u=0,d=0,h=0,p=0,m=0,g=0,y=0;for(let S=0;S<i;S++){const v=a(t._sampleCount-i+1+S),T=(t._prevTimes[v]||0)-n,A=-T;if(A>5*l)continue;const P=Math.exp(-A/l),$=t._prevPositions[v*2]||0,V=t._prevPositions[v*2+1]||0;u+=P,d+=P*T,h+=P*T*T,p+=P*$,m+=P*V,g+=P*T*$,y+=P*T*V}const w=u*h-d*d;if(Math.abs(w)<=c){const S=t._sampleCount%kr,v=a(t._sampleCount-1),x=(t._prevTimes[S]||0)-(t._prevTimes[v]||0);if(x>c){const T=(t._prevPositions[S*2]||0)-(t._prevPositions[v*2]||0),A=(t._prevPositions[S*2+1]||0)-(t._prevPositions[v*2+1]||0);t._velocity=[T/x,A/x]}else t._velocity=[0,0];return}const k=(u*g-d*p)/w,b=(u*y-d*m)/w;t._velocity=[k,b]}var Jr=He({name:"scaleWithZoom"},{anchor:E.tuple(E.float64(),2).default([.5,.5]),startPosition:E.tuple(E.float64(),2).default([0,0]),startSize:E.tuple(E.float64(),2).default([0,0]),scaleMultiplier:E.tuple(E.float64(),2).default([1,1])}),dt={Solid:"solid",Dashed:"dashed",None:"none"},yn=He({name:"shape",sync:"document"},{kind:E.string().default("rectangle"),strokeKind:E.enum(dt).default(dt.Solid),strokeWidth:E.uint16().default(2),strokeRed:E.uint8().default(0),strokeGreen:E.uint8().default(0),strokeBlue:E.uint8().default(0),strokeAlpha:E.uint8().default(255),fillRed:E.uint8().default(255),fillGreen:E.uint8().default(255),fillBlue:E.uint8().default(255),fillAlpha:E.uint8().default(0)});function I_(){const t=["#f43f5e","#ec4899","#a855f7","#6366f1","#3b82f6","#0ea5e9","#14b8a6","#22c55e","#eab308","#f97316"];return t[Math.floor(Math.random()*t.length)]}var Em=qt({userId:ct().max(36).default(()=>crypto.randomUUID()),sessionId:ct().max(36).default(()=>crypto.randomUUID()),color:ct().max(7).default(I_),name:ct().max(100).default("Anonymous"),avatar:ct().max(500).default("")});function si(t,e){return t.resources.pluginResources[e]}var B_=qt({enabled:Lt().default(!0),strict:Lt().default(!1),colWidth:Xe().nonnegative().default(20),rowHeight:Xe().nonnegative().default(20),snapAngleRad:Xe().nonnegative().default(Math.PI/36),shiftSnapAngleRad:Xe().nonnegative().default(Math.PI/12)}),P_=qt({leftMouseTool:ct().max(32).default("select"),middleMouseTool:ct().max(32).default("hand"),rightMouseTool:ct().max(32).default("menu"),wheelTool:ct().max(32).default("scroll"),modWheelTool:ct().max(32).default("zoom")}),N_=qt({plugins:pn(mn()).default([]),maxEntities:Xe().default(5e3),user:mn().default({}),grid:mn().default({}),blockDefs:pn(mn()).default([]),keybinds:pn(mn()).default([]),cursors:wT(ct(),mn()).default({}),components:pn(mn()).default([]),singletons:pn(mn()).default([]),systems:pn(mn()).default([]),fonts:pn(mn()).default([]),omitPluginKeybinds:Lt().default(!1),omitPluginCursors:Lt().default(!1),omitPluginFonts:Lt().default(!1),controls:mn().optional()});qt({command:ct(),key:Xe(),mod:Lt().optional(),shift:Lt().optional()}),qt({makeSvg:OT({input:xa([Xe()]),output:ct()}),hotspot:xa([Xe(),Xe()]),rotationOffset:Xe()});var st={Top:"top",Center:"center",Bottom:"bottom"},wn={Left:"left",Center:"center",Right:"right",Justify:"justify"},Cm=qt({canEdit:Lt().default(!1),removeWhenTextEmpty:Lt().default(!1)}),xm=qt({enabled:Lt().default(!0),terminals:pn(xa([Xe(),Xe()])).default([[.5,0],[.5,1],[.5,.5],[0,.5],[1,.5]])}),D_=jc(["background","content","overlay"]),wu=qt({tag:ct(),stratum:D_.default("content"),editOptions:Cm.default(Cm.parse({})),components:pn(mn()).default([]),resizeMode:jc(["scale","text","free","groupOnly"]).default("scale"),canRotate:Lt().default(!0),canScale:Lt().default(!0),connectors:xm.default(xm.parse({}))}),ft=He({name:"text",sync:"document"},{content:E.string().max(1e4).default(""),fontSizePx:E.float64().default(24),fontFamily:E.string().max(64).default("Figtree"),lineHeight:E.float64().default(1.2),letterSpacingEm:E.float64().default(0),constrainWidth:E.boolean().default(!0),defaultAlignment:E.enum(wn).default(wn.Left)}),vr=He({name:"user",sync:"ephemeral"},{userId:E.string().max(36),sessionId:E.string().max(36),color:E.string().max(7),name:E.string().max(100),avatar:E.string().max(500),position:E.tuple(E.float32(),2).default([0,0])}),Ao=He({name:"verticalAlign",sync:"document"},{value:E.enum(st).default(st.Top)}),O_="core",ku={background:0,content:1,overlay:2},Tm={};ym(Tm,{Camera:()=>he,Controls:()=>Qe,Cursor:()=>kn,Frame:()=>Es,Grid:()=>Dt,Intersect:()=>Xr,Key:()=>Xt,Keyboard:()=>_n,Mouse:()=>An,RankBounds:()=>In,ScaleWithZoomState:()=>Su,Screen:()=>Nt,clearBits:()=>J_,codeToIndex:()=>N,setBit:()=>ii});var R_={width:E.float64().default(0),height:E.float64().default(0),left:E.float64().default(0),top:E.float64().default(0)},z_=class extends bt{constructor(){super({name:"screen"},R_)}getSize(t){const e=this.read(t);return[e.width,e.height]}getPosition(t){const e=this.read(t);return[e.left,e.top]}getCenter(t){const e=this.read(t);return[e.left+e.width/2,e.top+e.height/2]}},Nt=new z_,$_={top:E.float64().default(0),left:E.float64().default(0),zoom:E.float64().default(1),canSeeBlocks:E.boolean().default(!0),lastSeenBlock:E.ref()},L_=class extends bt{constructor(){super({name:"camera",sync:"local"},$_)}toWorld(t,e){const n=this.read(t),r=n.left+e[0]/n.zoom,o=n.top+e[1]/n.zoom;return[r,o]}toScreen(t,e){const n=this.read(t),r=(e[0]-n.left)*n.zoom,o=(e[1]-n.top)*n.zoom;return[r,o]}getWorldCenter(t){const e=this.read(t),n=Nt.read(t);return[e.left+n.width/e.zoom/2,e.top+n.height/e.zoom/2]}getWorldBounds(t){const e=this.read(t),n=Nt.read(t);return{left:e.left,top:e.top,right:e.left+n.width/e.zoom,bottom:e.top+n.height/e.zoom}}getAabb(t,e){const n=this.read(t),r=Nt.read(t),o=e??[0,0,0,0];return o[0]=n.left,o[1]=n.top,o[2]=n.left+r.width/n.zoom,o[3]=n.top+r.height/n.zoom,o}},he=new L_,F_={leftMouseTool:E.string().max(32).default("select"),middleMouseTool:E.string().max(32).default("hand"),rightMouseTool:E.string().max(32).default("menu"),wheelTool:E.string().max(32).default("scroll"),modWheelTool:E.string().max(32).default("zoom"),heldSnapshot:E.string().max(4096).default("")},V_=class extends bt{constructor(){super({name:"controls"},F_)}getButtons(t,...e){const n=this.read(t),r=[];return e.includes(n.leftMouseTool)&&r.push(ln.Left),e.includes(n.middleMouseTool)&&r.push(ln.Middle),e.includes(n.rightMouseTool)&&r.push(ln.Right),r}wheelActive(t,e,n){const r=this.read(t);return r.wheelTool===e&&!n||r.modWheelTool===e&&n}},Qe=new V_,W_={cursorKind:E.string().max(64).default("select"),rotation:E.float64().default(0),contextCursorKind:E.string().max(64).default(""),contextRotation:E.float64().default(0)},U_=class extends bt{constructor(){super({name:"cursor"},W_)}getEffective(t){const e=this.read(t);return e.contextCursorKind?{cursorKind:e.contextCursorKind,rotation:e.contextRotation}:{cursorKind:e.cursorKind,rotation:e.rotation}}setCursor(t,e,n=0){const r=this.write(t);r.cursorKind=e,r.rotation=n}setContextCursor(t,e,n=0){const r=this.write(t);r.contextCursorKind=e,r.contextRotation=n}clearContextCursor(t){const e=this.write(t);e.contextCursorKind="",e.contextRotation=0}},kn=new U_,Es=xh({name:"frame"},{number:E.uint32().default(0),delta:E.float64().default(0),time:E.float64().default(0),lastTime:E.float64().default(0)}),H_={enabled:E.boolean().default(!1),strict:E.boolean().default(!1),colWidth:E.float64().default(20),rowHeight:E.float64().default(20),snapAngleRad:E.float64().default(Math.PI/36),shiftSnapAngleRad:E.float64().default(Math.PI/12)},j_=class extends bt{constructor(){super({name:"grid"},H_)}snapPosition(t,e){const n=this.read(t);n.enabled&&(n.colWidth!==0&&(e[0]=Math.round(e[0]/n.colWidth)*n.colWidth),n.rowHeight!==0&&(e[1]=Math.round(e[1]/n.rowHeight)*n.rowHeight))}snapSize(t,e){const n=this.read(t);n.enabled&&(n.colWidth!==0&&(e[0]=Math.max(n.colWidth,Math.round(e[0]/n.colWidth)*n.colWidth)),n.rowHeight!==0&&(e[1]=Math.max(n.rowHeight,Math.round(e[1]/n.rowHeight)*n.rowHeight)))}snapX(t,e){const n=this.read(t);return!n.enabled||n.colWidth===0?e:Math.round(e/n.colWidth)*n.colWidth}snapY(t,e){const n=this.read(t);return!n.enabled||n.rowHeight===0?e:Math.round(e/n.rowHeight)*n.rowHeight}},Dt=new j_,Z_={entity1:E.ref(),entity2:E.ref(),entity3:E.ref(),entity4:E.ref(),entity5:E.ref()},K_=class extends bt{constructor(){super({name:"intersect"},Z_)}getTop(t){return this.read(t).entity1}getAll(t){const e=this.read(t),n=[];return e.entity1!==null&&n.push(e.entity1),e.entity2!==null&&n.push(e.entity2),e.entity3!==null&&n.push(e.entity3),e.entity4!==null&&n.push(e.entity4),e.entity5!==null&&n.push(e.entity5),n}setAll(t,e){const n=this.write(t);n.entity1=e[0]??null,n.entity2=e[1]??null,n.entity3=e[2]??null,n.entity4=e[3]??null,n.entity5=e[4]??null}clear(t){const e=this.write(t);e.entity1=null,e.entity2=null,e.entity3=null,e.entity4=null,e.entity5=null}},Xr=new K_,vu=32,Y_={keysDown:E.buffer(E.uint8()).size(vu),keysDownTrigger:E.buffer(E.uint8()).size(vu),keysUpTrigger:E.buffer(E.uint8()).size(vu),shiftDown:E.boolean().default(!1),altDown:E.boolean().default(!1),modDown:E.boolean().default(!1)};function bu(t,e){if(e<0||e>=t.length*8)return!1;const n=Math.floor(e/8),r=e%8;return(t[n]&1<<r)!==0}var q_=class extends bt{constructor(){super({name:"keyboard"},Y_)}isKeyDown(t,e){return bu(this.read(t).keysDown,e)}isKeyDownTrigger(t,e){return bu(this.read(t).keysDownTrigger,e)}isKeyUpTrigger(t,e){return bu(this.read(t).keysUpTrigger,e)}},_n=new q_;function ii(t,e,n){if(e<0||e>=t.length*8)return;const r=Math.floor(e/8),o=e%8;n?t[r]|=1<<o:t[r]&=~(1<<o)}function J_(t){for(let e=0;e<t.length;e++)t[e]=0}var N={KeyA:0,KeyB:1,KeyC:2,KeyD:3,KeyE:4,KeyF:5,KeyG:6,KeyH:7,KeyI:8,KeyJ:9,KeyK:10,KeyL:11,KeyM:12,KeyN:13,KeyO:14,KeyP:15,KeyQ:16,KeyR:17,KeyS:18,KeyT:19,KeyU:20,KeyV:21,KeyW:22,KeyX:23,KeyY:24,KeyZ:25,Digit0:26,Digit1:27,Digit2:28,Digit3:29,Digit4:30,Digit5:31,Digit6:32,Digit7:33,Digit8:34,Digit9:35,F1:36,F2:37,F3:38,F4:39,F5:40,F6:41,F7:42,F8:43,F9:44,F10:45,F11:46,F12:47,ShiftLeft:48,ShiftRight:49,ControlLeft:50,ControlRight:51,AltLeft:52,AltRight:53,MetaLeft:54,MetaRight:55,Escape:56,Space:57,Enter:58,Tab:59,Backspace:60,Delete:61,ArrowLeft:62,ArrowUp:63,ArrowRight:64,ArrowDown:65,Home:66,End:67,PageUp:68,PageDown:69,Insert:70,Semicolon:72,Equal:73,Comma:74,Minus:75,Period:76,Slash:77,Backquote:78,BracketLeft:79,Backslash:80,BracketRight:81,Quote:82,Numpad0:84,Numpad1:85,Numpad2:86,Numpad3:87,Numpad4:88,Numpad5:89,Numpad6:90,Numpad7:91,Numpad8:92,Numpad9:93,NumpadAdd:94,NumpadSubtract:95,NumpadMultiply:96,NumpadDivide:97,NumpadDecimal:98,NumpadEnter:99},Xt={A:N.KeyA,B:N.KeyB,C:N.KeyC,D:N.KeyD,E:N.KeyE,F:N.KeyF,G:N.KeyG,H:N.KeyH,I:N.KeyI,J:N.KeyJ,K:N.KeyK,L:N.KeyL,M:N.KeyM,N:N.KeyN,O:N.KeyO,P:N.KeyP,Q:N.KeyQ,R:N.KeyR,S:N.KeyS,T:N.KeyT,U:N.KeyU,V:N.KeyV,W:N.KeyW,X:N.KeyX,Y:N.KeyY,Z:N.KeyZ,Digit0:N.Digit0,Digit1:N.Digit1,Digit2:N.Digit2,Digit3:N.Digit3,Digit4:N.Digit4,Digit5:N.Digit5,Digit6:N.Digit6,Digit7:N.Digit7,Digit8:N.Digit8,Digit9:N.Digit9,F1:N.F1,F2:N.F2,F3:N.F3,F4:N.F4,F5:N.F5,F6:N.F6,F7:N.F7,F8:N.F8,F9:N.F9,F10:N.F10,F11:N.F11,F12:N.F12,ShiftLeft:N.ShiftLeft,ShiftRight:N.ShiftRight,ControlLeft:N.ControlLeft,ControlRight:N.ControlRight,AltLeft:N.AltLeft,AltRight:N.AltRight,MetaLeft:N.MetaLeft,MetaRight:N.MetaRight,Escape:N.Escape,Space:N.Space,Enter:N.Enter,Tab:N.Tab,Backspace:N.Backspace,Delete:N.Delete,ArrowLeft:N.ArrowLeft,ArrowUp:N.ArrowUp,ArrowRight:N.ArrowRight,ArrowDown:N.ArrowDown,Home:N.Home,End:N.End,PageUp:N.PageUp,PageDown:N.PageDown,Insert:N.Insert,Semicolon:N.Semicolon,Equal:N.Equal,Comma:N.Comma,Minus:N.Minus,Period:N.Period,Slash:N.Slash,Backquote:N.Backquote,BracketLeft:N.BracketLeft,Backslash:N.Backslash,BracketRight:N.BracketRight,Quote:N.Quote,Numpad0:N.Numpad0,Numpad1:N.Numpad1,Numpad2:N.Numpad2,Numpad3:N.Numpad3,Numpad4:N.Numpad4,Numpad5:N.Numpad5,Numpad6:N.Numpad6,Numpad7:N.Numpad7,Numpad8:N.Numpad8,Numpad9:N.Numpad9,NumpadAdd:N.NumpadAdd,NumpadSubtract:N.NumpadSubtract,NumpadMultiply:N.NumpadMultiply,NumpadDivide:N.NumpadDivide,NumpadDecimal:N.NumpadDecimal,NumpadEnter:N.NumpadEnter},X_={position:E.tuple(E.float32(),2).default([0,0]),wheelDeltaX:E.float32().default(0),wheelDeltaY:E.float32().default(0),moveTrigger:E.boolean().default(!1),wheelTrigger:E.boolean().default(!1),enterTrigger:E.boolean().default(!1),leaveTrigger:E.boolean().default(!1)},G_=class extends bt{constructor(){super({name:"mouse"},X_)}didMove(t){return this.read(t).moveTrigger}didScroll(t){return this.read(t).wheelTrigger}didEnter(t){return this.read(t).enterTrigger}didLeave(t){return this.read(t).leaveTrigger}getPosition(t){const e=this.read(t);return[e.position[0],e.position[1]]}getWheelDelta(t){const e=this.read(t);return[e.wheelDeltaX,e.wheelDeltaY]}},An=new G_,Q_={minRank:E.string().max(36).default(""),maxRank:E.string().max(36).default("")},eA=class extends bt{constructor(){super({name:"rankBounds"},Q_)}genNext(t){const e=this.write(t),n=Aa(e.maxRank||null,null);return e.maxRank=n,e.minRank||(e.minRank=n),n}genPrev(t){const e=this.write(t),n=Aa(null,e.minRank||null);return e.minRank=n,e.maxRank||(e.maxRank=n),n}genBetween(t,e){return Aa(t,e)}add(t,e){if(!e)return;const n=this.write(t);(!n.minRank||e<n.minRank)&&(n.minRank=e),(!n.maxRank||e>n.maxRank)&&(n.maxRank=e)}},In=new eA,Su=xh({name:"scaleWithZoomState"},{lastZoom:E.float64().default(1)}),Cs=_c({name:E.string().max(128)}),Mm=new WeakMap;function Eu(t){const{editor:e}=Le(t);let n=Mm.get(e);return n||(n=new Map,Mm.set(e,n)),n}var Cu=ne(t=>t.with(Cs));function le(t){return{name:t,spawn(e,n){const r=vt(e);return G(e,r,Cs,{name:t}),Eu(e).set(r,n),r},*iter(e){const n=Eu(e);for(const r of Cu.current(e))if(Cs.read(e,r).name===t){const s=n.get(r);yield{eid:r,payload:s}}},didSpawnLastFrame(e){for(const n of Cu.removed(e))if(Cs.read(e,n).name===t)return!0;return!1}}}function tA(t){const e=Eu(t);for(const n of Cu.current(t))e.delete(n),Ye(t,n)}function ie(t,e,n){for(const{payload:r}of e.iter(t))n(t,r)}var _m=le("undo"),xu=le("redo"),nA=0;function pe(t,e){return{_system:new Fb(e),phase:t.phase,priority:t.priority??nA}}var rA=pe({phase:"capture"},t=>{const e=_n.read(t),{editor:n}=Le(t);for(const r of n.keybinds){let o=_n.isKeyDownTrigger(t,r.key);if(o&&(o=!!r.mod===e.modDown),o&&(o=!!r.shift===e.shiftDown),o){const s=vt(t);G(t,s,Cs,{name:r.command});break}}}),oA=pe({phase:"input",priority:100},t=>{const e=performance.now(),n=Es._getInstance(t).buffer,r=n.lastTime[0];n.number[0]++,n.lastTime[0]=e,n.time[0]=e,r===0?n.delta[0]=.016:n.delta[0]=Math.min((e-r)/1e3,.1)}),ai=new WeakMap;function sA(t){if(ai.has(t))return;t.hasAttribute("tabindex")||t.setAttribute("tabindex","0");const e={eventsBuffer:[],onKeyDown:n=>{(n.key==="Tab"||n.key==="Alt"||n.key===" ")&&n.preventDefault(),e.eventsBuffer.push(n)},onKeyUp:n=>{e.eventsBuffer.push(n)},onBlur:()=>{e.eventsBuffer.push({type:"blur"})},keysDown:new Uint8Array(32),keysDownTrigger:new Uint8Array(32),keysUpTrigger:new Uint8Array(32)};ai.set(t,e),t.addEventListener("keydown",e.onKeyDown),t.addEventListener("keyup",e.onKeyUp),t.addEventListener("blur",e.onBlur)}function iA(t){const e=ai.get(t);e&&(t.removeEventListener("keydown",e.onKeyDown),t.removeEventListener("keyup",e.onKeyUp),t.removeEventListener("blur",e.onBlur),ai.delete(t))}var aA=pe({phase:"input"},t=>{const e=Le(t),n=ai.get(e.domElement);if(!n)return;const r=n.eventsBuffer.length>0,o=!Am(n.keysDownTrigger)||!Am(n.keysUpTrigger);if(!r&&!o)return;const s=_n.write(t),i=n.keysDown,a=n.keysDownTrigger,l=n.keysUpTrigger;a.fill(0),l.fill(0),i.set(s.keysDown);for(const c of n.eventsBuffer){if(c.type==="blur"){i.fill(0),s.shiftDown=!1,s.altDown=!1,s.modDown=!1;continue}const u=N[c.code];u!==void 0&&(c.type==="keydown"?(lA(i,u)||ii(a,u,!0),ii(i,u,!0)):c.type==="keyup"&&(ii(i,u,!1),ii(l,u,!0)),s.shiftDown=c.shiftKey,s.altDown=c.altKey,s.modDown=c.ctrlKey||c.metaKey)}s.keysDown=i,s.keysDownTrigger=a,s.keysUpTrigger=l,n.eventsBuffer.length=0});function lA(t,e){if(e<0||e>=t.length*8)return!1;const n=Math.floor(e/8),r=e%8;return(t[n]&1<<r)!==0}function Am(t){for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}var li=new WeakMap;function cA(t){if(li.has(t))return;const e={eventsBuffer:[],onMouseMove:n=>{e.eventsBuffer.push({type:"mousemove",clientX:n.clientX,clientY:n.clientY})},onWheel:n=>{n.preventDefault(),e.eventsBuffer.push({type:"wheel",clientX:n.clientX,clientY:n.clientY,deltaX:n.deltaX,deltaY:n.deltaY,deltaMode:n.deltaMode})},onMouseEnter:()=>{e.eventsBuffer.push({type:"mouseenter"})},onMouseLeave:()=>{e.eventsBuffer.push({type:"mouseleave"})}};li.set(t,e),window.addEventListener("mousemove",e.onMouseMove),t.addEventListener("wheel",e.onWheel,{passive:!1}),t.addEventListener("mouseenter",e.onMouseEnter),t.addEventListener("mouseleave",e.onMouseLeave)}function uA(t){const e=li.get(t);e&&(window.removeEventListener("mousemove",e.onMouseMove),t.removeEventListener("wheel",e.onWheel),t.removeEventListener("mouseenter",e.onMouseEnter),t.removeEventListener("mouseleave",e.onMouseLeave),li.delete(t))}var dA=pe({phase:"input"},t=>{const e=Le(t),n=li.get(e.domElement);if(!n)return;const r=An.read(t),o=r.moveTrigger||r.wheelTrigger||r.enterTrigger||r.leaveTrigger,s=n.eventsBuffer.length>0;if(!o&&!s)return;const i=An.write(t),a=Nt.read(t);i.moveTrigger=!1,i.wheelTrigger=!1,i.enterTrigger=!1,i.leaveTrigger=!1,i.wheelDeltaX=0,i.wheelDeltaY=0;for(const l of n.eventsBuffer)switch(l.type){case"mousemove":i.position=[l.clientX-a.left,l.clientY-a.top],i.moveTrigger=!0;break;case"wheel":i.wheelDeltaX=l.deltaX,i.wheelDeltaY=fA(l.deltaY,l.deltaMode),i.wheelTrigger=!0;break;case"mouseenter":i.enterTrigger=!0;break;case"mouseleave":i.leaveTrigger=!0;break}n.eventsBuffer.length=0});function fA(t,e){const r=typeof window<"u"?window.innerHeight:800;let o=t;return e===1?o*=16:e===2&&(o*=r),typeof navigator<"u"&&navigator.userAgent.includes("Firefox")&&(o*=4),typeof navigator<"u"&&(navigator.userAgent.includes("Mac")||navigator.userAgent.includes("Macintosh"))&&(o*=1.5),Math.min(Math.max(o,-100),100)}var ci=new WeakMap;function hA(t){if(ci.has(t))return;const e={eventsBuffer:[],frameCount:0,pointerEntityMap:new Map,onPointerDown:n=>{e.eventsBuffer.push({type:"pointerdown",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})},onContextMenu:n=>{n.preventDefault(),!e.eventsBuffer.some(o=>o.type==="pointerdown")&&e.eventsBuffer.push({type:"pointerdown",pointerId:0,clientX:n.clientX,clientY:n.clientY,button:2,pointerType:"mouse",pressure:.5,target:n.target})},onPointerMove:n=>{e.eventsBuffer.push({type:"pointermove",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})},onPointerUp:n=>{e.eventsBuffer.push({type:"pointerup",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})},onPointerCancel:n=>{e.eventsBuffer.push({type:"pointercancel",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})}};ci.set(t,e),t.addEventListener("pointerdown",e.onPointerDown),t.addEventListener("contextmenu",e.onContextMenu),window.addEventListener("pointermove",e.onPointerMove),window.addEventListener("pointerup",e.onPointerUp),window.addEventListener("pointercancel",e.onPointerCancel)}function pA(t){const e=ci.get(t);e&&(t.removeEventListener("pointerdown",e.onPointerDown),t.removeEventListener("contextmenu",e.onContextMenu),window.removeEventListener("pointermove",e.onPointerMove),window.removeEventListener("pointerup",e.onPointerUp),window.removeEventListener("pointercancel",e.onPointerCancel),ci.delete(t))}var mA=pe({phase:"input"},t=>{const e=Le(t),{domElement:n}=e,r=ci.get(n);if(!r)return;r.frameCount++;const o=Nt.read(t),s=r.frameCount/60;for(const i of r.eventsBuffer)switch(i.type){case"pointerdown":{const a=[i.clientX-o.left,i.clientY-o.top],l=vt(t);G(t,l,Pt,{pointerId:i.pointerId,position:a,downPosition:a,downFrame:r.frameCount,button:Pt.getButton(i.button),pointerType:Pt.getType(i.pointerType),pressure:i.pressure,obscured:i.target!==n});const c=Pt.write(t,l);Va(c,a,s),r.pointerEntityMap.set(i.pointerId,l);break}case"pointermove":{const a=r.pointerEntityMap.get(i.pointerId);if(a===void 0)break;const l=[i.clientX-o.left,i.clientY-o.top],c=Pt.write(t,a);Va(c,l,s),c.pressure=i.pressure,c.obscured=i.target!==n;break}case"pointerup":case"pointercancel":{const a=r.pointerEntityMap.get(i.pointerId);if(a===void 0)break;const l=[i.clientX-o.left,i.clientY-o.top],c=Pt.write(t,a);Va(c,l,s),Ye(t,a),r.pointerEntityMap.delete(i.pointerId);break}}r.eventsBuffer.length=0}),ui=new WeakMap;function gA(t){if(ui.has(t))return;const e={needsUpdate:!1,resizeObserver:new ResizeObserver(()=>{e.needsUpdate=!0}),onScroll:()=>{e.needsUpdate=!0}};ui.set(t,e),e.resizeObserver.observe(t),window.addEventListener("scroll",e.onScroll,!0)}function yA(t){const e=ui.get(t);e&&(e.resizeObserver.disconnect(),window.removeEventListener("scroll",e.onScroll,!0),ui.delete(t))}var wA=pe({phase:"input"},t=>{const e=Le(t),{domElement:n}=e,r=ui.get(n);if(!r||(Es.read(t).number===1&&(r.needsUpdate=!0),!r.needsUpdate))return;const s=Nt.write(t),i=n.getBoundingClientRect();s.left=i.left,s.top=i.top,s.width=i.width,s.height=i.height,r.needsUpdate=!1}),kA=ne(t=>t.tracking(kn));function vA(t,e,n){const r=t[e];if(!r)return"auto";const o=r.makeSvg(n+r.rotationOffset);return`url("data:image/svg+xml,${encodeURIComponent(o.trim())}") ${r.hotspot[0]} ${r.hotspot[1]}, auto`}var bA=pe({phase:"render",priority:-100},t=>{const e=kA.changed(t),n=Es.read(t);if(e.length===0&&n.number!==1)return;const{cursorKind:r,rotation:o}=kn.getEffective(t);if(!r){document.body.style.cursor="default";return}const{editor:s}=Le(t),i=vA(s.cursors,r,o);document.body.style.cursor=i});function SA(t){const{editor:e}=Le(t);return e.blockDefs}function Ft(t,e){return SA(t)[e]??wu.parse({tag:e})}function Im(t,e){return Ft(t,e).editOptions.canEdit}function Bm(t,e,n){if(O(t,e,ye)){const r=ye.getExtremaWorld(t,e);Q.setFromPoints(n,r)}else{const r=_.getCorners(t,e);Q.setFromPoints(n,r)}}function Tu(t,e){if(!O(t,e,xt))return!1;const{sessionId:n}=Le(t),r=xt.read(t,e);return r.sessionId!==""&&r.sessionId!==n}var Pm=ne(t=>t.with(_,Ae));function EA(t,e,n){const r=[],o=Pm.current(t);for(const s of o)if(Ae.containsPoint(t,s,e)){if(O(t,s,ye)){if(!ye.containsPointWorld(t,s,e))continue}else if(!_.containsPoint(t,s,e))continue;r.push(s)}return xA(t,r)}function CA(t,e,n){const r=[],o=n??Pm.current(t);for(const s of o){const{value:i}=Ae.read(t,s);if(Q.intersects(e,i)){if(Q.contains(e,i)){r.push(s);continue}O(t,s,ye)?ye.intersectsAabbWorld(t,s,e)&&r.push(s):_.intersectsAabb(t,s,e)&&r.push(s)}}return r}function xA(t,e){return e.sort((n,r)=>{const o=_.read(t,n),s=_.read(t,r),i=Ft(t,o.tag).stratum,a=Ft(t,s.tag).stratum,l=ku[i],c=ku[a];if(c!==l)return c-l;const u=o.rank,d=s.rank;return!u&&!d?0:u?d?d>u?1:d<u?-1:0:-1:1})}var xs=[1,0,0,1,0,0];function TA(t,e,n){const r=[],o=rt.bounds(e);for(const s of n){const i=Ae.read(t,s);Q.intersects(o,i.value)&&(O(t,s,ye)?MA(t,s,e)&&r.push(s):rt.intersectsAabb(e,i.value)&&r.push(s))}return r}function MA(t,e,n){const r=ye.read(t,e);_.getUvToWorldMatrix(t,e,xs);for(let o=0;o<r.arcCount;o++){const s=ye.getArcAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(xs,i);const a=[s[2],s[3]];Te.transformPoint(xs,a);const l=[s[4],s[5]];Te.transformPoint(xs,l);const c=s[6],u=xe.create(i[0],i[1],a[0],a[1],l[0],l[1],c),d=rt.pointA(n),h=rt.pointB(n);if(xe.intersectsCapsule(u,d,h,rt.radius(n)))return!0}for(let o=0;o<r.capsuleCount;o++){const s=ye.getCapsuleAt(t,e,o),i=[s[0],s[1]];Te.transformPoint(xs,i);const a=[s[2],s[3]];Te.transformPoint(xs,a);const l=s[4],c=rt.create(i[0],i[1],a[0],a[1],l);if(rt.intersectsCapsule(n,c))return!0}return!1}var _A=ne(t=>t.with(vr));function AA(t){const e=Le(t).sessionId;for(const n of _A.current(t))if(vr.read(t,n).sessionId===e)return n;return null}var Nm=ne(t=>t.tracking(Pt)),IA=pe({phase:"render",priority:-100},t=>{if(An.didMove(t)){const i=An.read(t);Dm(t,i.position);return}if(Nm.changed(t).length===0)return;const n=Nm.current(t);let r=null,o=Number.MAX_SAFE_INTEGER;for(const i of n){const a=Pt.read(t,i);a.pointerId<o&&(o=a.pointerId,r=i)}const s=Pt.read(t,r);Dm(t,s.position)});function Dm(t,e){const n=AA(t);if(n===null)return;const r=vr.write(t,n);r.position=he.toWorld(t,e)}var Om=ne(t=>t.tracking(_)),Rm=ne(t=>t.tracking(ye)),zm=ne(t=>t.with(xt).tracking(xt)),BA=ne(t=>t.with(Yr)),PA=ne(t=>t.with(Pt));function $m(t){for(const e of BA.current(t))O(t,e,Yr)&&nn(t,e,Yr)}function NA(t,e){for(const n of e)return Tu(t,n)?void 0:n}function DA(t,e){const r=Qe.read(t).leftMouseTool==="select";if($m(t),!r)return;const o=NA(t,e);o!==void 0&&G(t,o,Yr,{})}function OA(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var di=new Set,fi=new Set,RA=pe({phase:"capture",priority:100},t=>{di.clear();for(const m of Om.added(t))di.add(m);for(const m of Rm.added(t))di.add(m);fi.clear();for(const m of Om.changed(t))fi.add(m);for(const m of Rm.changed(t))fi.add(m);for(const m of di){O(t,m,Ae)||G(t,m,Ae,{value:[0,0,0,0]});const g=Ae.write(t,m);Bm(t,m,g.value)}for(const m of fi){const g=Ae.write(t,m);Bm(t,m,g.value)}const e=An.didMove(t),n=An.didLeave(t),r=An.didScroll(t),o=di.size>0||fi.size>0,s=zm.added(t),i=zm.removed(t),a=s.length>0||i.length>0;if(!e&&!n&&!r&&!o&&!a)return;if(n){Xr.clear(t),$m(t);return}const l=An.getPosition(t),c=he.toWorld(t,l),u=EA(t,c),d=Xr.getAll(t),h=!OA(u,d);h&&Xr.setAll(t,u),!(PA.current(t).length>0)&&(h||a)&&DA(t,u)}),zA=ne(t=>t.with(de,_)),$A=pe({phase:"input",priority:100},t=>{const e=zA.added(t);for(const n of e){const r=_.read(t,n);if(r.rank===""){const o=_.write(t,n);o.rank=In.genNext(t)}else In.add(t,r.rank)}}),LA=ne(t=>t.tracking(he)),FA=ne(t=>t.with(de,_,Ae)),VA=ne(t=>t.with(de,_,Ae)),WA=[0,0,0,0],UA=pe({phase:"render",priority:90},t=>{if(LA.changed(t).length===0&&VA.addedOrRemoved(t).length===0)return;const e=he.read(t),n=he.getAabb(t,WA);if(e.canSeeBlocks&&e.lastSeenBlock!==null&&O(t,e.lastSeenBlock,Ae)){const i=Ae.read(t,e.lastSeenBlock);if(Q.intersects(n,i.value))return}let r=null;for(const i of FA.current(t)){const a=Ae.read(t,i);if(Q.intersects(n,a.value)){r=i;break}}const o=r!==null;if(o===e.canSeeBlocks){r!==e.lastSeenBlock&&(he.write(t).lastSeenBlock=r);return}const s=he.write(t);s.canSeeBlocks=o,s.lastSeenBlock=r}),Lm=ne(t=>t.with(_).tracking(Jr)),Wa=[0,0],Ua=[0,0],HA=pe({phase:"render",priority:100},t=>{const e=he.read(t),n=Su.read(t);if(!Ct.approxEqual(e.zoom,n.lastZoom)){for(const o of Lm.current(t))Fm(t,o,e.zoom);Su.write(t).lastZoom=e.zoom}for(const o of Lm.addedOrChanged(t))Fm(t,o,e.zoom)});function Fm(t,e,n){const r=_.write(t,e),o=Jr.read(t,e),s=1/n,i=1+(s-1)*o.scaleMultiplier[0],a=1+(s-1)*o.scaleMultiplier[1];Wa[0]=o.startSize[0]*i,Wa[1]=o.startSize[1]*a,z.copy(Ua,o.startSize),z.sub(Ua,Wa),z.multiply(Ua,o.anchor),z.copy(r.position,o.startPosition),z.add(r.position,Ua),z.copy(r.size,Wa)}var jA={name:O_,singletons:Object.values(Tm).filter(t=>t instanceof bt),components:Object.values(wm).filter(t=>t instanceof Kt),blockDefs:[{tag:"sticky-note",components:[gn,ft,Ao],editOptions:{canEdit:!0}},{tag:"text",components:[ft],resizeMode:"text",editOptions:{canEdit:!0,removeWhenTextEmpty:!0}},{tag:"image",components:[oi,_o],resizeMode:"scale"},{tag:"shape",components:[yn,ft,Ao],resizeMode:"free",editOptions:{canEdit:!0}}],systems:[oA,$A,aA,dA,wA,mA,RA,rA,HA,UA,bA,IA],setup(t){const{domElement:e}=Le(t);sA(e),cA(e),gA(e),hA(e)},teardown(t){const{domElement:e}=Le(t);iA(e),uA(e),yA(e),pA(e)}},ZA=qt({name:ct(),displayName:ct(),url:ct(),previewImage:ct().optional(),selectable:Lt().default(!0),weights:pn(Xe()).default([400,700]),italics:Lt().default(!0)}),KA=class{constructor(){this.loadedFonts=new Set}async loadFonts(t){const e=t.filter(r=>!this.loadedFonts.has(r.name));if(e.length===0)return;const n=e.map(r=>this.loadSingleFont(r));await Promise.all(n)}buildGoogleFontsUrl(t){const e=t.url;if(!e.includes("fonts.googleapis.com"))return e;const n=new URL(e),r=n.searchParams.get("family");if(!r)return e;const o=r.split(":")[0],s=t.weights,i=[];if(t.italics){for(const a of s)i.push(`0,${a}`);for(const a of s)i.push(`1,${a}`);n.searchParams.set("family",`${o}:ital,wght@${i.join(";")}`)}else n.searchParams.set("family",`${o}:wght@${s.join(";")}`);return n.toString()}loadSingleFont(t){return this.loadedFonts.add(t.name),new Promise((e,n)=>{const r=document.createElement("link");r.rel="stylesheet",r.href=this.buildGoogleFontsUrl(t),r.onload=async()=>{try{const o=this.getFontLoadPromises(t);await Promise.all(o),await document.fonts.ready,e()}catch(o){n(new Error(`Failed to load font face for: ${t.name}. ${o}`))}},r.onerror=()=>{n(new Error(`Failed to load font stylesheet: ${t.name}`))},document.head.appendChild(r)})}getFontLoadPromises(t){const e=[],n=t.name;for(const r of t.weights)e.push(document.fonts.load(`${r} 12px "${n}"`)),t.italics&&e.push(document.fonts.load(`italic ${r} 12px "${n}"`));return e}isLoaded(t){return this.loadedFonts.has(t)}getLoadedFonts(){return this.loadedFonts}};function YA(t){return typeof t=="function"?t({}):t}function qA(t){const e=[],n=new Set,r=new Set,o=new Map(t.map(i=>[i.name,i]));function s(i){if(!n.has(i.name)){if(r.has(i.name))throw new Error(`Circular plugin dependency detected: ${i.name}`);r.add(i.name);for(const a of i.dependencies??[]){const l=o.get(a);if(!l)throw new Error(`Plugin "${i.name}" depends on "${a}" which is not registered`);s(l)}r.delete(i.name),n.add(i.name),e.push(i)}}for(const i of t)s(i);return e}var Vm=["input","capture","update","render"];function JA(t){const e=new Map;for(const r of Vm)e.set(r,[]);for(const r of t)e.get(r.phase).push(r);const n=[];for(const r of Vm){const o=e.get(r),s=new Map;for(const a of o){const l=s.get(a.priority)??[];l.push(a),s.set(a.priority,l)}const i=[...s.keys()].sort((a,l)=>l-a);for(const a of i)n.push(s.get(a))}return n}var XA=class{constructor(e,n){this.cursors={},this.blockDefs={},this.fonts=[],this.components=[],this.singletons=[];const r=N_.parse(n??{}),{plugins:o,maxEntities:s}=r,i=Em.parse(r.user??{});this.userData=i,this.gridOptions=B_.parse(r.grid??{}),this.controlsOptions=P_.parse(r.controls??{});const a=o.map(YA),l=qA([jA,...a]),c=[Cs,de];for(const v of l)v.components&&c.push(...v.components),v.singletons&&c.push(...v.singletons);c.push(...r.components),c.push(...r.singletons);const u=r.keybinds;if(!r.omitPluginKeybinds)for(const v of l)v.keybinds&&u.push(...v.keybinds);this.keybinds=u;const d={};for(const v of r.blockDefs){const x=wu.parse(v);d[x.tag]=x}for(const v of l)if(v.blockDefs)for(const x of v.blockDefs){const T=wu.parse(x);d[T.tag]=T}this.blockDefs=d;const h={};if(Object.assign(h,r.cursors),!r.omitPluginCursors)for(const v of l)v.cursors&&Object.assign(h,v.cursors);this.cursors=h,this.fontLoader=new KA;const p=[...r.fonts];if(!r.omitPluginFonts)for(const v of l)v.fonts&&p.push(...v.fonts);this.fonts=p.map(v=>ZA.parse(v));const m={};for(const v of l)v.resources!==void 0&&(m[v.name]=v.resources);const g=new Map,y=new Map,w=new Map,k=new Map,b={domElement:e,editor:this,userId:i.userId,sessionId:i.sessionId,pluginResources:m,componentsByName:g,singletonsByName:y,componentsById:w,singletonsById:k};this.world=new qb(c,{maxEntities:s,resources:b});const S=[];for(const v of l)v.systems&&S.push(...v.systems);S.push(...r.systems),this.systemBatches=JA(S),this.plugins=new Map(l.map(v=>[v.name,v]));for(const v of l){if(v.components)for(const x of v.components){const T=x._getComponentId(this.ctx);w.set(T,x),g.set(x.name,x)}if(v.singletons)for(const x of v.singletons){const T=x._getComponentId(this.ctx);k.set(T,x),y.set(x.name,x)}}for(const v of r.components){const x=v._getComponentId(this.ctx);w.set(x,v),g.set(v.name,v)}for(const v of r.singletons){const x=v._getComponentId(this.ctx);k.set(x,v),y.set(v.name,v)}this.components=[...g.values()],this.singletons=[...y.values()]}get ctx(){return this.world._getContext()}async initialize(){this.fonts.length>0&&await this.fontLoader.loadFonts(this.fonts),Dt.copy(this.ctx,this.gridOptions),Qe.copy(this.ctx,this.controlsOptions),this.nextTick(e=>{const n=vt(e);G(e,n,de,{id:crypto.randomUUID()}),G(e,n,vr,{userId:this.userData.userId,sessionId:this.userData.sessionId,color:this.userData.color,name:this.userData.name,avatar:this.userData.avatar})});for(const e of this.plugins.values())e.setup&&await e.setup(this.ctx)}async tick(){this.world.sync();for(const n of this.systemBatches){const r=n.map(o=>o._system);await this.world.execute(...r)}const e=this.ctx.eventBuffer.getWriteIndex();this.ctx.prevEventIndex=e,this.ctx.currEventIndex=e,tA(this.ctx)}nextTick(e){return this.world.nextSync(n=>{e(n)})}command(e,...n){const r=n[0];this.nextTick(o=>{e.spawn(o,r)})}subscribe(e,n){return this.world.subscribe(e,(r,o)=>{n(r,o)})}_getContext(){return this.ctx}dispose(){const e=Array.from(this.plugins.values()).reverse();for(const n of e)n.teardown&&n.teardown(this.ctx);this.world.dispose(),this.plugins.clear(),this.systemBatches=[]}};function GA(t,e,n,r){if(r.length===0)return{value:e,context:n};let o=t.resolveState({value:String(e),context:n});for(const s of r){const[i,a]=m_(t,o,s);o=i;for(const l of a)typeof l.exec=="function"&&l.exec(l.info,l.params)}return{value:o.value,context:o.context}}var QA=class extends bt{constructor(t,e){super({name:t,sync:"none"},e)}getState(t){return this.read(t).state}getContext(t){const e=this.snapshot(t),n={};for(const r of Object.keys(e))r!=="state"&&(n[r]=e[r]);return n}run(t,e,n){const r=this.getState(t),o=this.getContext(t),s=GA(e,r,o,n),i=this.write(t);i.state=s.value;for(const[a,l]of Object.entries(s.context))i[a]=l;return s}};function Gr(t,e){return new QA(t,e)}function e2(t){const e=Es.read(t);return{type:"frame",ctx:t,delta:e.delta,frameNumber:e.number,time:e.time}}function t2(t,e){const n=[];for(const r of e)_n.isKeyDownTrigger(t,r)&&n.push({type:"keyDown",key:r,ctx:t}),_n.isKeyUpTrigger(t,r)&&n.push({type:"keyUp",key:r,ctx:t});return n}function Wm(t){const e=[],n=An.read(t),r=[n.position[0],n.position[1]],o=he.toWorld(t,r);return n.wheelTrigger&&e.push({type:"wheel",ctx:t,screenPosition:r,worldPosition:o,wheelDeltaX:n.wheelDeltaX,wheelDeltaY:n.wheelDeltaY}),n.moveTrigger&&e.push({type:"mouseMove",ctx:t,screenPosition:r,worldPosition:o,wheelDeltaX:0,wheelDeltaY:0}),e}var n2=3,r2=30,Ha=ne(t=>t.tracking(Pt)),Um=new Map;function o2(t){const e=t.readerId;let n=Um.get(e);return n||(n={prevPositions:new Map,prevModifiers:{shiftDown:!1,altDown:!1,modDown:!1},prevCamera:{left:0,top:0,zoom:1}},Um.set(e,n)),n}function br(t,e,n={}){if(e.length===0)return[];const{includeFrameEvent:r=!1,clickMoveThreshold:o=n2,clickFrameThreshold:s=r2}=n,i=o2(t),a=Es.read(t).number,l=[],c=_n.read(t),u={shiftDown:c.shiftDown,altDown:c.altDown,modDown:c.modDown},d=he.read(t),h=V=>{const U=Pt.read(t,V);return e.includes(U.button)},p=Xr.getAll(t),m=(V,U)=>{const M=Pt.read(t,U),L=[M.position[0],M.position[1]],q=he.toWorld(t,L);return{type:V,ctx:t,screenPosition:L,worldPosition:q,velocity:[M._velocity[0],M._velocity[1]],pressure:M.pressure,button:M.button,pointerType:M.pointerType,obscured:M.obscured,shiftDown:u.shiftDown,altDown:u.altDown,modDown:u.modDown,cameraLeft:d.left,cameraTop:d.top,cameraZoom:d.zoom,pointerId:U,intersects:p}},g=Ha.added(t),y=Ha.removed(t),w=Ha.changed(t),k=Ha.current(t),b=g.filter(h),S=y.filter(h),v=w.filter(h),x=Array.from(k).filter(h),T=_n.isKeyDownTrigger(t,Xt.Escape),A=x.length>1&&b.length>0;if((T||A)&&x.length>0)return l.push(m("cancel",x[0])),l;if(b.length>0&&x.length===1){const V=x[0],U=Pt.read(t,V);U.obscured||(l.push(m("pointerDown",V)),i.prevPositions.set(V,[U.position[0],U.position[1]]))}if(S.length>0&&x.length===0){const V=S[0],U=Pt.read(t,V);l.push(m("pointerUp",V));const M=i.prevPositions.get(V);if(M){const L=[U.position[0],U.position[1]],q=z.distance(M,L),se=a-U.downFrame;q<o&&se<s&&l.push(m("click",V)),i.prevPositions.delete(V)}}const P=u.shiftDown!==i.prevModifiers.shiftDown||u.altDown!==i.prevModifiers.altDown||u.modDown!==i.prevModifiers.modDown,$=d.left!==i.prevCamera.left||d.top!==i.prevCamera.top||d.zoom!==i.prevCamera.zoom;return(v.length>0||P||$)&&x.length===1&&l.push(m("pointerMove",x[0])),r&&x.length===1&&l.push(m("frame",x[0])),i.prevModifiers={...u},i.prevCamera={left:d.left,top:d.top,zoom:d.zoom},l}var Gt={ECS:1,History:2,Persistence:3,Websocket:4},s2=1;function Hm(t){const e=new Set,n=new Map;for(const r of t){if(e.has(r.name))throw new Error(`Duplicate migration name: "${r.name}"`);if(e.add(r.name),r.supersedes!=null){if(!e.has(r.supersedes))throw new Error(`Migration "${r.name}" supersedes "${r.supersedes}", which ${t.some(o=>o.name===r.supersedes)?"must come before it":"does not exist"}`);if(n.has(r.supersedes))throw new Error(`Migration "${r.supersedes}" is already superseded by "${n.get(r.supersedes)}"`);n.set(r.supersedes,r.name)}}}function Mu(t,e){let n=null;for(const[r,o]of Object.entries(t)){if(o._exists!==!0)continue;const s=r.slice(r.indexOf("/")+1),i=e.get(s);if(!i||i.migrations.length===0)continue;const{_exists:a,_version:l,...c}=o,u=i2(c,l??null,i.migrations);u.changed&&(n||(n={...t}),n[r]={...u.data,_exists:!0,_version:u.version})}return n??t}function i2(t,e,n){if(n.length===0)return{data:t,version:e,changed:!1};const r=new Set;for(const l of n)l.supersedes!=null&&r.add(l.supersedes);let o=0;if(e!==null){const l=n.findIndex(c=>c.name===e);if(l===-1)throw new Error(`Unknown migration version "${e}" — known versions: ${n.map(c=>`"${c.name}"`).join(", ")}`);o=l+1}let s=t,i=e,a=!1;for(let l=o;l<n.length;l++){const c=n[l];r.has(c.name)||(s=c.upgrade(s,i),i=c.name,a=!0)}return{data:s,version:i,changed:a}}function _u(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!=typeof e)return!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!_u(t[n],e[n]))return!1;return!0}if(typeof t=="object"&&typeof e=="object"){const n=t,r=e,o=Object.keys(n),s=Object.keys(r);return o.length!==s.length?!1:o.every(i=>_u(n[i],r[i]))}return!1}function cn(...t){const e={},n=new Set;for(const r of t)for(const[o,s]of Object.entries(r)){const i=e[o];s._exists===!1?n.has(o)?(delete e[o],n.delete(o)):e[o]={_exists:!1}:i===void 0||i._exists===!1?(i===void 0&&s._exists===!0&&n.add(o),e[o]={...s}):e[o]={...i,...s}}return e}function jm(t,e){if(Object.keys(e).length===0)return t;const n={};for(const[r,o]of Object.entries(t)){const s=e[r];if(s===void 0){n[r]=o;continue}if(o._exists===!1){n[r]=o;continue}if(s._exists===!1)continue;const i={};let a=!1;for(const[l,c]of Object.entries(o))l in s||(i[l]=c,a=!0);a&&(n[r]=i)}return n}var a2=1e3;async function Zm(t,e,n){const r=await Qf(t,1,{upgrade(o){o.objectStoreNames.contains(e)||o.createObjectStore(e)}});return new l2(r,e,n)}var l2=class{constructor(e,n,r){C(this,"pending",new Map);C(this,"flushTimer",null);C(this,"flushIntervalMs");this.db=e,this.storeName=n,this.flushIntervalMs=(r==null?void 0:r.flushIntervalMs)??a2}async get(e){const n=this.pending.get(e);return n?n.type==="put"?n.value:void 0:this.db.get(this.storeName,e)}put(e,n){this.pending.set(e,{type:"put",value:n}),this.scheduleFlush()}delete(e){this.pending.set(e,{type:"delete"}),this.scheduleFlush()}async getAllEntries(){const n=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName),r=await n.getAllKeys(),o=await n.getAll(),s=new Map;for(let i=0;i<r.length;i++)s.set(r[i],o[i]);for(const[i,a]of this.pending)a.type==="put"?s.set(i,a.value):s.delete(i);return Array.from(s.entries())}async clear(){this.pending.clear(),this.cancelFlush();const e=this.db.transaction(this.storeName,"readwrite");e.objectStore(this.storeName).clear(),await e.done}close(){this.flushSync(),this.db.close()}scheduleFlush(){if(this.flushIntervalMs===0){this.flush().catch(console.error);return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(console.error)},this.flushIntervalMs))}cancelFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async flush(){if(this.pending.size===0)return;const e=new Map(this.pending);this.pending.clear();const n=this.db.transaction(this.storeName,"readwrite"),r=n.objectStore(this.storeName);for(const[o,s]of e)s.type==="put"?r.put(s.value,o):r.delete(o);await n.done}flushSync(){this.cancelFlush(),this.pending.size!==0&&this.flush().catch(console.error)}},c2=1e3/30,u2=1e3,d2=(ur=class{constructor(e){C(this,"url");C(this,"clientId");C(this,"ws",null);C(this,"pendingDocumentPatches",[]);C(this,"pendingEphemeralPatches",[]);C(this,"lastTimestamp",0);C(this,"messageCounter",0);C(this,"inFlight",new Map);C(this,"startOffline");C(this,"usePersistence");C(this,"documentId");C(this,"store",null);C(this,"offlineBuffer",{});C(this,"connectedUsers",0);C(this,"intentionallyClosed",!1);C(this,"reconnectTimer",null);C(this,"reconnectDelay",500);C(this,"documentSendBuffer",[]);C(this,"ephemeralSendBuffer",[]);C(this,"lastSendTime",0);C(this,"localEphemeralState",{});C(this,"remoteEphemeralState",{});C(this,"token");C(this,"onVersionMismatch");C(this,"onConnectivityChange");C(this,"componentsByName");this.url=e.url,this.clientId=e.clientId,this.startOffline=e.startOffline??!1,this.usePersistence=e.usePersistence,this.documentId=e.documentId,this.token=e.token,this.onVersionMismatch=e.onVersionMismatch,this.onConnectivityChange=e.onConnectivityChange;const n=new Map;for(const r of[...e.components,...e.singletons])n.set(r.name,r);this.componentsByName=n}get isOnline(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}async init(){if(this.usePersistence)try{this.store=await Zm(`${this.documentId}-ws`,"meta");const e=await this.store.get("offlineBuffer"),n=await this.store.get("lastTimestamp");e&&(this.offlineBuffer=e),n&&(this.lastTimestamp=n)}catch(e){console.error("Failed to load websocket offline state:",e)}if(this.startOffline){this.intentionallyClosed=!0;return}this.intentionallyClosed=!1;try{await this.connectWs()}catch(e){console.warn("WebSocket connection failed:",e),this.scheduleReconnect()}}connectWs(){return this.inFlight.clear(),new Promise((e,n)=>{const r=new URL(this.url);r.searchParams.set("roomId",this.documentId),r.searchParams.set("clientId",this.clientId),this.token&&r.searchParams.set("token",this.token);const o=new WebSocket(r.toString());o.addEventListener("open",()=>{var i;this.ws=o,(i=this.onConnectivityChange)==null||i.call(this,!0);const s={type:"reconnect",lastTimestamp:this.lastTimestamp,protocolVersion:s2,...Object.keys(this.offlineBuffer).length>0&&{documentPatches:[this.offlineBuffer]},...Object.keys(this.localEphemeralState).length>0&&{ephemeralPatches:[this.localEphemeralState]}};o.send(JSON.stringify(s)),e()}),o.addEventListener("error",()=>{n(new Error(`WebSocket failed to connect to ${this.url}`))}),o.addEventListener("message",s=>{this.handleMessage(s.data)}),o.addEventListener("close",()=>{var s;this.ws=null,(s=this.onConnectivityChange)==null||s.call(this,!1),this.clearRemoteEphemeral(),this.intentionallyClosed||this.scheduleReconnect()})})}push(e){const n=[],r=[];for(const o of e)o.origin!==Gt.Websocket&&o.origin!==Gt.Persistence&&o.syncBehavior!=="local"&&(o.syncBehavior==="ephemeral"?r.push(o.patch):n.push(o.patch));if(!this.isOnline){n.length>0&&(this.offlineBuffer=cn(this.offlineBuffer,...n),this.persistOfflineBuffer()),r.length>0&&(this.localEphemeralState=cn(this.localEphemeralState,...r));return}n.length>0&&this.documentSendBuffer.push(...n),r.length>0&&this.ephemeralSendBuffer.push(...r),this.flushIfReady()}get sendInterval(){return this.connectedUsers>1?c2:u2}flushIfReady(){performance.now()-this.lastSendTime>=this.sendInterval&&this.flush()}flush(){if(!this.isOnline)return;const e=[];Object.keys(this.offlineBuffer).length>0&&(e.push(this.offlineBuffer),this.offlineBuffer={}),e.push(...this.documentSendBuffer),this.documentSendBuffer=[];const n=this.ephemeralSendBuffer;if(this.ephemeralSendBuffer=[],n.length>0&&(this.localEphemeralState=cn(this.localEphemeralState,...n)),e.length===0&&n.length===0)return;const r=`${this.clientId}-${++this.messageCounter}`;e.length>0&&this.inFlight.set(r,cn(...e));const o={type:"patch",messageId:r,...e.length>0&&{documentPatches:e},...n.length>0&&{ephemeralPatches:n}};this.ws.send(JSON.stringify(o)),this.lastSendTime=performance.now()}pull(){const e=[];if(this.pendingDocumentPatches.length>0){const n=cn(...this.pendingDocumentPatches);this.pendingDocumentPatches=[];const r=Mu(n,this.componentsByName),o=Mu(this.offlineBuffer,this.componentsByName),s=jm(r,o);this.clearPersistedOfflineBuffer(),Object.keys(s).length>0&&e.push({patch:s,origin:Gt.Websocket,syncBehavior:"document"})}if(this.pendingEphemeralPatches.length>0){const n=cn(...this.pendingEphemeralPatches);this.pendingEphemeralPatches=[],e.push({patch:n,origin:Gt.Websocket,syncBehavior:"ephemeral"})}return e}disconnect(){this.intentionallyClosed=!0,this.clearReconnectTimer(),this.ws&&(this.ws.close(),this.ws=null)}close(){this.disconnect(),this.store&&(this.store.close(),this.store=null)}async reconnect(){this.intentionallyClosed=!1,this.reconnectDelay=ur.MIN_RECONNECT_DELAY,this.clearReconnectTimer(),await this.connectWs()}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}scheduleReconnect(){this.clearReconnectTimer(),this.reconnectTimer=setTimeout(async()=>{this.reconnectTimer=null;try{await this.connectWs(),this.reconnectDelay=ur.MIN_RECONNECT_DELAY}catch{this.reconnectDelay=Math.min(this.reconnectDelay*2,ur.MAX_RECONNECT_DELAY),this.scheduleReconnect()}},this.reconnectDelay)}handleMessage(e){var r;let n;try{n=JSON.parse(e)}catch{return}switch(n.type){case"patch":{if(this.lastTimestamp=n.timestamp,this.persistTimestamp(),n.documentPatches&&n.documentPatches.length>0){const o=this.stripInFlightFields(n.documentPatches);this.pendingDocumentPatches.push(...o)}n.ephemeralPatches&&n.ephemeralPatches.length>0&&(this.pendingEphemeralPatches.push(...n.ephemeralPatches),this.remoteEphemeralState=cn(this.remoteEphemeralState,...n.ephemeralPatches));break}case"ack":this.lastTimestamp=n.timestamp,this.persistTimestamp(),this.inFlight.delete(n.messageId);break;case"clientCount":this.connectedUsers=n.count;break;case"version-mismatch":this.disconnect(),(r=this.onVersionMismatch)==null||r.call(this,n.serverProtocolVersion);break}}stripInFlightFields(e){if(this.inFlight.size===0)return e;const n=cn(...Array.from(this.inFlight.values())),r=[];for(const o of e){const s=jm(o,n);Object.keys(s).length>0&&r.push(s)}return r}clearRemoteEphemeral(){const e=Object.keys(this.remoteEphemeralState);if(e.length===0)return;const n={};for(const r of e)n[r]={_exists:!1};this.pendingEphemeralPatches.push(n),this.remoteEphemeralState={}}persistOfflineBuffer(){!this.store||!this.usePersistence||this.store.put("offlineBuffer",this.offlineBuffer)}persistTimestamp(){!this.store||!this.usePersistence||this.store.put("lastTimestamp",this.lastTimestamp)}clearPersistedOfflineBuffer(){Object.keys(this.offlineBuffer).length!==0&&(this.offlineBuffer={},!(!this.store||!this.usePersistence)&&this.store.delete("offlineBuffer"))}},C(ur,"MIN_RECONNECT_DELAY",500),C(ur,"MAX_RECONNECT_DELAY",1e4),ur),Km=class extends Mc{constructor(e,n){super(n,!1);C(this,"name");C(this,"sync");C(this,"migrations");C(this,"excludeFromHistory");this.name=e.name,this.sync=e.sync??"none",this.migrations=e.migrations??[],this.excludeFromHistory=e.excludeFromHistory??[],this.migrations.length>0&&Hm(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(e,n){return{...super.snapshot(e,n),_exists:!0,_version:this.currentVersion}}};function f2(t,e){return new Km(t,e)}var Ym=class extends gh{constructor(e,n){super(n);C(this,"name");C(this,"sync");C(this,"migrations");C(this,"excludeFromHistory");this.name=e.name,this.sync=e.sync??"none",this.migrations=e.migrations??[],this.excludeFromHistory=e.excludeFromHistory??[],this.migrations.length>0&&Hm(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(e){return{...super.snapshot(e),_exists:!0,_version:this.currentVersion}}};function qm(t,e){return new Ym(t,e)}var hi=_c({id:E.string().max(36)}),Au="SINGLETON";function h2(t,e){if(t._exists===!1&&e._exists===!1)return null;if(t._exists===!1)return e;if(e._exists===!1)return null;const n={};let r=!1;for(const o in e){if(o==="_exists")continue;const s=t[o],i=e[o];_u(s,i)||(n[o]=i,r=!0)}return r?n:null}var p2=class{constructor(t){C(this,"ctx");C(this,"components");C(this,"singletons");C(this,"componentMap",new Map);C(this,"componentsByName",new Map);C(this,"stableIdToEntity",new Map);C(this,"entityToStableId",new Map);C(this,"prevState",{});C(this,"eventIndex",0);C(this,"initialized",!1);this.components=t.components,this.singletons=t.singletons}async init(){}ensureInitialized(){if(this.initialized)return;this.initialized=!0;const t=this.ctx;for(const e of[...this.components,...this.singletons]){if(e.sync==="none")continue;const n=e._getComponentId(t);this.componentMap.set(n,e),this.componentsByName.set(e.name,e)}}pull(){this.ensureInitialized();const t=this.ctx,{events:e}=t.eventBuffer.readEvents(this.eventIndex);if(e.length===0)return[];const n={},r={},o={},s=a=>a==="ephemeral"?r:a==="local"?o:n;for(const a of e){const{entityId:l,eventType:c,componentId:u}=a;if(c===_e.REMOVED){const y=this.entityToStableId.get(l);if(!y)continue;const w=`${y}/`;for(const k of Object.keys(this.prevState))if(k.startsWith(w)){const b=k.slice(w.length),S=this.componentsByName.get(b),v=s(S==null?void 0:S.sync);v[k]={_exists:!1},this.prevState[k]={_exists:!1}}this.stableIdToEntity.delete(y),this.entityToStableId.delete(l);continue}const d=this.componentMap.get(u);if(!d||!d.isSingleton&&!O(t,l,hi,!1))continue;const h=hi.read(t,l);let p;d.isSingleton?p=Au:(p=h.id,this.stableIdToEntity.set(p,l),this.entityToStableId.set(l,p));const m=`${p}/${d.name}`,g=s(d.sync);switch(c){case _e.COMPONENT_ADDED:{if(d.isSingleton)continue;const y=d.snapshot(t,l),w=this.translateRefsOutbound(d,y);g[m]=w,this.prevState[m]={...w};break}case _e.COMPONENT_REMOVED:{if(d.isSingleton)continue;g[m]={_exists:!1},this.prevState[m]={_exists:!1};break}case _e.CHANGED:{const y=d.isSingleton?d.snapshot(t):d.snapshot(t,l),w=this.translateRefsOutbound(d,y),k=this.prevState[m]??{_exists:!1},b=h2(k,w);if(!b)continue;g[m]=b,this.prevState[m]={...w};break}}}const i=[];return Object.keys(n).length>0&&i.push({patch:n,origin:Gt.ECS,syncBehavior:"document"}),Object.keys(r).length>0&&i.push({patch:r,origin:Gt.ECS,syncBehavior:"ephemeral"}),Object.keys(o).length>0&&i.push({patch:o,origin:Gt.ECS,syncBehavior:"local"}),i}push(t){const e=this.ctx;for(const{patch:n,origin:r}of t)if(r!==Gt.ECS){for(const[o,s]of Object.entries(n)){if(!s._exists)continue;const i=o.indexOf("/"),a=o.slice(0,i);if(a!==Au&&!this.stableIdToEntity.has(a)){const l=vt(e);G(e,l,hi,{id:a}),this.stableIdToEntity.set(a,l),this.entityToStableId.set(l,a)}}for(const[o,s]of Object.entries(n)){const i=o.indexOf("/"),a=o.slice(0,i),l=o.slice(i+1),c=this.componentsByName.get(l);if(!c)continue;if(a===Au){if(s._exists===!1)continue;c.patch(e,s),this.prevState[o]={...this.prevState[o],...s};continue}const u=this.stableIdToEntity.get(a);if(u!==void 0){if(s._exists===!1)O(e,u,c,!1)&&nn(e,u,c),this.prevState[o]={_exists:!1};else if(s._exists){const d=this.translateRefsInbound(c,s);O(e,u,c,!1)?c.copy(e,u,d):G(e,u,c,d),this.prevState[o]={...s}}else if(u!==void 0&&O(e,u,c,!1)){const d=this.translateRefsInbound(c,s);c.patch(e,u,d),this.prevState[o]={...this.prevState[o],...s}}}}}this.eventIndex=e.eventBuffer.getWriteIndex()}translateRefsOutbound(t,e){const n=t.schema;let r=!1;for(const s in n)if(n[s].def.type==="ref"){r=!0;break}if(!r)return e;const o={...e};for(const s in n)if(n[s].def.type==="ref"&&o[s]!=null){const i=o[s];o[s]=this.entityToStableId.get(i)??null}return o}translateRefsInbound(t,e){const n=t.schema;let r=!1;for(const s in n)if(n[s].def.type==="ref"){r=!0;break}if(!r)return e;const o={...e};for(const s in n)if(n[s].def.type==="ref"&&o[s]!=null){const i=o[s];o[s]=this.stableIdToEntity.get(i)??null}return o}close(){}},m2=class{constructor(t){C(this,"state",{});C(this,"undoStack",[]);C(this,"redoStack",[]);C(this,"pendingForward",{});C(this,"pendingInverse",{});C(this,"pendingPullPatches",[]);C(this,"dirty",!1);C(this,"commitCheckpointAfterFrames");C(this,"maxHistoryStackSize");C(this,"checkpoints",new Map);C(this,"settledCallbacks",[]);C(this,"cancelCommitSettled",null);C(this,"excludedFields",new Map);this.commitCheckpointAfterFrames=t.commitCheckpointAfterFrames??60,this.maxHistoryStackSize=t.maxHistoryStackSize??100;for(const e of t.components)e.excludeFromHistory.length>0&&this.excludedFields.set(e.name,new Set(e.excludeFromHistory));for(const e of t.singletons)e.excludeFromHistory.length>0&&this.excludedFields.set(e.name,new Set(e.excludeFromHistory))}async init(){}push(t){var n;const e=t.filter(r=>r.origin===Gt.ECS&&r.syncBehavior!=="ephemeral"&&r.syncBehavior!=="local");for(const r of t)if(r.syncBehavior!=="ephemeral")if(r.origin===Gt.ECS&&r.syncBehavior!=="local"){if(Object.keys(r.patch).length===0)continue;const o=this.applyAndComputeInverse(r.patch);let s=r.patch,i=o;if(this.excludedFields.size>0&&(s=this.filterExcludedFields(r.patch),i=this.filterExcludedFields(o,!0),Object.keys(s).length===0))continue;this.pendingForward=cn(this.pendingForward,s),this.pendingInverse=cn(i,this.pendingInverse),this.dirty=!0,(n=this.cancelCommitSettled)==null||n.call(this),this.cancelCommitSettled=this.onSettled(()=>this.commitPendingDelta(),{frames:this.commitCheckpointAfterFrames}),this.redoStack=[]}else this.applyToState(r.patch);this.processSettledCallbacks(e.length===0)}pull(){if(this.pendingPullPatches.length===0)return[];const t=cn(...this.pendingPullPatches);return this.pendingPullPatches=[],[{patch:t,origin:Gt.History,syncBehavior:"document"}]}undo(){if(this.dirty&&this.commitPendingDelta(),this.undoStack.length===0)return!1;const t=this.undoStack.pop(),e=this.applyAndComputeInverse(t.inverse);this.redoStack.push({forward:e,inverse:t.inverse}),this.pendingPullPatches.push(t.inverse);for(const[n,r]of this.checkpoints)r>this.undoStack.length&&this.checkpoints.delete(n);return!0}redo(){if(this.redoStack.length===0)return!1;const t=this.redoStack.pop(),e=this.applyAndComputeInverse(t.forward);return this.undoStack.push({forward:t.forward,inverse:e}),this.pendingPullPatches.push(t.forward),!0}canUndo(){return this.undoStack.length>0||this.dirty}canRedo(){return this.redoStack.length>0}close(){var t;(t=this.cancelCommitSettled)==null||t.call(this),this.cancelCommitSettled=null,this.settledCallbacks=[]}createCheckpoint(){const t=crypto.randomUUID();return this.checkpoints.set(t,this.undoStack.length),t}revertToCheckpoint(t){const e=this.checkpoints.get(t);if(e===void 0)return!1;if(this.commitPendingDelta(),this.undoStack.length<=e)return this.checkpoints.delete(t),!1;for(;this.undoStack.length>e;){const n=this.undoStack.pop();this.applyToState(n.inverse),this.pendingPullPatches.push(n.inverse)}return this.redoStack=[],this.checkpoints.delete(t),!0}squashToCheckpoint(t){const e=this.checkpoints.get(t);if(e===void 0)return!1;if(this.commitPendingDelta(),this.undoStack.length<=e)return this.checkpoints.delete(t),!1;const n=this.undoStack.splice(e),r=cn(...n.map(s=>s.forward)),o=cn(...n.map(s=>s.inverse));for(const s of Object.keys(o))s in r||delete o[s];return Object.keys(r).length===0?(this.checkpoints.delete(t),!0):(this.undoStack.push({forward:r,inverse:o}),this.checkpoints.delete(t),!0)}onSettled(t,e){const n={callback:t,requiredFrames:e.frames,quietFrames:0};return this.settledCallbacks.push(n),()=>{const r=this.settledCallbacks.indexOf(n);r!==-1&&this.settledCallbacks.splice(r,1)}}processSettledCallbacks(t){const e=this.settledCallbacks;this.settledCallbacks=[];for(const n of e)t?(n.quietFrames++,n.quietFrames>=n.requiredFrames?n.callback():this.settledCallbacks.push(n)):(n.quietFrames=0,this.settledCallbacks.push(n))}commitPendingDelta(){if(this.dirty){this.cancelCommitSettled=null,this.dirty=!1;for(const t of Object.keys(this.pendingForward))t in this.pendingInverse&&JSON.stringify(this.pendingForward[t])===JSON.stringify(this.pendingInverse[t])&&(delete this.pendingForward[t],delete this.pendingInverse[t]);if(Object.keys(this.pendingForward).length!==0)for(this.undoStack.push({forward:this.pendingForward,inverse:this.pendingInverse}),this.pendingForward={},this.pendingInverse={};this.undoStack.length>this.maxHistoryStackSize;){this.undoStack.shift();for(const[t,e]of this.checkpoints)e<=0?this.checkpoints.delete(t):this.checkpoints.set(t,e-1)}}}applyAndComputeInverse(t){const e={};for(const[n,r]of Object.entries(t)){const o=this.state[n];if(r._exists===!1)o!==void 0&&o._exists!==!1&&(e[n]={_exists:!0,...o}),this.state[n]={_exists:!1};else if(r._exists){o===void 0||o._exists===!1?e[n]={_exists:!1}:e[n]={_exists:!0,...o};const{_exists:s,...i}=r;this.state[n]=i}else{const s={};for(const a of Object.keys(r))o!==void 0&&o._exists!==!1&&a in o&&(s[a]=o[a]);Object.keys(s).length>0&&(e[n]=s);const i=(o==null?void 0:o._exists)===!1?{}:o;this.state[n]={...i,...r}}}return e}applyToState(t){for(const[e,n]of Object.entries(t))if(n._exists===!1)this.state[e]={_exists:!1};else if(n._exists){const{_exists:r,...o}=n;this.state[e]=o}else{const r=this.state[e],o=(r==null?void 0:r._exists)===!1?{}:r;this.state[e]={...o,...n}}}getExcludedFields(t){const e=t.indexOf("/");if(e===-1)return;const n=t.slice(e+1);return this.excludedFields.get(n)}filterExcludedFields(t,e=!1){const n={};for(const[r,o]of Object.entries(t)){const s=this.getExcludedFields(r);if(!s||s.size===0){n[r]=o;continue}if(o._exists===!1){n[r]=o;continue}if(e&&o._exists){n[r]=o;continue}const i={};let a=!1;for(const[l,c]of Object.entries(o))l==="_exists"?i._exists=c:l==="_version"?i._version=c:s.has(l)||(i[l]=c,a=!0);(o._exists||a)&&(n[r]=i)}return n}},g2=class{constructor(t){C(this,"store",null);C(this,"documentId");C(this,"pendingDocumentPatch",null);C(this,"pendingLocalPatch",null);C(this,"componentsByName");this.documentId=t.documentId,this.componentsByName=new Map;for(const e of[...t.components,...t.singletons])this.componentsByName.set(e.name,e)}async init(){try{this.store=await Zm(this.documentId,"state"),await this.loadState()}catch(t){console.error("IndexedDB error:",t)}}async loadState(){if(!this.store)return;const t=await this.store.getAllEntries(),e={};for(const[s,i]of t)e[s]=i;if(Object.keys(e).length===0)return;const n=Mu(e,this.componentsByName);if(n!==e)for(const[s,i]of Object.entries(n))this.store.put(s,i);const r={},o={};for(const[s,i]of Object.entries(n)){const a=s.indexOf("/"),l=a!==-1?s.slice(a+1):s,c=this.componentsByName.get(l);(c==null?void 0:c.sync)==="local"?o[s]=i:r[s]=i}Object.keys(r).length>0&&(this.pendingDocumentPatch=r),Object.keys(o).length>0&&(this.pendingLocalPatch=o)}push(t){if(!this.store)return;const e=t.filter(n=>n.origin!==Gt.Persistence&&n.syncBehavior!=="ephemeral");e.length!==0&&this.persistMutations(e).catch(n=>{console.error("Error persisting mutations:",n)})}async persistMutations(t){if(this.store)for(const{patch:e}of t)for(const[n,r]of Object.entries(e))if(r._exists===!1)this.store.delete(n);else if(r._exists)this.store.put(n,r);else{const o=await this.store.get(n);o&&this.store.put(n,{...o,...r})}}pull(){const t=[];return this.pendingDocumentPatch&&(t.push({patch:this.pendingDocumentPatch,origin:Gt.Persistence,syncBehavior:"document"}),this.pendingDocumentPatch=null),this.pendingLocalPatch&&(t.push({patch:this.pendingLocalPatch,origin:Gt.Persistence,syncBehavior:"local"}),this.pendingLocalPatch=null),t}close(){this.store&&(this.store.close(),this.store=null)}async clearAll(){this.pendingDocumentPatch=null,this.pendingLocalPatch=null,this.store&&await this.store.clear()}},Jm=class{constructor(t){C(this,"ecsAdapter");C(this,"historyAdapter",null);C(this,"websocketAdapter",null);C(this,"persistenceAdapter",null);C(this,"adapters",[]);C(this,"options");this.options=t}async initialize({components:t,singletons:e}){if(this.ecsAdapter=new p2({components:t,singletons:e}),this.adapters.push(this.ecsAdapter),this.options.persistence&&(this.persistenceAdapter=new g2({documentId:this.options.persistence.documentId,components:t,singletons:e}),this.adapters.push(this.persistenceAdapter)),this.options.history){const n=this.options.history===!0?{}:this.options.history;this.historyAdapter=new m2({components:t,singletons:e,commitCheckpointAfterFrames:n.commitCheckpointAfterFrames,maxHistoryStackSize:n.maxHistoryStackSize}),this.adapters.push(this.historyAdapter)}this.options.websocket&&(this.websocketAdapter=new d2({documentId:this.options.websocket.documentId,url:this.options.websocket.url,clientId:this.options.websocket.clientId,startOffline:this.options.websocket.startOffline,token:this.options.websocket.token,usePersistence:!!this.options.persistence,onVersionMismatch:this.options.websocket.onVersionMismatch,onConnectivityChange:this.options.websocket.onConnectivityChange,components:t,singletons:e}),this.adapters.push(this.websocketAdapter)),await Promise.all(this.adapters.map(n=>n.init()))}sync(t){this.ecsAdapter.ctx=t;const e=[];for(const n of this.adapters)e.push(...n.pull());for(const n of this.adapters)n.push(e)}undo(){var t;return((t=this.historyAdapter)==null?void 0:t.undo())??!1}redo(){var t;return((t=this.historyAdapter)==null?void 0:t.redo())??!1}canUndo(){var t;return((t=this.historyAdapter)==null?void 0:t.canUndo())??!1}canRedo(){var t;return((t=this.historyAdapter)==null?void 0:t.canRedo())??!1}createCheckpoint(){var t;return((t=this.historyAdapter)==null?void 0:t.createCheckpoint())??null}revertToCheckpoint(t){var e;return((e=this.historyAdapter)==null?void 0:e.revertToCheckpoint(t))??!1}squashToCheckpoint(t){var e;return((e=this.historyAdapter)==null?void 0:e.squashToCheckpoint(t))??!1}onSettled(t,e){var n;(n=this.historyAdapter)==null||n.onSettled(t,e)}async connect(){this.websocketAdapter&&await this.websocketAdapter.reconnect()}disconnect(){this.websocketAdapter&&this.websocketAdapter.disconnect()}close(){for(const t of this.adapters)t.close()}},y2=Object.defineProperty,Ts=(t,e)=>{for(var n in e)y2(t,n,{get:e[n],enumerable:!0})},pi=le("drag-block"),w2=le("remove-block"),Xm=le("remove-selected"),Gm=le("bring-forward-selected"),Qm=le("send-backward-selected"),eg=le("clone-entities"),Iu=le("unclone-entities"),ja=le("set-cursor"),tg=le("cut"),ng=le("copy"),rg=le("paste"),Bu=le("select-block"),k2=le("deselect-block"),og=le("toggle-select"),mi=le("deselect-all"),sg=le("select-all"),ig=le("add-selection-box"),ag=le("update-selection-box"),lg=le("remove-selection-box"),cg=le("add-held"),ug=le("remove-held"),dg=le("add-transform-box"),Pu=le("update-transform-box"),fg=le("hide-transform-box"),hg=le("show-transform-box"),Nu=le("remove-transform-box"),pg=le("start-transform-box-edit"),v2=le("end-transform-box-edit"),mg={};Ts(mg,{DragStart:()=>it,EditAfterPlacing:()=>gi,Selected:()=>ht,SelectionBox:()=>Za,TransformBox:()=>Vt,TransformHandle:()=>ze});var it=He({name:"dragStart"},{position:E.tuple(E.float64(),2).default([0,0]),size:E.tuple(E.float64(),2).default([0,0]),rotateZ:E.float64().default(0),flip:E.tuple(E.boolean(),2).default([!1,!1]),fontSize:E.float64().default(16)}),gi=He({name:"editAfterPlacing"},{}),ht=He({name:"selected"},{}),Za=He({name:"selectionBox"},{}),Vt=He({name:"transformBox"},{}),b2=`
39
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of t.seen.entries()){const f=u[1];if(e===u[0]){s(u);continue}if(t.external){const p=(l=t.external.registry.get(u[0]))==null?void 0:l.id;if(e!==u[0]&&p){s(u);continue}}if((c=t.metadataRegistry.get(u[0]))==null?void 0:c.id){s(u);continue}if(f.cycle){s(u);continue}if(f.count>1&&t.reused==="ref"){s(u);continue}}}function _p(t,e){var i,a,l;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=c=>{const u=t.seen.get(c);if(u.ref===null)return;const f=u.def??u.schema,h={...f},p=u.ref;if(u.ref=null,p){r(p);const g=t.seen.get(p),y=g.schema;if(y.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(y)):Object.assign(f,y),Object.assign(f,h),c._zod.parent===p)for(const k in f)k==="$ref"||k==="allOf"||k in h||delete f[k];if(y.$ref&&g.def)for(const k in f)k==="$ref"||k==="allOf"||k in g.def&&JSON.stringify(f[k])===JSON.stringify(g.def[k])&&delete f[k]}const m=c._zod.parent;if(m&&m!==p){r(m);const g=t.seen.get(m);if(g!=null&&g.schema.$ref&&(f.$ref=g.schema.$ref,g.def))for(const y in f)y==="$ref"||y==="allOf"||y in g.def&&JSON.stringify(f[y])===JSON.stringify(g.def[y])&&delete f[y]}t.override({zodSchema:c,jsonSchema:f,path:u.path??[]})};for(const c of[...t.seen.entries()].reverse())r(c[0]);const o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,(i=t.external)!=null&&i.uri){const c=(a=t.external.registry.get(e))==null?void 0:a.id;if(!c)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(c)}Object.assign(o,n.def??n.schema);const s=((l=t.external)==null?void 0:l.defs)??{};for(const c of t.seen.entries()){const u=c[1];u.def&&u.defId&&(s[u.defId]=u.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...e["~standard"],jsonSchema:{input:Aa(e,"input",t.processors),output:Aa(e,"output",t.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function $t(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return $t(r.element,n);if(r.type==="set")return $t(r.valueType,n);if(r.type==="lazy")return $t(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return $t(r.innerType,n);if(r.type==="intersection")return $t(r.left,n)||$t(r.right,n);if(r.type==="record"||r.type==="map")return $t(r.keyType,n)||$t(r.valueType,n);if(r.type==="pipe")return $t(r.in,n)||$t(r.out,n);if(r.type==="object"){for(const o in r.shape)if($t(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if($t(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if($t(o,n))return!0;return!!(r.rest&&$t(r.rest,n))}return!1}const ix=(t,e={})=>n=>{const r=Mp({...n,processors:e});return Ke(t,r),Ap(r,t),_p(r,t)},Aa=(t,e,n={})=>r=>{const{libraryOptions:o,target:s}=r??{},i=Mp({...o??{},target:s,io:e,processors:n});return Ke(t,i),Ap(i,t),_p(i,t)},ax={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lx=(t,e,n,r)=>{const o=n;o.type="string";const{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:c}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=ax[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),c&&(o.contentEncoding=c),l&&l.size>0){const u=[...l];u.length===1?o.pattern=u[0].source:u.length>1&&(o.allOf=[...u.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},cx=(t,e,n,r)=>{const o=n,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number",typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u),typeof s=="number"&&(o.minimum=s,typeof u=="number"&&e.target!=="draft-04"&&(u>=s?delete o.minimum:delete o.exclusiveMinimum)),typeof c=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c),typeof i=="number"&&(o.maximum=i,typeof c=="number"&&e.target!=="draft-04"&&(c<=i?delete o.maximum:delete o.exclusiveMaximum)),typeof l=="number"&&(o.multipleOf=l)},ux=(t,e,n,r)=>{n.type="boolean"},dx=(t,e,n,r)=>{n.not={}},fx=(t,e,n,r)=>{},hx=(t,e,n,r)=>{const o=t._zod.def,s=Uh(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},px=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},mx=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},gx=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yx=(t,e,n,r)=>{const o=n,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Ke(s.element,e,{...r,path:[...r.path,"items"]})},wx=(t,e,n,r)=>{var c;const o=n,s=t._zod.def;o.type="object",o.properties={};const i=s.shape;for(const u in i)o.properties[u]=Ke(i[u],e,{...r,path:[...r.path,"properties",u]});const a=new Set(Object.keys(i)),l=new Set([...a].filter(u=>{const f=s.shape[u]._zod;return e.io==="input"?f.optin===void 0:f.optout===void 0}));l.size>0&&(o.required=Array.from(l)),((c=s.catchall)==null?void 0:c._zod.def.type)==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=Ke(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},kx=(t,e,n,r)=>{const o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,l)=>Ke(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",l]}));s?n.oneOf=i:n.anyOf=i},vx=(t,e,n,r)=>{const o=t._zod.def,s=Ke(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=Ke(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=l},bx=(t,e,n,r)=>{const o=n,s=t._zod.def;o.type="array";const i=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",l=s.items.map((h,p)=>Ke(h,e,{...r,path:[...r.path,i,p]})),c=s.rest?Ke(s.rest,e,{...r,path:[...r.path,a,...e.target==="openapi-3.0"?[s.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=l,c&&(o.items=c)):e.target==="openapi-3.0"?(o.items={anyOf:l},c&&o.items.anyOf.push(c),o.minItems=l.length,c||(o.maxItems=l.length)):(o.items=l,c&&(o.additionalItems=c));const{minimum:u,maximum:f}=t._zod.bag;typeof u=="number"&&(o.minItems=u),typeof f=="number"&&(o.maxItems=f)},Sx=(t,e,n,r)=>{const o=n,s=t._zod.def;o.type="object";const i=s.keyType,a=i._zod.bag,l=a==null?void 0:a.patterns;if(s.mode==="loose"&&l&&l.size>0){const u=Ke(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const f of l)o.patternProperties[f.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Ke(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Ke(s.valueType,e,{...r,path:[...r.path,"additionalProperties"]});const c=i._zod.values;if(c){const u=[...c].filter(f=>typeof f=="string"||typeof f=="number");u.length>0&&(o.required=u)}},Ex=(t,e,n,r)=>{const o=t._zod.def,s=Ke(o.innerType,e,r),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},Cx=(t,e,n,r)=>{const o=t._zod.def;Ke(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},xx=(t,e,n,r)=>{const o=t._zod.def;Ke(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},Tx=(t,e,n,r)=>{const o=t._zod.def;Ke(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Mx=(t,e,n,r)=>{const o=t._zod.def;Ke(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},Ax=(t,e,n,r)=>{const o=t._zod.def,s=e.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Ke(s,e,r);const i=e.seen.get(t);i.ref=s},_x=(t,e,n,r)=>{const o=t._zod.def;Ke(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0},Ip=(t,e,n,r)=>{const o=t._zod.def;Ke(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},Ix=B("ZodISODateTime",(t,e)=>{_E.init(t,e),He.init(t,e)});function Bx(t){return OC(Ix,t)}const Nx=B("ZodISODate",(t,e)=>{IE.init(t,e),He.init(t,e)});function Px(t){return RC(Nx,t)}const Dx=B("ZodISOTime",(t,e)=>{BE.init(t,e),He.init(t,e)});function Ox(t){return zC(Dx,t)}const Rx=B("ZodISODuration",(t,e)=>{NE.init(t,e),He.init(t,e)});function zx(t){return $C(Rx,t)}const pn=B("ZodError",(t,e)=>{qh.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>SS(t,n)},flatten:{value:n=>bS(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,jc,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,jc,2)}},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),$x=ka(pn),Lx=va(pn),Vx=ba(pn),Fx=Sa(pn),Wx=xS(pn),Ux=TS(pn),Hx=MS(pn),jx=AS(pn),Zx=_S(pn),Kx=IS(pn),Yx=BS(pn),qx=NS(pn),We=B("ZodType",(t,e)=>(Oe.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Aa(t,"input"),output:Aa(t,"output")}}),t.toJSONSchema=ix(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(jr(e,{checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),t.with=t.check,t.clone=(n,r)=>Zr(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>$x(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Vx(t,n,r),t.parseAsync=async(n,r)=>Lx(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Fx(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>Wx(t,n,r),t.decode=(n,r)=>Ux(t,n,r),t.encodeAsync=async(n,r)=>Hx(t,n,r),t.decodeAsync=async(n,r)=>jx(t,n,r),t.safeEncode=(n,r)=>Zx(t,n,r),t.safeDecode=(n,r)=>Kx(t,n,r),t.safeEncodeAsync=async(n,r)=>Yx(t,n,r),t.safeDecodeAsync=async(n,r)=>qx(t,n,r),t.refine=(n,r)=>t.check(jT(n,r)),t.superRefine=n=>t.check(ZT(n)),t.overwrite=n=>t.check(ks(n)),t.optional=()=>Rp(t),t.exactOptional=()=>BT(t),t.nullable=()=>zp(t),t.nullish=()=>Rp(zp(t)),t.nonoptional=n=>zT(t,n),t.array=()=>mn(t),t.or=n=>ST([t,n]),t.and=n=>CT(t,n),t.transform=n=>Lp(t,_T(n)),t.default=n=>DT(t,n),t.prefault=n=>RT(t,n),t.catch=n=>LT(t,n),t.pipe=n=>Lp(t,n),t.readonly=()=>WT(t),t.describe=n=>{const r=t.clone();return ci.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=ci.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return ci.get(t);const r=t.clone();return ci.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),Bp=B("_ZodString",(t,e)=>{Xc.init(t,e),We.init(t,e),t._zod.processJSONSchema=(r,o,s)=>lx(t,r,o);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(HC(...r)),t.includes=(...r)=>t.check(KC(...r)),t.startsWith=(...r)=>t.check(YC(...r)),t.endsWith=(...r)=>t.check(qC(...r)),t.min=(...r)=>t.check(Ma(...r)),t.max=(...r)=>t.check(xp(...r)),t.length=(...r)=>t.check(Tp(...r)),t.nonempty=(...r)=>t.check(Ma(1,...r)),t.lowercase=r=>t.check(jC(r)),t.uppercase=r=>t.check(ZC(r)),t.trim=()=>t.check(GC()),t.normalize=(...r)=>t.check(XC(...r)),t.toLowerCase=()=>t.check(JC()),t.toUpperCase=()=>t.check(QC()),t.slugify=()=>t.check(ex())}),Xx=B("ZodString",(t,e)=>{Xc.init(t,e),Bp.init(t,e),t.email=n=>t.check(pC(Gx,n)),t.url=n=>t.check(kC(Jx,n)),t.jwt=n=>t.check(DC(hT,n)),t.emoji=n=>t.check(vC(Qx,n)),t.guid=n=>t.check(bp(Np,n)),t.uuid=n=>t.check(mC(_a,n)),t.uuidv4=n=>t.check(gC(_a,n)),t.uuidv6=n=>t.check(yC(_a,n)),t.uuidv7=n=>t.check(wC(_a,n)),t.nanoid=n=>t.check(bC(eT,n)),t.guid=n=>t.check(bp(Np,n)),t.cuid=n=>t.check(SC(tT,n)),t.cuid2=n=>t.check(EC(nT,n)),t.ulid=n=>t.check(CC(rT,n)),t.base64=n=>t.check(BC(uT,n)),t.base64url=n=>t.check(NC(dT,n)),t.xid=n=>t.check(xC(oT,n)),t.ksuid=n=>t.check(TC(sT,n)),t.ipv4=n=>t.check(MC(iT,n)),t.ipv6=n=>t.check(AC(aT,n)),t.cidrv4=n=>t.check(_C(lT,n)),t.cidrv6=n=>t.check(IC(cT,n)),t.e164=n=>t.check(PC(fT,n)),t.datetime=n=>t.check(Bx(n)),t.date=n=>t.check(Px(n)),t.time=n=>t.check(Ox(n)),t.duration=n=>t.check(zx(n))});function dt(t){return hC(Xx,t)}const He=B("ZodStringFormat",(t,e)=>{Fe.init(t,e),Bp.init(t,e)}),Gx=B("ZodEmail",(t,e)=>{vE.init(t,e),He.init(t,e)}),Np=B("ZodGUID",(t,e)=>{wE.init(t,e),He.init(t,e)}),_a=B("ZodUUID",(t,e)=>{kE.init(t,e),He.init(t,e)}),Jx=B("ZodURL",(t,e)=>{bE.init(t,e),He.init(t,e)}),Qx=B("ZodEmoji",(t,e)=>{SE.init(t,e),He.init(t,e)}),eT=B("ZodNanoID",(t,e)=>{EE.init(t,e),He.init(t,e)}),tT=B("ZodCUID",(t,e)=>{CE.init(t,e),He.init(t,e)}),nT=B("ZodCUID2",(t,e)=>{xE.init(t,e),He.init(t,e)}),rT=B("ZodULID",(t,e)=>{TE.init(t,e),He.init(t,e)}),oT=B("ZodXID",(t,e)=>{ME.init(t,e),He.init(t,e)}),sT=B("ZodKSUID",(t,e)=>{AE.init(t,e),He.init(t,e)}),iT=B("ZodIPv4",(t,e)=>{PE.init(t,e),He.init(t,e)}),aT=B("ZodIPv6",(t,e)=>{DE.init(t,e),He.init(t,e)}),lT=B("ZodCIDRv4",(t,e)=>{OE.init(t,e),He.init(t,e)}),cT=B("ZodCIDRv6",(t,e)=>{RE.init(t,e),He.init(t,e)}),uT=B("ZodBase64",(t,e)=>{zE.init(t,e),He.init(t,e)}),dT=B("ZodBase64URL",(t,e)=>{LE.init(t,e),He.init(t,e)}),fT=B("ZodE164",(t,e)=>{VE.init(t,e),He.init(t,e)}),hT=B("ZodJWT",(t,e)=>{WE.init(t,e),He.init(t,e)}),Pp=B("ZodNumber",(t,e)=>{ap.init(t,e),We.init(t,e),t._zod.processJSONSchema=(r,o,s)=>cx(t,r,o),t.gt=(r,o)=>t.check(Ep(r,o)),t.gte=(r,o)=>t.check(Qc(r,o)),t.min=(r,o)=>t.check(Qc(r,o)),t.lt=(r,o)=>t.check(Sp(r,o)),t.lte=(r,o)=>t.check(Jc(r,o)),t.max=(r,o)=>t.check(Jc(r,o)),t.int=r=>t.check(Dp(r)),t.safe=r=>t.check(Dp(r)),t.positive=r=>t.check(Ep(0,r)),t.nonnegative=r=>t.check(Qc(0,r)),t.negative=r=>t.check(Sp(0,r)),t.nonpositive=r=>t.check(Jc(0,r)),t.multipleOf=(r,o)=>t.check(Cp(r,o)),t.step=(r,o)=>t.check(Cp(r,o)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Je(t){return LC(Pp,t)}const pT=B("ZodNumberFormat",(t,e)=>{UE.init(t,e),Pp.init(t,e)});function Dp(t){return VC(pT,t)}const mT=B("ZodBoolean",(t,e)=>{HE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ux(t,n,r)});function Lt(t){return FC(mT,t)}const gT=B("ZodUnknown",(t,e)=>{jE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fx()});function Ia(){return WC(gT)}const yT=B("ZodNever",(t,e)=>{ZE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>dx(t,n,r)});function wT(t){return UC(yT,t)}const kT=B("ZodArray",(t,e)=>{KE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yx(t,n,r,o),t.element=e.element,t.min=(n,r)=>t.check(Ma(n,r)),t.nonempty=n=>t.check(Ma(1,n)),t.max=(n,r)=>t.check(xp(n,r)),t.length=(n,r)=>t.check(Tp(n,r)),t.unwrap=()=>t.element});function mn(t,e){return tx(kT,t,e)}const vT=B("ZodObject",(t,e)=>{qE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wx(t,n,r,o),xe(t,"shape",()=>e.shape),t.keyof=()=>tu(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ia()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ia()}),t.strict=()=>t.clone({...t._zod.def,catchall:wT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>gS(t,n),t.safeExtend=n=>yS(t,n),t.merge=n=>wS(t,n),t.pick=n=>pS(t,n),t.omit=n=>mS(t,n),t.partial=(...n)=>kS(Op,t,n[0]),t.required=(...n)=>vS($p,t,n[0])});function qt(t,e){const n={type:"object",shape:t??{},...te(e)};return new vT(n)}const bT=B("ZodUnion",(t,e)=>{XE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>kx(t,n,r,o),t.options=e.options});function ST(t,e){return new bT({type:"union",options:t,...te(e)})}const ET=B("ZodIntersection",(t,e)=>{GE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vx(t,n,r,o)});function CT(t,e){return new ET({type:"intersection",left:t,right:e})}const xT=B("ZodTuple",(t,e)=>{hp.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bx(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function Ba(t,e,n){const r=e instanceof Oe,o=r?n:e,s=r?e:null;return new xT({type:"tuple",items:t,rest:s,...te(o)})}const TT=B("ZodRecord",(t,e)=>{JE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Sx(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function MT(t,e,n){return new TT({type:"record",keyType:t,valueType:e,...te(n)})}const eu=B("ZodEnum",(t,e)=>{QE.init(t,e),We.init(t,e),t._zod.processJSONSchema=(r,o,s)=>hx(t,r,o),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{const s={};for(const i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new eu({...e,checks:[],...te(o),entries:s})},t.exclude=(r,o)=>{const s={...e.entries};for(const i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new eu({...e,checks:[],...te(o),entries:s})}});function tu(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new eu({type:"enum",entries:n,...te(e)})}const AT=B("ZodTransform",(t,e)=>{eC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gx(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Fh(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(li(s,n.value,e));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),n.issues.push(li(i))}};const o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function _T(t){return new AT({type:"transform",transform:t})}const Op=B("ZodOptional",(t,e)=>{mp.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ip(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Rp(t){return new Op({type:"optional",innerType:t})}const IT=B("ZodExactOptional",(t,e)=>{tC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ip(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function BT(t){return new IT({type:"optional",innerType:t})}const NT=B("ZodNullable",(t,e)=>{nC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ex(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function zp(t){return new NT({type:"nullable",innerType:t})}const PT=B("ZodDefault",(t,e)=>{rC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function DT(t,e){return new PT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Kh(e)}})}const OT=B("ZodPrefault",(t,e)=>{oC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Tx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function RT(t,e){return new OT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Kh(e)}})}const $p=B("ZodNonOptional",(t,e)=>{sC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Cx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function zT(t,e){return new $p({type:"nonoptional",innerType:t,...te(e)})}const $T=B("ZodCatch",(t,e)=>{iC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Mx(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function LT(t,e){return new $T({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const VT=B("ZodPipe",(t,e)=>{aC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ax(t,n,r,o),t.in=e.in,t.out=e.out});function Lp(t,e){return new VT({type:"pipe",in:t,out:e})}const FT=B("ZodReadonly",(t,e)=>{lC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_x(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function WT(t){return new FT({type:"readonly",innerType:t})}const UT=B("ZodFunction",(t,e)=>{cC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mx(t,n)});function HT(t){return new UT({type:"function",input:Array.isArray(t==null?void 0:t.input)?Ba(t==null?void 0:t.input):(t==null?void 0:t.input)??mn(Ia()),output:(t==null?void 0:t.output)??Ia()})}const Vp=B("ZodCustom",(t,e)=>{uC.init(t,e),We.init(t,e),t._zod.processJSONSchema=(n,r,o)=>px(t,n)});function gn(t,e){return nx(Vp,()=>!0,e)}function jT(t,e={}){return rx(Vp,t,e)}function ZT(t){return ox(t)}function KT(t){const e=YT(t.chars),n=qT(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=XT(r,e.length);return{chars:t.chars,byChar:e.byChar,byCode:e.byCode,length:e.length,first:e.byCode[0],last:e.byCode[e.length-1],firstPositive:n.firstPositive,mostPositive:n.mostPositive,firstNegative:n.firstNegative,mostNegative:n.mostNegative,jitterRange:r,paddingDict:o}}function YT(t){const e={},n={},r=t.length;for(let o=0;o<r;o++){const s=t[o];e[o]=s,n[s]=o}return{byCode:e,byChar:n,length:r}}function qT(t,e,n,r){const o=t.byChar[e],s=t.byChar[n],i=t.byChar[r];if(o===void 0||s===void 0||i===void 0)throw new Error("invalid charSet");if(s-o<3)throw new Error("mostPositive must be at least 3 characters away from neutral");if(o-i<3)throw new Error("mostNegative must be at least 3 characters away from neutral");return{firstPositive:t.byCode[o],mostPositive:t.byCode[s],firstNegative:t.byCode[o-1],mostNegative:t.byCode[i]}}function XT(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var nu=null;function Fp(){return nu||(nu=KT({chars:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",firstPositive:"a",mostPositive:"z",mostNegative:"A"}))}function Yr(t,e,n){const r=n.byChar[t],o=n.byChar[e];return Math.abs(r-o)}function ru(t,e){const n=t[0];if(n>e.mostPositive||n<e.mostNegative)throw new Error("invalid firstChar on key");return n===e.mostPositive?Yr(n,e.firstPositive,e)+1+Na(t.slice(1),"positive",e):n===e.mostNegative?Yr(n,e.firstNegative,e)+1+Na(t.slice(1),"negative",e):n>=e.firstPositive?Yr(n,e.firstPositive,e)+2:Yr(n,e.firstNegative,e)+2}function Na(t,e,n){const r=t[0];if(r>n.mostPositive||r<n.mostNegative)throw new Error("invalid firstChar on key");return r===n.mostPositive&&e==="positive"?Yr(r,n.mostNegative,n)+1+Na(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?Yr(r,n.mostPositive,n)+1+Na(t.slice(1),e,n):e==="positive"?Yr(r,n.mostNegative,n)+2:Yr(r,n.mostPositive,n)+2}function Pa(t,e,n,r,o){const s=Math.max(t.length,e.length);return n==="start"?[t.padStart(s,r),e.padStart(s,r)]:[t.padEnd(s,r),e.padEnd(s,r)]}function GT(t,e,n){let[r,o]=Pa(t,e,"end",n.first),s=ou(r,o,n);s===1&&(r=r.padEnd(r.length+1,n.first),s=n.length);const i=Hp(Math.floor(s/2),n);return su(r,i,n)}function ou(t,e,n){const[r,o]=Pa(t,e,"end",n.first).sort(),s=Wp(o,r,n);return JT(s,n)}function su(t,e,n){const r=n.length,[o,s]=Pa(t,e,"start",n.first),i=[];let a=0;for(let l=o.length-1;l>=0;l--){const c=n.byChar[o[l]],u=n.byChar[s[l]],f=c+u+a;a=Math.floor(f/r);const h=f%r;i.unshift(n.byCode[h])}return a>0&&i.unshift(n.byCode[a]),i.join("")}function Wp(t,e,n,r=!0){const o=n.length,[s,i]=Pa(t,e,"start",n.first),a=[];let l=0;for(let c=s.length-1;c>=0;c--){let u=n.byChar[s[c]];const f=n.byChar[i[c]]+l;u<f?(l=1,u+=o):l=0;const h=u-f;a.unshift(n.byCode[h])}if(l>0)throw new Error("Subtraction result is negative. Ensure a is greater than or equal to b.");for(;r&&a.length>1&&a[0]===n.first;)a.shift();return a.join("")}function Up(t,e){return su(t,e.byCode[1],e)}function iu(t,e){return Wp(t,e.byCode[1],e,!1)}function Hp(t,e){if(t===0)return e.byCode[0];let n="";const r=e.length;for(;t>0;)n=e.byCode[t%r]+n,t=Math.floor(t/r);return n}function JT(t,e){let n=0;const r=t.length,o=e.length;for(let s=0;s<r;s++)n+=e.byChar[t[s]]*Math.pow(o,r-s-1);return n}function QT(t){return t.firstPositive+t.byCode[0]}function eM(t,e){return ru(t,e)===t.length}function jp(t,e){Da(t,e)}function Da(t,e){const n=Yp(t,e),r=ru(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function Zp(t,e){if(!eM(t,e))throw new Error("invalid integer length: "+t)}function Kp(t,e){Zp(t,e);const[n,r]=qp(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=Up(r,e);return n+i}const s=nM(n,e);return Xp(s,"lower",e)}function tM(t,e){Zp(t,e);const[n,r]=qp(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=iu(r,e);return n+i}const s=rM(n,e);return Xp(s,"upper",e)}function Yp(t,e){let n=0;if(t[0]===e.mostPositive)for(;t[n]===e.mostPositive;)n=n+1;if(t[0]===e.mostNegative)for(;t[n]===e.mostNegative;)n=n+1;return t.slice(0,n+1)}function qp(t,e){const n=Yp(t,e),r=t.slice(n.length);return[n,r]}function nM(t,e){const n=t>=e.firstPositive,r=Up(t,e),o=t[t.length-1]===e.mostPositive,s=r[r.length-1]===e.mostPositive;return n&&s?r+e.mostNegative:!n&&o?t.slice(0,t.length-1):r}function rM(t,e){const n=t>=e.firstPositive,r=t[t.length-1]===e.mostNegative;if(n&&r){const o=t.slice(0,t.length-1);return iu(o,e)}return!n&&r?t+e.mostPositive:iu(t,e)}function Xp(t,e,n){const r=ru(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function Gp(t,e){const n=Hp(Math.floor(Math.random()*e.jitterRange),e);return su(t,n,e)}function oM(t,e,n){const r=t.padEnd(t.length+e,n.first);return Gp(r,n)}function sM(t,e,n){const r=Da(t,n),o=Kp(r,n);let s=0;if(e!==null){const a=ou(t,e,n);a<n.jitterRange+1&&(s=Math.max(s,Jp(a,n)))}const i=ou(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,Jp(i,n))),s}function Jp(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function iM(t,e,n=Fp()){if(t!==null&&jp(t,n),e!==null&&jp(e,n),t===null&&e===null)return QT(n);if(t===null){const r=Da(e,n);return tM(r,n)}if(e===null){const r=Da(t,n);return Kp(r,n)}if(t>=e)throw new Error(t+" >= "+e);return GT(t,e,n)}function Oa(t,e,n=Fp()){const r=iM(t,e,n),o=sM(r,e,n);return o?oM(r,o,n):Gp(r,n)}function aM(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function lM(){const t=aM();if(t.__xstate__)return t.__xstate__}const cM=t=>{if(typeof window>"u")return;const e=lM();e&&e.register(t)};class Qp{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(e){const n={value:e,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const e=this._current;this._process(e.value),this._current=e.next}this._last=null}}const em=".",uM="",tm="",dM="#",fM="*",nm="xstate.init",hM="xstate.error",au="xstate.stop";function pM(t,e){return{type:`xstate.after.${t}.${e}`}}function lu(t,e){return{type:`xstate.done.state.${t}`,output:e}}function mM(t,e){return{type:`xstate.done.actor.${t}`,output:e,actorId:t}}function rm(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function om(t){return{type:nm,input:t}}function tr(t){setTimeout(()=>{throw t})}const gM=typeof Symbol=="function"&&Symbol.observable||"@@observable";function sm(t,e){const n=im(t),r=im(e);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(o=>o in r?sm(n[o],r[o]):!1)}function cu(t){if(cm(t))return t;const e=[];let n="";for(let r=0;r<t.length;r++){switch(t.charCodeAt(r)){case 92:n+=t[r+1],r++;continue;case 46:e.push(n),n="";continue}n+=t[r]}return e.push(n),e}function im(t){if(GM(t))return t.value;if(typeof t!="string")return t;const e=cu(t);return yM(e)}function yM(t){if(t.length===1)return t[0];const e={};let n=e;for(let r=0;r<t.length-1;r++)if(r===t.length-2)n[t[r]]=t[r+1];else{const o=n;n={},o[t[r]]=n}return e}function am(t,e){const n={},r=Object.keys(t);for(let o=0;o<r.length;o++){const s=r[o];n[s]=e(t[s],s,t,o)}return n}function lm(t){return cm(t)?t:[t]}function qr(t){return t===void 0?[]:lm(t)}function uu(t,e,n,r){return typeof t=="function"?t({context:e,event:n,self:r}):t}function cm(t){return Array.isArray(t)}function wM(t){return t.type.startsWith("xstate.error.actor")}function vs(t){return lm(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function um(t){if(!(t===void 0||t===uM))return qr(t)}function du(t,e,n){var s,i,a;const r=typeof t=="object",o=r?t:void 0;return{next:(s=r?t.next:t)==null?void 0:s.bind(o),error:(i=r?t.error:e)==null?void 0:i.bind(o),complete:(a=r?t.complete:n)==null?void 0:a.bind(o)}}function dm(t,e){return`${e}.${t}`}function fu(t,e){const n=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return t.implementations.actors[e];const[,r,o]=n,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[r]:i).src}function kM(t,e){if(e===t||e===fM)return!0;if(!e.endsWith(".*"))return!1;const n=e.split("."),r=t.split(".");for(let o=0;o<n.length;o++){const s=n[o],i=r[o];if(s==="*")return o===n.length-1;if(s!==i)return!1}return!0}function fm(t,e){return`${t.sessionId}.${e}`}let vM=0;function bM(t,e){const n=new Map,r=new Map,o=new WeakMap,s=new Set,i={},{clock:a,logger:l}=e,c={schedule:(h,p,m,g,y=Math.random().toString(36).slice(2))=>{const w={source:h,target:p,event:m,delay:g,id:y,startedAt:Date.now()},k=fm(h,y);f._snapshot._scheduledEvents[k]=w;const b=a.setTimeout(()=>{delete i[k],delete f._snapshot._scheduledEvents[k],f._relay(h,p,m)},g);i[k]=b},cancel:(h,p)=>{const m=fm(h,p),g=i[m];delete i[m],delete f._snapshot._scheduledEvents[m],g!==void 0&&a.clearTimeout(g)},cancelAll:h=>{for(const p in f._snapshot._scheduledEvents){const m=f._snapshot._scheduledEvents[p];m.source===h&&c.cancel(h,m.id)}}},u=h=>{if(!s.size)return;const p={...h,rootId:t.sessionId};s.forEach(m=>{var g;return(g=m.next)==null?void 0:g.call(m,p)})},f={_snapshot:{_scheduledEvents:((e==null?void 0:e.snapshot)&&e.snapshot.scheduler)??{}},_bookId:()=>`x:${vM++}`,_register:(h,p)=>(n.set(h,p),h),_unregister:h=>{n.delete(h.sessionId);const p=o.get(h);p!==void 0&&(r.delete(p),o.delete(h))},get:h=>r.get(h),getAll:()=>Object.fromEntries(r.entries()),_set:(h,p)=>{const m=r.get(h);if(m&&m!==p)throw new Error(`Actor with system ID '${h}' already exists.`);r.set(h,p),o.set(p,h)},inspect:h=>{const p=du(h);return s.add(p),{unsubscribe(){s.delete(p)}}},_sendInspectionEvent:u,_relay:(h,p,m)=>{f._sendInspectionEvent({type:"@xstate.event",sourceRef:h,actorRef:p,event:m}),p._send(m)},scheduler:c,getSnapshot:()=>({_scheduledEvents:{...f._snapshot._scheduledEvents}}),start:()=>{const h=f._snapshot._scheduledEvents;f._snapshot._scheduledEvents={};for(const p in h){const{source:m,target:g,event:y,delay:w,id:k}=h[p];c.schedule(m,g,y,w,k)}},_clock:a,_logger:l};return f}let hu=!1;const pu=1;let Xt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const SM={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class EM{constructor(e,n){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Qp(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Xt.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const r={...SM,...n},{clock:o,logger:s,parent:i,syncSnapshot:a,id:l,systemId:c,inspect:u}=r;this.system=i?i.system:bM(this,{clock:o,logger:s}),u&&!i&&this.system.inspect(du(u)),this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=(n==null?void 0:n.logger)??this.system._logger,this.clock=(n==null?void 0:n.clock)??this.system._clock,this._parent=i,this._syncSnapshot=a,this.options=r,this.src=r.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:f=>{this._deferred.push(f)},system:this.system,stopChild:f=>{if(f._parent!==this)throw new Error(`Cannot stop child actor ${f.id} of ${this.id} because it is not a child`);f._stop()},emit:f=>{const h=this.eventListeners.get(f.type),p=this.eventListeners.get("*");if(!h&&!p)return;const m=[...h?h.values():[],...p?p.values():[]];for(const g of m)try{g(f)}catch(y){tr(y)}},actionExecutor:f=>{const h=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:f.type,params:f.params}}),!f.exec)return;const p=hu;try{hu=!0,f.exec(f.info,f.params)}finally{hu=p}};this._processingStatus===Xt.Running?h():this._deferred.push(h)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),c&&(this.systemId=c,this.system._set(c,this)),this._initState((n==null?void 0:n.snapshot)??(n==null?void 0:n.state)),c&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(e){var n;try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,(n=this.options)==null?void 0:n.input)}catch(r){this._snapshot={status:"error",output:void 0,error:r}}}update(e,n){var o,s;this._snapshot=e;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...e,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{(o=i.next)==null||o.call(i,e)}catch(a){tr(a)}break;case"done":for(const i of this.observers)try{(s=i.next)==null||s.call(i,e)}catch(a){tr(a)}this._stopProcedure(),this._complete(),this._doneEvent=mM(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:e})}subscribe(e,n,r){var s;const o=du(e,n,r);if(this._processingStatus!==Xt.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{(s=o.complete)==null||s.call(o)}catch(i){tr(i)}break;case"error":{const i=this._snapshot.error;if(!o.error)tr(i);else try{o.error(i)}catch(a){tr(a)}break}}return{unsubscribe:()=>{this.observers.delete(o)}}}on(e,n){let r=this.eventListeners.get(e);r||(r=new Set,this.eventListeners.set(e,r));const o=n.bind(void 0);return r.add(o),{unsubscribe:()=>{r.delete(o)}}}start(){if(this._processingStatus===Xt.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=Xt.Running;const e=om(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case"done":return this.update(this._snapshot,e),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let n,r;try{n=this.logic.transition(this._snapshot,e,this._actorScope)}catch(o){r={err:o}}if(r){const{err:o}=r;this._snapshot={...this._snapshot,status:"error",error:o},this._error(o);return}this.update(n,e),e.type===au&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Xt.Stopped?this:(this.mailbox.clear(),this._processingStatus===Xt.NotStarted?(this._processingStatus=Xt.Stopped,this):(this.mailbox.enqueue({type:au}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var e;for(const n of this.observers)try{(e=n.complete)==null||e.call(n)}catch(r){tr(r)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||tr(e),this.eventListeners.clear();return}let n=!1;for(const r of this.observers){const o=r.error;n||(n=!o);try{o==null||o(e)}catch(s){tr(s)}}this.observers.clear(),this.eventListeners.clear(),n&&tr(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,rm(this.id,e))}_stopProcedure(){return this._processingStatus!==Xt.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Qp(this._process.bind(this)),this._processingStatus=Xt.Stopped,this.system._unregister(this),this)}_send(e){this._processingStatus!==Xt.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}attachDevTools(){const{devTools:e}=this.options;e&&(typeof e=="function"?e:cM)(this)}toJSON(){return{xstate$$type:pu,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[gM](){return this}getSnapshot(){return this._snapshot}}function ui(t,...[e]){return new EM(t,e)}function CM(t,e,n,r,{sendId:o}){const s=typeof o=="function"?o(n,r):o;return[e,{sendId:s},void 0]}function xM(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function mu(t){function e(n,r){}return e.type="xstate.cancel",e.sendId=t,e.resolve=CM,e.execute=xM,e}function TM(t,e,n,r,{id:o,systemId:s,src:i,input:a,syncSnapshot:l}){const c=typeof i=="string"?fu(e.machine,i):i,u=typeof o=="function"?o(n):o;let f,h;return c&&(h=typeof a=="function"?a({context:e.context,event:n.event,self:t.self}):a,f=ui(c,{id:u,src:i,parent:t.self,syncSnapshot:l,systemId:s,input:h})),[Io(e,{children:{...e.children,[u]:f}}),{id:o,systemId:s,actorRef:f,src:i,input:h},void 0]}function MM(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==Xt.Stopped&&e.start()})}function gu(...[t,{id:e,systemId:n,input:r,syncSnapshot:o=!1}={}]){function s(i,a){}return s.type="xstate.spawnChild",s.id=e,s.systemId=n,s.src=t,s.input=r,s.syncSnapshot=o,s.resolve=TM,s.execute=MM,s}function AM(t,e,n,r,{actorRef:o}){const s=typeof o=="function"?o(n,r):o,i=typeof s=="string"?e.children[s]:s;let a=e.children;return i&&(a={...a},delete a[i.id]),[Io(e,{children:a}),i,void 0]}function hm(t,e){const n=e.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))hm(t,r);t.system._unregister(e)}function _M(t,e){if(e){if(hm(t,e),e._processingStatus!==Xt.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function Ra(t){function e(n,r){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=AM,e.execute=_M,e}function IM(t,{context:e,event:n},{guards:r}){return!bs(r[0],e,n,t)}function Mo(t){function e(n,r){return!1}return e.check=IM,e.guards=[t],e}function BM(t,{context:e,event:n},{guards:r}){return r.every(o=>bs(o,e,n,t))}function di(t){function e(n,r){return!1}return e.check=BM,e.guards=t,e}function bs(t,e,n,r){const{machine:o}=r,s=typeof t=="function",i=s?t:o.implementations.guards[typeof t=="string"?t:t.type];if(!s&&!i)throw new Error(`Guard '${typeof t=="string"?t:t.type}' is not implemented.'.`);if(typeof i!="function")return bs(i,e,n,r);const a={context:e,event:n},l=s||typeof t=="string"?void 0:"params"in t?typeof t.params=="function"?t.params({context:e,event:n}):t.params:void 0;return"check"in i?i.check(r,a,i):i(a,l)}const yu=t=>t.type==="atomic"||t.type==="final";function Ss(t){return Object.values(t.states).filter(e=>e.type!=="history")}function fi(t,e){const n=[];if(e===t)return n;let r=t.parent;for(;r&&r!==e;)n.push(r),r=r.parent;return n}function za(t){const e=new Set(t),n=mm(e);for(const r of e)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))wm(r).forEach(o=>e.add(o));else if(r.type==="parallel"){for(const o of Ss(r))if(o.type!=="history"&&!e.has(o)){const s=wm(o);for(const i of s)e.add(i)}}for(const r of e){let o=r.parent;for(;o;)e.add(o),o=o.parent}return e}function pm(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const o=n[0];if(o){if(yu(o))return o.key}else return{}}const r={};for(const o of n)r[o.key]=pm(o,e);return r}function mm(t){const e=new Map;for(const n of t)e.has(n)||e.set(n,[]),n.parent&&(e.has(n.parent)||e.set(n.parent,[]),e.get(n.parent).push(n));return e}function gm(t,e){const n=za(e);return pm(t,mm(n))}function wu(t,e){return e.type==="compound"?Ss(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?Ss(e).every(n=>wu(t,n)):e.type==="final"}const $a=t=>t[0]===dM;function NM(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(r=>kM(e,r)).sort((r,o)=>o.length-r.length).flatMap(r=>t.transitions.get(r))}function PM(t){const e=t.config.after;if(!e)return[];const n=o=>{const s=pM(o,t.id),i=s.type;return t.entry.push(Wa(s,{id:i,delay:o})),t.exit.push(mu(i)),i};return Object.keys(e).flatMap(o=>{const s=e[o],i=typeof s=="string"?{target:s}:s,a=Number.isNaN(+o)?o:+o,l=n(a);return qr(i).map(c=>({...c,event:l,delay:a}))}).map(o=>{const{delay:s}=o;return{...Ao(t,o.event,o),delay:s}})}function Ao(t,e,n){const r=um(n.target),o=n.reenter??!1,s=RM(t,r),i={...n,actions:qr(n.actions),guard:n.guard,target:s,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:s?s.map(a=>`#${a.id}`):void 0})};return i}function DM(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===tm)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=t.config.on[n];e.set(n,vs(r).map(o=>Ao(t,n,o)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,vs(t.config.onDone).map(r=>Ao(t,n,r)))}for(const n of t.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;e.set(r,vs(n.onDone).map(o=>Ao(t,r,o)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;e.set(r,vs(n.onError).map(o=>Ao(t,r,o)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;e.set(r,vs(n.onSnapshot).map(o=>Ao(t,r,o)))}}for(const n of t.after){let r=e.get(n.eventType);r||(r=[],e.set(n.eventType,r)),r.push(n)}return e}function OM(t,e){const n=typeof e=="string"?t.states[e]:e?t.states[e.target]:void 0;if(!n&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const r={source:t,actions:!e||typeof e=="string"?[]:qr(e.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${t.id}`,target:n?[`#${n.id}`]:[]})};return r}function RM(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if($a(n))return t.machine.getStateNodeById(n);const r=n[0]===em;if(r&&!t.parent)return La(t,n.slice(1));const o=r?t.key+n:n;if(t.parent)try{return La(t.parent,o)}catch(s){throw new Error(`Invalid transition definition for state node '${t.id}':
40
+ ${s.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function ym(t){const e=um(t.config.target);return e?{target:e.map(n=>typeof n=="string"?La(t.parent,n):n)}:t.parent.initial}function _o(t){return t.type==="history"}function wm(t){const e=km(t);for(const n of e)for(const r of fi(n,t))e.add(r);return e}function km(t){const e=new Set;function n(r){if(!e.has(r)){if(e.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const o of Ss(r))n(o)}}return n(t),e}function Es(t,e){if($a(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function La(t,e){if(typeof e=="string"&&$a(e))try{return t.machine.getStateNodeById(e)}catch{}const n=cu(e).slice();let r=t;for(;n.length;){const o=n.shift();if(!o.length)break;r=Es(r,o)}return r}function Va(t,e){if(typeof e=="string"){const o=t.states[e];if(!o)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,o]}const n=Object.keys(e),r=n.map(o=>Es(t,o)).filter(Boolean);return[t.machine.root,t].concat(r,n.reduce((o,s)=>{const i=Es(t,s);if(!i)return o;const a=Va(i,e[s]);return o.concat(a)},[]))}function zM(t,e,n,r){const s=Es(t,e).next(n,r);return!s||!s.length?t.next(n,r):s}function $M(t,e,n,r){const o=Object.keys(e),s=Es(t,o[0]),i=ku(s,e[o[0]],n,r);return!i||!i.length?t.next(n,r):i}function LM(t,e,n,r){const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)continue;const a=Es(t,s),l=ku(a,i,n,r);l&&o.push(...l)}return o.length?o:t.next(n,r)}function ku(t,e,n,r){return typeof e=="string"?zM(t,e,n,r):Object.keys(e).length===1?$M(t,e,n,r):LM(t,e,n,r)}function VM(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function Xr(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function FM(t,e){const n=new Set(t),r=new Set(e);for(const o of n)if(r.has(o))return!0;for(const o of r)if(n.has(o))return!0;return!1}function vm(t,e,n){const r=new Set;for(const o of t){let s=!1;const i=new Set;for(const a of r)if(FM(bu([o],e,n),bu([a],e,n)))if(Xr(o.source,a.source))i.add(a);else{s=!0;break}if(!s){for(const a of i)r.delete(a);r.add(o)}}return Array.from(r)}function WM(t){const[e,...n]=t;for(const r of fi(e,void 0))if(n.every(o=>Xr(o,r)))return r}function vu(t,e){if(!t.target)return[];const n=new Set;for(const r of t.target)if(_o(r))if(e[r.id])for(const o of e[r.id])n.add(o);else for(const o of vu(ym(r),e))n.add(o);else n.add(r);return[...n]}function bm(t,e){const n=vu(t,e);if(!n)return;if(!t.reenter&&n.every(o=>o===t.source||Xr(o,t.source)))return t.source;const r=WM(n.concat(t.source));if(r)return r;if(!t.reenter)return t.source.machine.root}function bu(t,e,n){var o;const r=new Set;for(const s of t)if((o=s.target)!=null&&o.length){const i=bm(s,n);s.reenter&&s.source===i&&r.add(i);for(const a of e)Xr(a,i)&&r.add(a)}return[...r]}function UM(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function Su(t,e,n,r,o,s){if(!t.length)return e;const i=new Set(e._nodes);let a=e.historyValue;const l=vm(t,i,a);let c=e;o||([c,a]=KM(c,r,n,l,i,a,s,n.actionExecutor)),c=xs(c,r,n,l.flatMap(f=>f.actions),s,void 0),c=jM(c,r,n,l,i,s,a,o);const u=[...i];c.status==="done"&&(c=xs(c,r,n,u.sort((f,h)=>h.order-f.order).flatMap(f=>f.exit),s,void 0));try{return a===e.historyValue&&UM(e._nodes,i)?c:Io(c,{_nodes:u,historyValue:a})}catch(f){throw f}}function HM(t,e,n,r,o){if(r.output===void 0)return;const s=lu(o.id,o.output!==void 0&&o.parent?uu(o.output,t.context,e,n.self):void 0);return uu(r.output,t.context,s,n.self)}function jM(t,e,n,r,o,s,i,a){let l=t;const c=new Set,u=new Set;ZM(r,i,u,c),a&&u.add(t.machine.root);const f=new Set;for(const h of[...c].sort((p,m)=>p.order-m.order)){o.add(h);const p=[];p.push(...h.entry);for(const m of h.invoke)p.push(gu(m.src,{...m,syncSnapshot:!!m.onSnapshot}));if(u.has(h)){const m=h.initial.actions;p.push(...m)}if(l=xs(l,e,n,p,s,h.invoke.map(m=>m.id)),h.type==="final"){const m=h.parent;let g=(m==null?void 0:m.type)==="parallel"?m:m==null?void 0:m.parent,y=g||h;for((m==null?void 0:m.type)==="compound"&&s.push(lu(m.id,h.output!==void 0?uu(h.output,l.context,e,n.self):void 0));(g==null?void 0:g.type)==="parallel"&&!f.has(g)&&wu(o,g);)f.add(g),s.push(lu(g.id)),y=g,g=g.parent;if(g)continue;l=Io(l,{status:"done",output:HM(l,e,n,l.machine.root,y)})}}return l}function ZM(t,e,n,r){for(const o of t){const s=bm(o,e);for(const a of o.target||[])!_o(a)&&(o.source!==a||o.source!==s||o.reenter)&&(r.add(a),n.add(a)),Cs(a,e,n,r);const i=vu(o,e);for(const a of i){const l=fi(a,s);(s==null?void 0:s.type)==="parallel"&&l.push(s),Sm(r,e,n,l,!o.source.parent&&o.reenter?void 0:s)}}}function Cs(t,e,n,r){var o;if(_o(t))if(e[t.id]){const s=e[t.id];for(const i of s)r.add(i),Cs(i,e,n,r);for(const i of s)Eu(i,t.parent,r,e,n)}else{const s=ym(t);for(const i of s.target)r.add(i),s===((o=t.parent)==null?void 0:o.initial)&&n.add(t.parent),Cs(i,e,n,r);for(const i of s.target)Eu(i,t.parent,r,e,n)}else if(t.type==="compound"){const[s]=t.initial.target;_o(s)||(r.add(s),n.add(s)),Cs(s,e,n,r),Eu(s,t,r,e,n)}else if(t.type==="parallel")for(const s of Ss(t).filter(i=>!_o(i)))[...r].some(i=>Xr(i,s))||(_o(s)||(r.add(s),n.add(s)),Cs(s,e,n,r))}function Sm(t,e,n,r,o){for(const s of r)if((!o||Xr(s,o))&&t.add(s),s.type==="parallel")for(const i of Ss(s).filter(a=>!_o(a)))[...t].some(a=>Xr(a,i))||(t.add(i),Cs(i,e,n,t))}function Eu(t,e,n,r,o){Sm(n,r,o,fi(t,e))}function KM(t,e,n,r,o,s,i,a){let l=t;const c=bu(r,o,s);c.sort((f,h)=>h.order-f.order);let u;for(const f of c)for(const h of VM(f)){let p;h.history==="deep"?p=m=>yu(m)&&Xr(m,f):p=m=>m.parent===f,u??(u={...s}),u[h.id]=Array.from(o).filter(p)}for(const f of c)l=xs(l,e,n,[...f.exit,...f.invoke.map(h=>Ra(h.id))],i,void 0),o.delete(f);return[l,u||s]}function YM(t,e){return t.implementations.actions[e]}function Em(t,e,n,r,o,s){const{machine:i}=t;let a=t;for(const l of r){const c=typeof l=="function",u=c?l:YM(i,typeof l=="string"?l:l.type),f={context:a.context,event:e,self:n.self,system:n.system},h=c||typeof l=="string"?void 0:"params"in l?typeof l.params=="function"?l.params({context:a.context,event:e}):l.params:void 0;if(!u||!("resolve"in u)){n.actionExecutor({type:typeof l=="string"?l:typeof l=="object"?l.type:l.name||"(anonymous)",info:f,params:h,exec:u});continue}const p=u,[m,g,y]=p.resolve(n,a,f,h,u,o);a=m,"retryResolve"in p&&(s==null||s.push([p,g])),"execute"in p&&n.actionExecutor({type:p.type,info:f,params:g,exec:p.execute.bind(null,n,g)}),y&&(a=Em(a,e,n,y,o,s))}return a}function xs(t,e,n,r,o,s){const i=s?[]:void 0,a=Em(t,e,n,r,{internalQueue:o,deferredActorIds:s},i);return i==null||i.forEach(([l,c])=>{l.retryResolve(n,a,c)}),a}function Cu(t,e,n,r){let o=t;const s=[];function i(c,u,f){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:u,snapshot:c,_transitions:f}),s.push(c)}if(e.type===au)return o=Io(Cm(o,e,n),{status:"stopped"}),i(o,e,[]),{snapshot:o,microstates:s};let a=e;if(a.type!==nm){const c=a,u=wM(c),f=xm(c,o);if(u&&!f.length)return o=Io(t,{status:"error",error:c.error}),i(o,c,[]),{snapshot:o,microstates:s};o=Su(f,t,n,a,!1,r),i(o,c,f)}let l=!0;for(;o.status==="active";){let c=l?qM(o,a):[];const u=c.length?o:void 0;if(!c.length){if(!r.length)break;a=r.shift(),c=xm(a,o)}o=Su(c,o,n,a,!1,r),l=o!==u,i(o,a,c)}return o.status!=="active"&&Cm(o,a,n),{snapshot:o,microstates:s}}function Cm(t,e,n){return xs(t,e,n,Object.values(t.children).map(r=>Ra(r)),[],void 0)}function xm(t,e){return e.machine.getTransitionData(e,t)}function qM(t,e){const n=new Set,r=t._nodes.filter(yu);for(const o of r)e:for(const s of[o].concat(fi(o,void 0)))if(s.always){for(const i of s.always)if(i.guard===void 0||bs(i.guard,t.context,e,t)){n.add(i);break e}}return vm(Array.from(n),new Set(t._nodes),t.historyValue)}function XM(t,e){const n=za(Va(t,e));return gm(t,[...n])}function GM(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const JM=function(e){return sm(e,this.value)},QM=function(e){return this.tags.has(e)},eA=function(e){const n=this.machine.getTransitionData(this,e);return!!(n!=null&&n.length)&&n.some(r=>r.target!==void 0||r.actions.length)},tA=function(){const{_nodes:e,tags:n,machine:r,getMeta:o,toJSON:s,can:i,hasTag:a,matches:l,...c}=this;return{...c,tags:Array.from(n)}},nA=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function Fa(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:gm(e.root,t._nodes),tags:new Set(t._nodes.flatMap(n=>n.tags)),children:t.children,historyValue:t.historyValue||{},matches:JM,hasTag:QM,can:eA,getMeta:nA,toJSON:tA}}function Io(t,e={}){return Fa({...t,...e},t.machine)}function rA(t){if(typeof t!="object"||t===null)return{};const e={};for(const n in t){const r=t[n];Array.isArray(r)&&(e[n]=r.map(o=>({id:o.id})))}return e}function oA(t,e){const{_nodes:n,tags:r,machine:o,children:s,context:i,can:a,hasTag:l,matches:c,getMeta:u,toJSON:f,...h}=t,p={};for(const g in s){const y=s[g];p[g]={snapshot:y.getPersistedSnapshot(e),src:y.src,systemId:y.systemId,syncSnapshot:y._syncSnapshot}}return{...h,context:Tm(i),children:p,historyValue:rA(h.historyValue)}}function Tm(t){let e;for(const n in t){const r=t[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)e??(e=Array.isArray(t)?t.slice():{...t}),e[n]={xstate$$type:pu,id:r.id};else{const o=Tm(r);o!==r&&(e??(e=Array.isArray(t)?t.slice():{...t}),e[n]=o)}}return e??t}function sA(t,e,n,r,{event:o,id:s,delay:i},{internalQueue:a}){const l=e.machine.implementations.delays;if(typeof o=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const c=typeof o=="function"?o(n,r):o;let u;if(typeof i=="string"){const f=l&&l[i];u=typeof f=="function"?f(n,r):f}else u=typeof i=="function"?i(n,r):i;return typeof u!="number"&&a.push(c),[e,{event:c,id:s,delay:u},void 0]}function iA(t,e){const{event:n,delay:r,id:o}=e;if(typeof r=="number"){t.defer(()=>{const s=t.self;t.system.scheduler.schedule(s,s,n,r,o)});return}}function Wa(t,e){function n(r,o){}return n.type="xstate.raise",n.event=t,n.id=e==null?void 0:e.id,n.delay=e==null?void 0:e.delay,n.resolve=sA,n.execute=iA,n}function aA(t,{machine:e,context:n},r,o){const s=(i,a)=>{if(typeof i=="string"){const l=fu(e,i);if(!l)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=ui(l,{id:a==null?void 0:a.id,parent:t.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:n,event:r,self:t.self}):a==null?void 0:a.input,src:i,systemId:a==null?void 0:a.systemId});return o[c.id]=c,c}else return ui(i,{id:a==null?void 0:a.id,parent:t.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:i,systemId:a==null?void 0:a.systemId})};return(i,a)=>{const l=s(i,a);return o[l.id]=l,t.defer(()=>{l._processingStatus!==Xt.Stopped&&l.start()}),l}}function lA(t,e,n,r,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const s={},i={context:e.context,event:n.event,spawn:aA(t,e,n.event,s),self:t.self,system:t.system};let a={};if(typeof o=="function")a=o(i,r);else for(const c of Object.keys(o)){const u=o[c];a[c]=typeof u=="function"?u(i,r):u}const l=Object.assign({},e.context,a);return[Io(e,{context:l,children:Object.keys(s).length?{...e.children,...s}:e.children}),void 0,void 0]}function Re(t){function e(n,r){}return e.type="xstate.assign",e.assignment=t,e.resolve=lA,e}const Mm=new WeakMap;function Ts(t,e,n){let r=Mm.get(t);return r?e in r||(r[e]=n()):(r={[e]:n()},Mm.set(t,r)),r[e]}const cA={},hi=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class Ua{constructor(e,n){if(this.config=e,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(em),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?am(this.config.states,(r,o)=>new Ua(r,{_parent:this,_key:o,_machine:this.machine})):cA,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=qr(this.config.entry).slice(),this.exit=qr(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=qr(e.tags).slice()}_initialize(){this.transitions=DM(this),this.config.always&&(this.always=vs(this.config.always).map(e=>Ao(this,tm,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(hi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(hi),eventType:null})}:void 0,history:this.history,states:am(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(hi)})),entry:this.entry.map(hi),exit:this.exit.map(hi),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Ts(this,"invoke",()=>qr(this.config.invoke).map((e,n)=>{const{src:r,systemId:o}=e,s=e.id??dm(this.id,n),i=typeof r=="string"?r:`xstate.invoke.${dm(this.id,n)}`;return{...e,src:i,id:s,systemId:o,toJSON(){const{onDone:a,onError:l,...c}=e;return{...c,type:"xstate.invoke",src:i,id:s}}}}))}get on(){return Ts(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(o=>[n,o])).reduce((n,[r,o])=>(n[r]=n[r]||[],n[r].push(o),n),{}))}get after(){return Ts(this,"delayedTransitions",()=>PM(this))}get initial(){return Ts(this,"initial",()=>OM(this,this.config.initial))}next(e,n){const r=n.type,o=[];let s;const i=Ts(this,`candidates-${r}`,()=>NM(this,r));for(const a of i){const{guard:l}=a,c=e.context;let u=!1;try{u=!l||bs(l,c,n,e)}catch(f){const h=typeof l=="string"?l:typeof l=="object"?l.type:void 0;throw new Error(`Unable to evaluate guard ${h?`'${h}' `:""}in transition for event '${r}' in state node '${this.id}':
41
+ ${f.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get events(){return Ts(this,"events",()=>{const{states:e}=this,n=new Set(this.ownEvents);if(e)for(const r of Object.keys(e)){const o=e[r];if(o.states)for(const s of o.events)n.add(`${s}`)}return Array.from(n)})}get ownEvents(){const e=Object.keys(Object.fromEntries(this.transitions)),n=new Set(e.filter(r=>this.transitions.get(r).some(o=>!(!o.target&&!o.actions.length&&!o.reenter))));return Array.from(n)}}const uA="#";class xu{constructor(e,n){this.config=e,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=e.id||"(machine)",this.implementations={actors:(n==null?void 0:n.actors)??{},actions:(n==null?void 0:n.actions)??{},delays:(n==null?void 0:n.delays)??{},guards:(n==null?void 0:n.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new Ua(e,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(e){const{actions:n,guards:r,actors:o,delays:s}=this.implementations;return new xu(this.config,{actions:{...n,...e.actions},guards:{...r,...e.guards},actors:{...o,...e.actors},delays:{...s,...e.delays}})}resolveState(e){const n=XM(this.root,e.value),r=za(Va(this.root,n));return Fa({_nodes:[...r],context:e.context||{},children:{},status:wu(r,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,r){return Cu(e,n,r,[]).snapshot}microstep(e,n,r){return Cu(e,n,r,[]).microstates}getTransitionData(e,n){return ku(this.root,e.value,e,n)||[]}getPreInitialState(e,n,r){const{context:o}=this.config,s=Fa({context:typeof o!="function"&&o?o:{},_nodes:[this.root],children:{},status:"active"},this);return typeof o=="function"?xs(s,n,e,[Re(({spawn:a,event:l,self:c})=>o({spawn:a,input:l.input,self:c}))],r,void 0):s}getInitialSnapshot(e,n){const r=om(n),o=[],s=this.getPreInitialState(e,r,o),i=Su([{target:[...km(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],s,e,r,!0,o),{snapshot:a}=Cu(i,r,e,o);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=cu(e),r=n.slice(1),o=$a(n[0])?n[0].slice(uA.length):n[0],s=this.idMap.get(o);if(!s)throw new Error(`Child state node '#${o}' does not exist on machine '${this.id}'`);return La(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,n){return oA(e,n)}restoreSnapshot(e,n){const r={},o=e.children;Object.keys(o).forEach(f=>{const h=o[f],p=h.snapshot,m=h.src,g=typeof m=="string"?fu(this,m):m;if(!g)return;const y=ui(g,{id:f,parent:n.self,syncSnapshot:h.syncSnapshot,snapshot:p,src:m,systemId:h.systemId});r[f]=y});function s(f,h){if(h instanceof Ua)return h;try{return f.machine.getStateNodeById(h.id)}catch{}}function i(f,h){if(!h||typeof h!="object")return{};const p={};for(const m in h){const g=h[m];for(const y of g){const w=s(f,y);w&&(p[m]??(p[m]=[]),p[m].push(w))}}return p}const a=i(this.root,e.historyValue),l=Fa({...e,children:r,_nodes:Array.from(za(Va(this.root,e.value))),historyValue:a},this),c=new Set;function u(f,h){if(!c.has(f)){c.add(f);for(const p in f){const m=f[p];if(m&&typeof m=="object"){if("xstate$$type"in m&&m.xstate$$type===pu){f[p]=h[m.id];continue}u(m,h)}}}}return u(l.context,r),l}}function dA(t,e,n,r,{event:o}){const s=typeof o=="function"?o(n,r):o;return[e,{event:s},void 0]}function fA(t,{event:e}){t.defer(()=>t.emit(e))}function Am(t){function e(n,r){}return e.type="xstate.emit",e.event=t,e.resolve=dA,e.execute=fA,e}let Tu=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function hA(t,e,n,r,{to:o,event:s,id:i,delay:a},l){var m;const c=e.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${s}" }) instead`);const u=typeof s=="function"?s(n,r):s;let f;if(typeof a=="string"){const g=c&&c[a];f=typeof g=="function"?g(n,r):g}else f=typeof a=="function"?a(n,r):a;const h=typeof o=="function"?o(n,r):o;let p;if(typeof h=="string"){if(h===Tu.Parent?p=t.self._parent:h===Tu.Internal?p=t.self:h.startsWith("#_")?p=e.children[h.slice(2)]:p=(m=l.deferredActorIds)!=null&&m.includes(h)?h:e.children[h],!p)throw new Error(`Unable to send event to actor '${h}' from machine '${e.machine.id}'.`)}else p=h||t.self;return[e,{to:p,targetId:typeof h=="string"?h:void 0,event:u,id:i,delay:f},void 0]}function pA(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function mA(t,e){t.defer(()=>{const{to:n,event:r,delay:o,id:s}=e;if(typeof o=="number"){t.system.scheduler.schedule(t.self,n,r,o,s);return}t.system._relay(t.self,n,r.type===hM?rm(t.self.id,r.data):r)})}function Mu(t,e,n){function r(o,s){}return r.type="xstate.sendTo",r.to=t,r.event=e,r.id=n==null?void 0:n.id,r.delay=n==null?void 0:n.delay,r.resolve=hA,r.retryResolve=pA,r.execute=mA,r}function gA(t,e){return Mu(Tu.Parent,t,e)}function yA(t,e,n,r,{collect:o}){const s=[],i=function(l){s.push(l)};return i.assign=(...a)=>{s.push(Re(...a))},i.cancel=(...a)=>{s.push(mu(...a))},i.raise=(...a)=>{s.push(Wa(...a))},i.sendTo=(...a)=>{s.push(Mu(...a))},i.sendParent=(...a)=>{s.push(gA(...a))},i.spawnChild=(...a)=>{s.push(gu(...a))},i.stopChild=(...a)=>{s.push(Ra(...a))},i.emit=(...a)=>{s.push(Am(...a))},o({context:n.context,event:n.event,enqueue:i,check:a=>bs(a,e.context,n.event,e),self:t.self,system:t.system},r),[e,void 0,s]}function wA(t){function e(n,r){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=yA,e}function kA(t,e,n,r,{value:o,label:s}){return[e,{value:typeof o=="function"?o(n,r):o,label:s},void 0]}function vA({logger:t},{value:e,label:n}){n?t(n,e):t(e)}function bA(t=({context:n,event:r})=>({context:n,event:r}),e){function n(r,o){}return n.type="xstate.log",n.value=t,n.label=e,n.resolve=kA,n.execute=vA,n}function SA(t,e){return new xu(t,e)}function EA(t){const e=ui(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}function br({schemas:t,actors:e,actions:n,guards:r,delays:o}){return{assign:Re,sendTo:Mu,raise:Wa,log:bA,cancel:mu,stopChild:Ra,enqueueActions:wA,emit:Am,spawnChild:gu,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>SA({...s,schemas:t},{actors:e,actions:n,guards:r,delays:o}),extend:s=>br({schemas:t,actors:e,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...o,...s.delays}})}}function CA(t,e,n){const r=[],o=EA(t);return o.actionExecutor=i=>{r.push(i)},[t.transition(e,n,o),r]}var xA=Object.defineProperty,_m=(t,e)=>{for(var n in e)xA(t,n,{get:e[n],enumerable:!0})},Im={};_m(Im,{Aabb:()=>Be,Asset:()=>Bo,Block:()=>A,Color:()=>yn,Connector:()=>ze,Edited:()=>Sr,Held:()=>Tt,HitGeometry:()=>ke,Hovered:()=>Gr,Image:()=>pi,MAX_HIT_ARCS:()=>ja,MAX_HIT_CAPSULES:()=>Ms,Opacity:()=>Qe,Pointer:()=>Dt,PointerButton:()=>ln,PointerType:()=>Jr,ScaleWithZoom:()=>Qr,Shape:()=>wn,StrokeKind:()=>ht,Text:()=>at,UploadState:()=>nr,User:()=>Cr,VerticalAlign:()=>No,addPointerSample:()=>Ka});var TA=[[0,0],[0,0],[0,0],[0,0]],MA=[[0,0],[0,0],[0,0],[0,0]],AA=[[0,0],[0,0]],_A={tag:C.string().max(36).default("div"),position:C.tuple(C.float64(),2).default([0,0]),size:C.tuple(C.float64(),2).default([100,100]),rotateZ:C.float64().default(0),flip:C.tuple(C.boolean(),2).default([!1,!1]),rank:C.string().max(36).default("")},IA=class extends Kt{constructor(){super({name:"block",sync:"document"},_A)}getCenter(t,e,n){const{position:r,size:o}=this.read(t,e),s=n??[0,0];return st.getCenter(r,o,s),s}setCenter(t,e,n){const r=this.write(t,e);st.setCenter(r.position,r.size,n)}getCorners(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e),i=n??[[0,0],[0,0],[0,0],[0,0]];return st.getCorners(r,o,s,i),i}containsPoint(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return st.containsPoint(r,o,s,n)}translate(t,e,n){const r=this.write(t,e);st.translate(r.position,n)}setPosition(t,e,n){const r=this.write(t,e);L.copy(r.position,n)}setSize(t,e,n){const r=this.write(t,e);L.copy(r.size,n)}rotateBy(t,e,n){const r=this.write(t,e);r.rotateZ+=n}rotateAround(t,e,n,r){const o=this.write(t,e);o.rotateZ=st.rotateAround(o.position,o.size,o.rotateZ,n,r)}scaleBy(t,e,n){const r=this.write(t,e);st.scaleBy(r.position,r.size,n)}scaleAround(t,e,n,r){const o=this.write(t,e);st.scaleAround(o.position,o.size,n,r)}intersectsAabb(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return st.intersectsAabb(r,o,s,n,MA,TA,AA)}worldToUv(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e),a=st.worldToUv(r,o,s,n);return i[0]&&(a[0]=1-a[0]),i[1]&&(a[1]=1-a[1]),a}uvToWorld(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e),a=[i[0]?1-n[0]:n[0],i[1]?1-n[1]:n[1]];return st.uvToWorld(r,o,s,a)}getUvToWorldMatrix(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e);st.getUvToWorldMatrix(r,o,s,n),i[0]&&(n[0]=-n[0],n[2]=-n[2],n[4]+=o[0]*Math.cos(s),n[5]+=o[0]*Math.sin(s)),i[1]&&(n[1]=-n[1],n[3]=-n[3],n[4]-=o[1]*Math.sin(s),n[5]+=o[1]*Math.cos(s))}},A=new IA,Bm=0,Nm=1,Pm=2,Dm=3,BA={value:C.tuple(C.float32(),4).default([0,0,0,0])},NA=class extends Kt{constructor(){super({name:"aabb"},BA)}containsPoint(t,e,n,r=!0){const{value:o}=this.read(t,e);return ee.containsPoint(o,n,r)}expandByPoint(t,e,n){const{value:r}=this.write(t,e);ee.expand(r,n)}expandByBlock(t,e,n){const r=A.getCorners(t,n),{value:o}=this.write(t,e);for(const s of r)ee.expand(o,s)}expandByAabb(t,e,n){const{value:r}=this.write(t,e);ee.union(r,n)}copyFrom(t,e,n){const{value:r}=this.read(t,n),{value:o}=this.write(t,e);ee.copy(o,r)}setByPoints(t,e,n){if(n.length===0)return;const{value:r}=this.write(t,e);ee.setFromPoints(r,n)}getCenter(t,e){const{value:n}=this.read(t,e);return ee.center(n)}getWidth(t,e){const{value:n}=this.read(t,e);return ee.width(n)}getHeight(t,e){const{value:n}=this.read(t,e);return ee.height(n)}distanceToPoint(t,e,n){const{value:r}=this.read(t,e);return ee.distanceToPoint(r,n)}intersectsEntity(t,e,n){const{value:r}=this.read(t,e),{value:o}=this.read(t,n);return ee.intersects(r,o)}surroundsEntity(t,e,n){const{value:r}=this.read(t,e),{value:o}=this.read(t,n);return ee.contains(r,o)}getCorners(t,e,n){const{value:r}=this.read(t,e),o=n??[[0,0],[0,0],[0,0],[0,0]];return o[0][0]=r[Bm],o[0][1]=r[Nm],o[1][0]=r[Pm],o[1][1]=r[Nm],o[2][0]=r[Pm],o[2][1]=r[Dm],o[3][0]=r[Bm],o[3][1]=r[Dm],o}applyPadding(t,e,n){const{value:r}=this.write(t,e);ee.pad(r,n)}},Be=new NA,nr={Pending:"pending",Uploading:"uploading",Complete:"complete",Failed:"failed"},Bo=Ze({name:"asset",sync:"document",excludeFromHistory:["uploadState"]},{identifier:C.string().max(512).default(""),uploadState:C.enum(nr).default(nr.Pending)}),PA={red:C.uint8().default(0),green:C.uint8().default(0),blue:C.uint8().default(0),alpha:C.uint8().default(255)},DA=class extends Kt{constructor(){super({name:"color",sync:"document"},PA)}toHex(t,e){const{red:n,green:r,blue:o,alpha:s}=this.read(t,e),i=n.toString(16).padStart(2,"0"),a=r.toString(16).padStart(2,"0"),l=o.toString(16).padStart(2,"0"),c=s.toString(16).padStart(2,"0");return`#${i}${a}${l}${c}`}fromHex(t,e,n){const r=this.write(t,e);r.red=Number.parseInt(n.slice(1,3),16),r.green=Number.parseInt(n.slice(3,5),16),r.blue=Number.parseInt(n.slice(5,7),16),r.alpha=n.length>7?Number.parseInt(n.slice(7,9),16):255}},yn=new DA,ze=Ze({name:"connector",sync:"document"},{startBlock:C.ref(),startBlockUv:C.tuple(C.float64(),2).default([0,0]),startUv:C.tuple(C.float64(),2).default([0,0]),endBlock:C.ref(),endBlockUv:C.tuple(C.float64(),2).default([0,0]),endUv:C.tuple(C.float64(),2).default([1,1])}),Sr=Ze({name:"edited"},{}),Tt=Ze({name:"held",sync:"ephemeral"},{sessionId:C.string().max(36).default("")}),ft=[1,0,0,1,0,0],Ms=64,Ha=5,ja=2,Za=7,OA={hitCapsules:C.buffer(C.float32()).size(Ms*Ha),capsuleCount:C.uint16().default(0),hitArcs:C.buffer(C.float32()).size(ja*Za),arcCount:C.uint16().default(0)},RA=class extends Kt{constructor(){super({name:"hitHeometry"},OA)}getCapsuleAt(t,e,n){const r=this.read(t,e),o=n*Ha;return[r.hitCapsules[o],r.hitCapsules[o+1],r.hitCapsules[o+2],r.hitCapsules[o+3],r.hitCapsules[o+4]]}setCapsuleAt(t,e,n,r){const o=this.write(t,e),s=n*Ha;for(let i=0;i<Ha;i++)o.hitCapsules[s+i]=r[i]}getArcAt(t,e,n){const r=this.read(t,e),o=n*Za;return[r.hitArcs[o],r.hitArcs[o+1],r.hitArcs[o+2],r.hitArcs[o+3],r.hitArcs[o+4],r.hitArcs[o+5],r.hitArcs[o+6]]}setArcAt(t,e,n,r){const o=this.write(t,e),s=n*Za;for(let i=0;i<Za;i++)o.hitArcs[s+i]=r[i]}containsPointWorld(t,e,n){const r=this.read(t,e);A.getUvToWorldMatrix(t,e,ft);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(ft,i);const a=[s[2],s[3]];Ae.transformPoint(ft,a);const l=[s[4],s[5]];Ae.transformPoint(ft,l);const c=s[6],u=Me.create(i[0],i[1],a[0],a[1],l[0],l[1],c);if(Me.containsPoint(u,n))return!0}for(let o=0;o<r.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(ft,i);const a=[s[2],s[3]];Ae.transformPoint(ft,a);const l=s[4],c=ot.create(i[0],i[1],a[0],a[1],l);if(ot.containsPoint(c,n))return!0}return!1}intersectsAabbWorld(t,e,n){const r=this.read(t,e);A.getUvToWorldMatrix(t,e,ft);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(ft,i);const a=[s[2],s[3]];Ae.transformPoint(ft,a);const l=[s[4],s[5]];Ae.transformPoint(ft,l);const c=s[6],u=Me.create(i[0],i[1],a[0],a[1],l[0],l[1],c);if(Me.intersectsAabb(u,n))return!0}for(let o=0;o<r.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(ft,i);const a=[s[2],s[3]];Ae.transformPoint(ft,a);const l=s[4],c=ot.create(i[0],i[1],a[0],a[1],l);if(ot.intersectsAabb(c,n))return!0}return!1}getExtremaWorld(t,e){const n=this.read(t,e),r=[];A.getUvToWorldMatrix(t,e,ft);for(let o=0;o<n.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(ft,i);const a=[s[2],s[3]];Ae.transformPoint(ft,a);const l=s[4],c=ot.create(i[0],i[1],a[0],a[1],l);r.push(...ot.getExtrema(c))}for(let o=0;o<n.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(ft,i);const a=[s[2],s[3]];Ae.transformPoint(ft,a);const l=[s[4],s[5]];Ae.transformPoint(ft,l);const c=s[6],u=Me.create(i[0],i[1],a[0],a[1],l[0],l[1],c);r.push(...Me.getExtrema(u))}return r}addCapsule(t,e,n){const r=this.write(t,e),o=r.capsuleCount;if(o>=Ms){console.warn(`HitGeometry: Max capsules (${Ms}) reached`);return}this.setCapsuleAt(t,e,o,n),r.capsuleCount=o+1}addCapsuleUv(t,e,n,r,o){const s=[n[0],n[1],r[0],r[1],o];this.addCapsule(t,e,s)}addCapsuleWorld(t,e,n,r,o){const s=A.worldToUv(t,e,n),i=A.worldToUv(t,e,r);this.addCapsuleUv(t,e,s,i,o)}addArc(t,e,n){const r=this.write(t,e),o=r.arcCount;if(o>=ja){console.warn(`HitGeometry: Max arcs (${ja}) reached`);return}this.setArcAt(t,e,o,n),r.arcCount=o+1}addArcUv(t,e,n,r,o,s){const i=[n[0],n[1],r[0],r[1],o[0],o[1],s];this.addArc(t,e,i)}addArcWorld(t,e,n,r,o,s){const i=A.worldToUv(t,e,n),a=A.worldToUv(t,e,r),l=A.worldToUv(t,e,o);this.addArcUv(t,e,i,a,l,s)}clear(t,e){const n=this.write(t,e);n.capsuleCount=0,n.arcCount=0}},ke=new RA,Gr=Ze({name:"hovered"},{}),pi=Ze({name:"image",sync:"document"},{width:C.uint16().default(0),height:C.uint16().default(0),alt:C.string().max(256).default("")}),Qe=Ze({name:"opacity"},{value:C.uint8().default(255)}),ln={None:"none",Left:"left",Middle:"middle",Right:"right",Back:"back",Forward:"forward"},Jr={Mouse:"mouse",Pen:"pen",Touch:"touch"},Er=6,zA={pointerId:C.uint16().default(0),position:C.tuple(C.float32(),2).default([0,0]),downPosition:C.tuple(C.float32(),2).default([0,0]),downFrame:C.uint32().default(0),button:C.enum(ln).default(ln.None),pointerType:C.enum(Jr).default(Jr.Mouse),pressure:C.float32().default(0),obscured:C.boolean().default(!1),_prevPositions:C.array(C.float32(),Er*2),_prevTimes:C.array(C.float32(),Er),_sampleCount:C.int32().default(0),_velocity:C.tuple(C.float32(),2).default([0,0])},$A=class extends Kt{constructor(){super({name:"pointer"},zA)}getVelocity(t,e){const n=this.read(t,e);return[n._velocity[0],n._velocity[1]]}getButton(t){switch(t){case 0:return ln.Left;case 1:return ln.Middle;case 2:return ln.Right;case 3:return ln.Back;case 4:return ln.Forward;default:return ln.None}}getType(t){switch(t){case"pen":return Jr.Pen;case"touch":return Jr.Touch;default:return Jr.Mouse}}},Dt=new $A;function Ka(t,e,n){const r=t._sampleCount%Er,o=t._prevTimes[r]||0;if(Math.abs(o-n)<.001)return;t.position=e,t._sampleCount++;const s=t._sampleCount%Er;t._prevPositions[s*2]=e[0],t._prevPositions[s*2+1]=e[1],t._prevTimes[s]=n;const i=Math.min(t._sampleCount,Er);if(i<=1){t._velocity=[0,0];return}const a=S=>(S%Er+Er)%Er,l=.04,c=1e-6;let u=0,f=0,h=0,p=0,m=0,g=0,y=0;for(let S=0;S<i;S++){const v=a(t._sampleCount-i+1+S),T=(t._prevTimes[v]||0)-n,_=-T;if(_>5*l)continue;const I=Math.exp(-_/l),z=t._prevPositions[v*2]||0,F=t._prevPositions[v*2+1]||0;u+=I,f+=I*T,h+=I*T*T,p+=I*z,m+=I*F,g+=I*T*z,y+=I*T*F}const w=u*h-f*f;if(Math.abs(w)<=c){const S=t._sampleCount%Er,v=a(t._sampleCount-1),E=(t._prevTimes[S]||0)-(t._prevTimes[v]||0);if(E>c){const T=(t._prevPositions[S*2]||0)-(t._prevPositions[v*2]||0),_=(t._prevPositions[S*2+1]||0)-(t._prevPositions[v*2+1]||0);t._velocity=[T/E,_/E]}else t._velocity=[0,0];return}const k=(u*g-f*p)/w,b=(u*y-f*m)/w;t._velocity=[k,b]}var Qr=Ze({name:"scaleWithZoom"},{anchor:C.tuple(C.float64(),2).default([.5,.5]),startPosition:C.tuple(C.float64(),2).default([0,0]),startSize:C.tuple(C.float64(),2).default([0,0]),scaleMultiplier:C.tuple(C.float64(),2).default([1,1])}),ht={Solid:"solid",Dashed:"dashed",None:"none"},wn=Ze({name:"shape",sync:"document"},{kind:C.string().default("rectangle"),strokeKind:C.enum(ht).default(ht.Solid),strokeWidth:C.uint16().default(2),strokeRed:C.uint8().default(0),strokeGreen:C.uint8().default(0),strokeBlue:C.uint8().default(0),strokeAlpha:C.uint8().default(255),fillRed:C.uint8().default(255),fillGreen:C.uint8().default(255),fillBlue:C.uint8().default(255),fillAlpha:C.uint8().default(0)});function LA(){const t=["#f43f5e","#ec4899","#a855f7","#6366f1","#3b82f6","#0ea5e9","#14b8a6","#22c55e","#eab308","#f97316"];return t[Math.floor(Math.random()*t.length)]}var Om=qt({userId:dt().max(36).default(()=>crypto.randomUUID()),sessionId:dt().max(36).default(()=>crypto.randomUUID()),color:dt().max(7).default(LA),name:dt().max(100).default("Anonymous"),avatar:dt().max(500).default("")});function As(t,e){return t.resources.pluginResources[e]}var VA=qt({enabled:Lt().default(!0),strict:Lt().default(!1),colWidth:Je().nonnegative().default(20),rowHeight:Je().nonnegative().default(20),snapAngleRad:Je().nonnegative().default(Math.PI/36),shiftSnapAngleRad:Je().nonnegative().default(Math.PI/12)}),FA=qt({leftMouseTool:dt().max(32).default("select"),middleMouseTool:dt().max(32).default("hand"),rightMouseTool:dt().max(32).default("menu"),wheelTool:dt().max(32).default("scroll"),modWheelTool:dt().max(32).default("zoom")}),WA=qt({plugins:mn(gn()).default([]),maxEntities:Je().default(5e3),user:gn().default({}),grid:gn().default({}),blockDefs:mn(gn()).default([]),keybinds:mn(gn()).default([]),cursors:MT(dt(),gn()).default({}),components:mn(gn()).default([]),singletons:mn(gn()).default([]),systems:mn(gn()).default([]),fonts:mn(gn()).default([]),omitPluginKeybinds:Lt().default(!1),omitPluginCursors:Lt().default(!1),omitPluginFonts:Lt().default(!1),controls:gn().optional()});qt({command:dt(),key:Je(),mod:Lt().optional(),shift:Lt().optional()}),qt({makeSvg:HT({input:Ba([Je()]),output:dt()}),hotspot:Ba([Je(),Je()]),rotationOffset:Je()});var it={Top:"top",Center:"center",Bottom:"bottom"},kn={Left:"left",Center:"center",Right:"right",Justify:"justify"},Rm=qt({canEdit:Lt().default(!1),removeWhenTextEmpty:Lt().default(!1)}),zm=qt({enabled:Lt().default(!0),terminals:mn(Ba([Je(),Je()])).default([[.5,0],[.5,1],[.5,.5],[0,.5],[1,.5]])}),UA=tu(["background","content","overlay"]),Au=qt({tag:dt(),stratum:UA.default("content"),editOptions:Rm.default(Rm.parse({})),components:mn(gn()).default([]),resizeMode:tu(["scale","text","free","groupOnly"]).default("scale"),canRotate:Lt().default(!0),canScale:Lt().default(!0),connectors:zm.default(zm.parse({}))}),at=Ze({name:"text",sync:"document"},{content:C.string().max(1e4).default(""),fontSizePx:C.float64().default(24),fontFamily:C.string().max(64).default("Figtree"),lineHeight:C.float64().default(1.2),letterSpacingEm:C.float64().default(0),constrainWidth:C.boolean().default(!0),defaultAlignment:C.enum(kn).default(kn.Left)}),Cr=Ze({name:"user",sync:"ephemeral"},{userId:C.string().max(36),sessionId:C.string().max(36),color:C.string().max(7),name:C.string().max(100),avatar:C.string().max(500),position:C.tuple(C.float32(),2).default([0,0])}),No=Ze({name:"verticalAlign",sync:"document"},{value:C.enum(it).default(it.Top)}),HA="core",_u={background:0,content:1,overlay:2},$m={};_m($m,{Camera:()=>he,Controls:()=>et,Cursor:()=>vn,Frame:()=>_s,Grid:()=>Ot,Intersect:()=>eo,Key:()=>Gt,Keyboard:()=>cn,Mouse:()=>bn,RankBounds:()=>Dn,ScaleWithZoomState:()=>Nu,Screen:()=>Mt,clearBits:()=>Po,codeToIndex:()=>P,setBit:()=>mi});var jA={width:C.float64().default(0),height:C.float64().default(0),left:C.float64().default(0),top:C.float64().default(0)},ZA=class extends St{constructor(){super({name:"screen"},jA)}getSize(t){const e=this.read(t);return[e.width,e.height]}getPosition(t){const e=this.read(t);return[e.left,e.top]}getCenter(t){const e=this.read(t);return[e.left+e.width/2,e.top+e.height/2]}},Mt=new ZA,KA={top:C.float64().default(0),left:C.float64().default(0),zoom:C.float64().default(1),canSeeBlocks:C.boolean().default(!0),lastSeenBlock:C.ref()},YA=class extends St{constructor(){super({name:"camera",sync:"local"},KA)}toWorld(t,e){const n=this.read(t),r=n.left+e[0]/n.zoom,o=n.top+e[1]/n.zoom;return[r,o]}toScreen(t,e){const n=this.read(t),r=(e[0]-n.left)*n.zoom,o=(e[1]-n.top)*n.zoom;return[r,o]}getWorldCenter(t){const e=this.read(t),n=Mt.read(t);return[e.left+n.width/e.zoom/2,e.top+n.height/e.zoom/2]}getWorldBounds(t){const e=this.read(t),n=Mt.read(t);return{left:e.left,top:e.top,right:e.left+n.width/e.zoom,bottom:e.top+n.height/e.zoom}}getAabb(t,e){const n=this.read(t),r=Mt.read(t),o=e??[0,0,0,0];return o[0]=n.left,o[1]=n.top,o[2]=n.left+r.width/n.zoom,o[3]=n.top+r.height/n.zoom,o}},he=new YA,qA={leftMouseTool:C.string().max(32).default("select"),middleMouseTool:C.string().max(32).default("hand"),rightMouseTool:C.string().max(32).default("menu"),wheelTool:C.string().max(32).default("scroll"),modWheelTool:C.string().max(32).default("zoom"),heldSnapshot:C.string().max(4096).default("")},XA=class extends St{constructor(){super({name:"controls"},qA)}getButtons(t,...e){const n=this.read(t),r=[];return e.includes(n.leftMouseTool)&&r.push(ln.Left),e.includes(n.middleMouseTool)&&r.push(ln.Middle),e.includes(n.rightMouseTool)&&r.push(ln.Right),r}wheelActive(t,e,n){const r=this.read(t);return r.wheelTool===e&&!n||r.modWheelTool===e&&n}},et=new XA,GA={cursorKind:C.string().max(64).default("select"),rotation:C.float64().default(0),contextCursorKind:C.string().max(64).default(""),contextRotation:C.float64().default(0)},JA=class extends St{constructor(){super({name:"cursor"},GA)}getEffective(t){const e=this.read(t);return e.contextCursorKind?{cursorKind:e.contextCursorKind,rotation:e.contextRotation}:{cursorKind:e.cursorKind,rotation:e.rotation}}setCursor(t,e,n=0){const r=this.write(t);r.cursorKind=e,r.rotation=n}setContextCursor(t,e,n=0){const r=this.write(t);r.contextCursorKind=e,r.contextRotation=n}clearContextCursor(t){const e=this.write(t);e.contextCursorKind="",e.contextRotation=0}},vn=new JA,_s=zh({name:"frame"},{number:C.uint32().default(0),delta:C.float64().default(0),time:C.float64().default(0),lastTime:C.float64().default(0)}),QA={enabled:C.boolean().default(!1),strict:C.boolean().default(!1),colWidth:C.float64().default(20),rowHeight:C.float64().default(20),snapAngleRad:C.float64().default(Math.PI/36),shiftSnapAngleRad:C.float64().default(Math.PI/12)},e_=class extends St{constructor(){super({name:"grid"},QA)}snapPosition(t,e){const n=this.read(t);n.enabled&&(n.colWidth!==0&&(e[0]=Math.round(e[0]/n.colWidth)*n.colWidth),n.rowHeight!==0&&(e[1]=Math.round(e[1]/n.rowHeight)*n.rowHeight))}snapSize(t,e){const n=this.read(t);n.enabled&&(n.colWidth!==0&&(e[0]=Math.max(n.colWidth,Math.round(e[0]/n.colWidth)*n.colWidth)),n.rowHeight!==0&&(e[1]=Math.max(n.rowHeight,Math.round(e[1]/n.rowHeight)*n.rowHeight)))}snapX(t,e){const n=this.read(t);return!n.enabled||n.colWidth===0?e:Math.round(e/n.colWidth)*n.colWidth}snapY(t,e){const n=this.read(t);return!n.enabled||n.rowHeight===0?e:Math.round(e/n.rowHeight)*n.rowHeight}},Ot=new e_,t_={entity1:C.ref(),entity2:C.ref(),entity3:C.ref(),entity4:C.ref(),entity5:C.ref()},n_=class extends St{constructor(){super({name:"intersect"},t_)}getTop(t){return this.read(t).entity1}getAll(t){const e=this.read(t),n=[];return e.entity1!==null&&n.push(e.entity1),e.entity2!==null&&n.push(e.entity2),e.entity3!==null&&n.push(e.entity3),e.entity4!==null&&n.push(e.entity4),e.entity5!==null&&n.push(e.entity5),n}setAll(t,e){const n=this.write(t);n.entity1=e[0]??null,n.entity2=e[1]??null,n.entity3=e[2]??null,n.entity4=e[3]??null,n.entity5=e[4]??null}clear(t){const e=this.write(t);e.entity1=null,e.entity2=null,e.entity3=null,e.entity4=null,e.entity5=null}},eo=new n_,Iu=32,r_={keysDown:C.buffer(C.uint8()).size(Iu),keysDownTrigger:C.buffer(C.uint8()).size(Iu),keysUpTrigger:C.buffer(C.uint8()).size(Iu),shiftDown:C.boolean().default(!1),altDown:C.boolean().default(!1),modDown:C.boolean().default(!1)};function Bu(t,e){if(e<0||e>=t.length*8)return!1;const n=Math.floor(e/8),r=e%8;return(t[n]&1<<r)!==0}var o_=class extends St{constructor(){super({name:"keyboard"},r_)}isKeyDown(t,e){return Bu(this.read(t).keysDown,e)}isKeyDownTrigger(t,e){return Bu(this.read(t).keysDownTrigger,e)}isKeyUpTrigger(t,e){return Bu(this.read(t).keysUpTrigger,e)}reset(t){const e=this.write(t);Po(e.keysDown),Po(e.keysDownTrigger),Po(e.keysUpTrigger),e.shiftDown=!1,e.altDown=!1,e.modDown=!1}},cn=new o_;function mi(t,e,n){if(e<0||e>=t.length*8)return;const r=Math.floor(e/8),o=e%8;n?t[r]|=1<<o:t[r]&=~(1<<o)}function Po(t){for(let e=0;e<t.length;e++)t[e]=0}var P={KeyA:0,KeyB:1,KeyC:2,KeyD:3,KeyE:4,KeyF:5,KeyG:6,KeyH:7,KeyI:8,KeyJ:9,KeyK:10,KeyL:11,KeyM:12,KeyN:13,KeyO:14,KeyP:15,KeyQ:16,KeyR:17,KeyS:18,KeyT:19,KeyU:20,KeyV:21,KeyW:22,KeyX:23,KeyY:24,KeyZ:25,Digit0:26,Digit1:27,Digit2:28,Digit3:29,Digit4:30,Digit5:31,Digit6:32,Digit7:33,Digit8:34,Digit9:35,F1:36,F2:37,F3:38,F4:39,F5:40,F6:41,F7:42,F8:43,F9:44,F10:45,F11:46,F12:47,ShiftLeft:48,ShiftRight:49,ControlLeft:50,ControlRight:51,AltLeft:52,AltRight:53,MetaLeft:54,MetaRight:55,Escape:56,Space:57,Enter:58,Tab:59,Backspace:60,Delete:61,ArrowLeft:62,ArrowUp:63,ArrowRight:64,ArrowDown:65,Home:66,End:67,PageUp:68,PageDown:69,Insert:70,Semicolon:72,Equal:73,Comma:74,Minus:75,Period:76,Slash:77,Backquote:78,BracketLeft:79,Backslash:80,BracketRight:81,Quote:82,Numpad0:84,Numpad1:85,Numpad2:86,Numpad3:87,Numpad4:88,Numpad5:89,Numpad6:90,Numpad7:91,Numpad8:92,Numpad9:93,NumpadAdd:94,NumpadSubtract:95,NumpadMultiply:96,NumpadDivide:97,NumpadDecimal:98,NumpadEnter:99},Gt={A:P.KeyA,B:P.KeyB,C:P.KeyC,D:P.KeyD,E:P.KeyE,F:P.KeyF,G:P.KeyG,H:P.KeyH,I:P.KeyI,J:P.KeyJ,K:P.KeyK,L:P.KeyL,M:P.KeyM,N:P.KeyN,O:P.KeyO,P:P.KeyP,Q:P.KeyQ,R:P.KeyR,S:P.KeyS,T:P.KeyT,U:P.KeyU,V:P.KeyV,W:P.KeyW,X:P.KeyX,Y:P.KeyY,Z:P.KeyZ,Digit0:P.Digit0,Digit1:P.Digit1,Digit2:P.Digit2,Digit3:P.Digit3,Digit4:P.Digit4,Digit5:P.Digit5,Digit6:P.Digit6,Digit7:P.Digit7,Digit8:P.Digit8,Digit9:P.Digit9,F1:P.F1,F2:P.F2,F3:P.F3,F4:P.F4,F5:P.F5,F6:P.F6,F7:P.F7,F8:P.F8,F9:P.F9,F10:P.F10,F11:P.F11,F12:P.F12,ShiftLeft:P.ShiftLeft,ShiftRight:P.ShiftRight,ControlLeft:P.ControlLeft,ControlRight:P.ControlRight,AltLeft:P.AltLeft,AltRight:P.AltRight,MetaLeft:P.MetaLeft,MetaRight:P.MetaRight,Escape:P.Escape,Space:P.Space,Enter:P.Enter,Tab:P.Tab,Backspace:P.Backspace,Delete:P.Delete,ArrowLeft:P.ArrowLeft,ArrowUp:P.ArrowUp,ArrowRight:P.ArrowRight,ArrowDown:P.ArrowDown,Home:P.Home,End:P.End,PageUp:P.PageUp,PageDown:P.PageDown,Insert:P.Insert,Semicolon:P.Semicolon,Equal:P.Equal,Comma:P.Comma,Minus:P.Minus,Period:P.Period,Slash:P.Slash,Backquote:P.Backquote,BracketLeft:P.BracketLeft,Backslash:P.Backslash,BracketRight:P.BracketRight,Quote:P.Quote,Numpad0:P.Numpad0,Numpad1:P.Numpad1,Numpad2:P.Numpad2,Numpad3:P.Numpad3,Numpad4:P.Numpad4,Numpad5:P.Numpad5,Numpad6:P.Numpad6,Numpad7:P.Numpad7,Numpad8:P.Numpad8,Numpad9:P.Numpad9,NumpadAdd:P.NumpadAdd,NumpadSubtract:P.NumpadSubtract,NumpadMultiply:P.NumpadMultiply,NumpadDivide:P.NumpadDivide,NumpadDecimal:P.NumpadDecimal,NumpadEnter:P.NumpadEnter},s_={position:C.tuple(C.float32(),2).default([0,0]),wheelDeltaX:C.float32().default(0),wheelDeltaY:C.float32().default(0),moveTrigger:C.boolean().default(!1),wheelTrigger:C.boolean().default(!1),enterTrigger:C.boolean().default(!1),leaveTrigger:C.boolean().default(!1)},i_=class extends St{constructor(){super({name:"mouse"},s_)}didMove(t){return this.read(t).moveTrigger}didScroll(t){return this.read(t).wheelTrigger}didEnter(t){return this.read(t).enterTrigger}didLeave(t){return this.read(t).leaveTrigger}getPosition(t){const e=this.read(t);return[e.position[0],e.position[1]]}getWheelDelta(t){const e=this.read(t);return[e.wheelDeltaX,e.wheelDeltaY]}},bn=new i_,a_={minRank:C.string().max(36).default(""),maxRank:C.string().max(36).default("")},l_=class extends St{constructor(){super({name:"rankBounds"},a_)}genNext(t){const e=this.write(t),n=Oa(e.maxRank||null,null);return e.maxRank=n,e.minRank||(e.minRank=n),n}genPrev(t){const e=this.write(t),n=Oa(null,e.minRank||null);return e.minRank=n,e.maxRank||(e.maxRank=n),n}genBetween(t,e){return Oa(t,e)}add(t,e){if(!e)return;const n=this.write(t);(!n.minRank||e<n.minRank)&&(n.minRank=e),(!n.maxRank||e>n.maxRank)&&(n.maxRank=e)}},Dn=new l_,Nu=zh({name:"scaleWithZoomState"},{lastZoom:C.float64().default(1)}),Is=$c({name:C.string().max(128)}),Lm=new WeakMap;function Pu(t){const{editor:e}=Ve(t);let n=Lm.get(e);return n||(n=new Map,Lm.set(e,n)),n}var Du=re(t=>t.with(Is));function le(t){return{name:t,spawn(e,n){const r=bt(e);return J(e,r,Is,{name:t}),Pu(e).set(r,n),r},*iter(e){const n=Pu(e);for(const r of Du.current(e))if(Is.read(e,r).name===t){const s=n.get(r);yield{eid:r,payload:s}}},didSpawnLastFrame(e){for(const n of Du.removed(e))if(Is.read(e,n).name===t)return!0;return!1}}}function c_(t){const e=Pu(t);for(const n of Du.current(t))e.delete(n),qe(t,n)}function ae(t,e,n){for(const{payload:r}of e.iter(t))n(t,r)}var Ou=le("undo"),Ya=le("redo"),Vm=le("reset-keyboard"),u_=0;function ge(t,e){return{_system:new qb(e),phase:t.phase,priority:t.priority??u_}}var d_=ge({phase:"capture"},t=>{const e=cn.read(t),{editor:n}=Ve(t);for(const r of n.keybinds){let o=cn.isKeyDownTrigger(t,r.key);if(o&&(o=!!r.mod===e.modDown),o&&(o=!!r.shift===e.shiftDown),o){const s=bt(t);J(t,s,Is,{name:r.command});break}}}),f_=ge({phase:"input",priority:100},t=>{const e=performance.now(),n=_s._getInstance(t).buffer,r=n.lastTime[0];n.number[0]++,n.lastTime[0]=e,n.time[0]=e,r===0?n.delta[0]=.016:n.delta[0]=Math.min((e-r)/1e3,.1)}),gi=new WeakMap;function h_(t){if(gi.has(t))return;t.hasAttribute("tabindex")||t.setAttribute("tabindex","0");const e={eventsBuffer:[],onKeyDown:n=>{(n.key==="Tab"||n.key==="Alt"||n.key===" ")&&n.preventDefault(),e.eventsBuffer.push(n)},onKeyUp:n=>{e.eventsBuffer.push(n)},onBlur:()=>{e.eventsBuffer.push({type:"blur"})}};gi.set(t,e),t.addEventListener("keydown",e.onKeyDown),t.addEventListener("keyup",e.onKeyUp),t.addEventListener("blur",e.onBlur)}function p_(t){const e=gi.get(t);e&&(t.removeEventListener("keydown",e.onKeyDown),t.removeEventListener("keyup",e.onKeyUp),t.removeEventListener("blur",e.onBlur),gi.delete(t))}var m_=ge({phase:"input"},t=>{const e=Ve(t),n=gi.get(e.domElement);if(!n)return;ae(t,Vm,()=>{cn.reset(t)});const r=n.eventsBuffer.length>0,o=cn.read(t),s=!Fm(o.keysDownTrigger)||!Fm(o.keysUpTrigger);if(!r&&!s)return;const i=cn.write(t);Po(i.keysDownTrigger),Po(i.keysUpTrigger);for(const a of n.eventsBuffer){if(a.type==="blur"){Po(i.keysDown),i.shiftDown=!1,i.altDown=!1,i.modDown=!1;continue}const l=P[a.code];l!==void 0&&(a.type==="keydown"?(g_(i.keysDown,l)||mi(i.keysDownTrigger,l,!0),mi(i.keysDown,l,!0)):a.type==="keyup"&&(mi(i.keysDown,l,!1),mi(i.keysUpTrigger,l,!0)),i.shiftDown=a.shiftKey,i.altDown=a.altKey,i.modDown=a.ctrlKey||a.metaKey)}n.eventsBuffer.length=0});function g_(t,e){if(e<0||e>=t.length*8)return!1;const n=Math.floor(e/8),r=e%8;return(t[n]&1<<r)!==0}function Fm(t){for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}var yi=new WeakMap;function y_(t){if(yi.has(t))return;const e={eventsBuffer:[],onMouseMove:n=>{e.eventsBuffer.push({type:"mousemove",clientX:n.clientX,clientY:n.clientY})},onWheel:n=>{n.preventDefault(),e.eventsBuffer.push({type:"wheel",clientX:n.clientX,clientY:n.clientY,deltaX:n.deltaX,deltaY:n.deltaY,deltaMode:n.deltaMode})},onMouseEnter:()=>{e.eventsBuffer.push({type:"mouseenter"})},onMouseLeave:()=>{e.eventsBuffer.push({type:"mouseleave"})}};yi.set(t,e),window.addEventListener("mousemove",e.onMouseMove),t.addEventListener("wheel",e.onWheel,{passive:!1}),t.addEventListener("mouseenter",e.onMouseEnter),t.addEventListener("mouseleave",e.onMouseLeave)}function w_(t){const e=yi.get(t);e&&(window.removeEventListener("mousemove",e.onMouseMove),t.removeEventListener("wheel",e.onWheel),t.removeEventListener("mouseenter",e.onMouseEnter),t.removeEventListener("mouseleave",e.onMouseLeave),yi.delete(t))}var k_=ge({phase:"input"},t=>{const e=Ve(t),n=yi.get(e.domElement);if(!n)return;const r=bn.read(t),o=r.moveTrigger||r.wheelTrigger||r.enterTrigger||r.leaveTrigger,s=n.eventsBuffer.length>0;if(!o&&!s)return;const i=bn.write(t),a=Mt.read(t);i.moveTrigger=!1,i.wheelTrigger=!1,i.enterTrigger=!1,i.leaveTrigger=!1,i.wheelDeltaX=0,i.wheelDeltaY=0;for(const l of n.eventsBuffer)switch(l.type){case"mousemove":i.position=[l.clientX-a.left,l.clientY-a.top],i.moveTrigger=!0;break;case"wheel":i.wheelDeltaX=l.deltaX,i.wheelDeltaY=v_(l.deltaY,l.deltaMode),i.wheelTrigger=!0;break;case"mouseenter":i.enterTrigger=!0;break;case"mouseleave":i.leaveTrigger=!0;break}n.eventsBuffer.length=0});function v_(t,e){const r=typeof window<"u"?window.innerHeight:800;let o=t;return e===1?o*=16:e===2&&(o*=r),typeof navigator<"u"&&navigator.userAgent.includes("Firefox")&&(o*=4),typeof navigator<"u"&&(navigator.userAgent.includes("Mac")||navigator.userAgent.includes("Macintosh"))&&(o*=1.5),Math.min(Math.max(o,-100),100)}var wi=new WeakMap;function b_(t){if(wi.has(t))return;const e={eventsBuffer:[],frameCount:0,pointerEntityMap:new Map,onPointerDown:n=>{e.eventsBuffer.push({type:"pointerdown",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})},onContextMenu:n=>{n.preventDefault(),!e.eventsBuffer.some(o=>o.type==="pointerdown")&&e.eventsBuffer.push({type:"pointerdown",pointerId:0,clientX:n.clientX,clientY:n.clientY,button:2,pointerType:"mouse",pressure:.5,target:n.target})},onPointerMove:n=>{e.eventsBuffer.push({type:"pointermove",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})},onPointerUp:n=>{e.eventsBuffer.push({type:"pointerup",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})},onPointerCancel:n=>{e.eventsBuffer.push({type:"pointercancel",pointerId:n.pointerId,clientX:n.clientX,clientY:n.clientY,button:n.button,pointerType:n.pointerType,pressure:n.pressure,target:n.target})}};wi.set(t,e),t.addEventListener("pointerdown",e.onPointerDown),t.addEventListener("contextmenu",e.onContextMenu),window.addEventListener("pointermove",e.onPointerMove),window.addEventListener("pointerup",e.onPointerUp),window.addEventListener("pointercancel",e.onPointerCancel)}function S_(t){const e=wi.get(t);e&&(t.removeEventListener("pointerdown",e.onPointerDown),t.removeEventListener("contextmenu",e.onContextMenu),window.removeEventListener("pointermove",e.onPointerMove),window.removeEventListener("pointerup",e.onPointerUp),window.removeEventListener("pointercancel",e.onPointerCancel),wi.delete(t))}var E_=ge({phase:"input"},t=>{const e=Ve(t),{domElement:n}=e,r=wi.get(n);if(!r)return;r.frameCount++;const o=Mt.read(t),s=r.frameCount/60;for(const i of r.eventsBuffer)switch(i.type){case"pointerdown":{const a=[i.clientX-o.left,i.clientY-o.top],l=bt(t);J(t,l,Dt,{pointerId:i.pointerId,position:a,downPosition:a,downFrame:r.frameCount,button:Dt.getButton(i.button),pointerType:Dt.getType(i.pointerType),pressure:i.pressure,obscured:i.target!==n});const c=Dt.write(t,l);Ka(c,a,s),r.pointerEntityMap.set(i.pointerId,l);break}case"pointermove":{const a=r.pointerEntityMap.get(i.pointerId);if(a===void 0)break;const l=[i.clientX-o.left,i.clientY-o.top],c=Dt.write(t,a);Ka(c,l,s),c.pressure=i.pressure,c.obscured=i.target!==n;break}case"pointerup":case"pointercancel":{const a=r.pointerEntityMap.get(i.pointerId);if(a===void 0)break;const l=[i.clientX-o.left,i.clientY-o.top],c=Dt.write(t,a);Ka(c,l,s),qe(t,a),r.pointerEntityMap.delete(i.pointerId);break}}r.eventsBuffer.length=0}),ki=new WeakMap;function C_(t){if(ki.has(t))return;const e={needsUpdate:!1,resizeObserver:new ResizeObserver(()=>{e.needsUpdate=!0}),onScroll:()=>{e.needsUpdate=!0}};ki.set(t,e),e.resizeObserver.observe(t),window.addEventListener("scroll",e.onScroll,!0)}function x_(t){const e=ki.get(t);e&&(e.resizeObserver.disconnect(),window.removeEventListener("scroll",e.onScroll,!0),ki.delete(t))}var T_=ge({phase:"input"},t=>{const e=Ve(t),{domElement:n}=e,r=ki.get(n);if(!r||(_s.read(t).number===1&&(r.needsUpdate=!0),!r.needsUpdate))return;const s=Mt.write(t),i=n.getBoundingClientRect();s.left=i.left,s.top=i.top,s.width=i.width,s.height=i.height,r.needsUpdate=!1}),M_=re(t=>t.tracking(vn));function A_(t,e,n){const r=t[e];if(!r)return"auto";const o=r.makeSvg(n+r.rotationOffset);return`url("data:image/svg+xml,${encodeURIComponent(o.trim())}") ${r.hotspot[0]} ${r.hotspot[1]}, auto`}var __=ge({phase:"render",priority:-100},t=>{const e=M_.changed(t),n=_s.read(t);if(e.length===0&&n.number!==1)return;const{cursorKind:r,rotation:o}=vn.getEffective(t);if(!r){document.body.style.cursor="default";return}const{editor:s}=Ve(t),i=A_(s.cursors,r,o);document.body.style.cursor=i});function I_(t){const{editor:e}=Ve(t);return e.blockDefs}function Vt(t,e){return I_(t)[e]??Au.parse({tag:e})}function Wm(t,e){return Vt(t,e).editOptions.canEdit}function Um(t,e,n){if(O(t,e,ke)){const r=ke.getExtremaWorld(t,e);ee.setFromPoints(n,r)}else{const r=A.getCorners(t,e);ee.setFromPoints(n,r)}}function Ru(t,e){if(!O(t,e,Tt))return!1;const{sessionId:n}=Ve(t),r=Tt.read(t,e);return r.sessionId!==""&&r.sessionId!==n}var Hm=re(t=>t.with(A,Be));function B_(t,e,n){const r=[],o=Hm.current(t);for(const s of o)if(Be.containsPoint(t,s,e)){if(O(t,s,ke)){if(!ke.containsPointWorld(t,s,e))continue}else if(!A.containsPoint(t,s,e))continue;r.push(s)}return P_(t,r)}function N_(t,e,n){const r=[],o=n??Hm.current(t);for(const s of o){const{value:i}=Be.read(t,s);if(ee.intersects(e,i)){if(ee.contains(e,i)){r.push(s);continue}O(t,s,ke)?ke.intersectsAabbWorld(t,s,e)&&r.push(s):A.intersectsAabb(t,s,e)&&r.push(s)}}return r}function P_(t,e){return e.sort((n,r)=>{const o=A.read(t,n),s=A.read(t,r),i=Vt(t,o.tag).stratum,a=Vt(t,s.tag).stratum,l=_u[i],c=_u[a];if(c!==l)return c-l;const u=o.rank,f=s.rank;return!u&&!f?0:u?f?f>u?1:f<u?-1:0:-1:1})}var Bs=[1,0,0,1,0,0];function D_(t,e,n){const r=[],o=ot.bounds(e);for(const s of n){const i=Be.read(t,s);ee.intersects(o,i.value)&&(O(t,s,ke)?O_(t,s,e)&&r.push(s):ot.intersectsAabb(e,i.value)&&r.push(s))}return r}function O_(t,e,n){const r=ke.read(t,e);A.getUvToWorldMatrix(t,e,Bs);for(let o=0;o<r.arcCount;o++){const s=ke.getArcAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(Bs,i);const a=[s[2],s[3]];Ae.transformPoint(Bs,a);const l=[s[4],s[5]];Ae.transformPoint(Bs,l);const c=s[6],u=Me.create(i[0],i[1],a[0],a[1],l[0],l[1],c),f=ot.pointA(n),h=ot.pointB(n);if(Me.intersectsCapsule(u,f,h,ot.radius(n)))return!0}for(let o=0;o<r.capsuleCount;o++){const s=ke.getCapsuleAt(t,e,o),i=[s[0],s[1]];Ae.transformPoint(Bs,i);const a=[s[2],s[3]];Ae.transformPoint(Bs,a);const l=s[4],c=ot.create(i[0],i[1],a[0],a[1],l);if(ot.intersectsCapsule(n,c))return!0}return!1}var R_=re(t=>t.with(Cr));function z_(t){const e=Ve(t).sessionId;for(const n of R_.current(t))if(Cr.read(t,n).sessionId===e)return n;return null}var jm=re(t=>t.tracking(Dt)),$_=ge({phase:"render",priority:-100},t=>{if(bn.didMove(t)){const i=bn.read(t);Zm(t,i.position);return}if(jm.changed(t).length===0)return;const n=jm.current(t);let r=null,o=Number.MAX_SAFE_INTEGER;for(const i of n){const a=Dt.read(t,i);a.pointerId<o&&(o=a.pointerId,r=i)}const s=Dt.read(t,r);Zm(t,s.position)});function Zm(t,e){const n=z_(t);if(n===null)return;const r=Cr.write(t,n);r.position=he.toWorld(t,e)}var Km=re(t=>t.tracking(A)),Ym=re(t=>t.tracking(ke)),qm=re(t=>t.with(Tt).tracking(Tt)),L_=re(t=>t.with(Gr)),V_=re(t=>t.with(Dt));function Xm(t){for(const e of L_.current(t))O(t,e,Gr)&&nn(t,e,Gr)}function F_(t,e){for(const n of e)return Ru(t,n)?void 0:n}function W_(t,e){const r=et.read(t).leftMouseTool==="select";if(Xm(t),!r)return;const o=F_(t,e);o!==void 0&&J(t,o,Gr,{})}function U_(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var vi=new Set,bi=new Set,H_=ge({phase:"capture",priority:100},t=>{vi.clear();for(const m of Km.added(t))vi.add(m);for(const m of Ym.added(t))vi.add(m);bi.clear();for(const m of Km.changed(t))bi.add(m);for(const m of Ym.changed(t))bi.add(m);for(const m of vi){O(t,m,Be)||J(t,m,Be,{value:[0,0,0,0]});const g=Be.write(t,m);Um(t,m,g.value)}for(const m of bi){const g=Be.write(t,m);Um(t,m,g.value)}const e=bn.didMove(t),n=bn.didLeave(t),r=bn.didScroll(t),o=vi.size>0||bi.size>0,s=qm.added(t),i=qm.removed(t),a=s.length>0||i.length>0;if(!e&&!n&&!r&&!o&&!a)return;if(n){eo.clear(t),Xm(t);return}const l=bn.getPosition(t),c=he.toWorld(t,l),u=B_(t,c),f=eo.getAll(t),h=!U_(u,f);h&&eo.setAll(t,u),!(V_.current(t).length>0)&&(h||a)&&W_(t,u)}),j_=re(t=>t.with(de,A)),Z_=ge({phase:"input",priority:100},t=>{const e=j_.added(t);for(const n of e){const r=A.read(t,n);if(r.rank===""){const o=A.write(t,n);o.rank=Dn.genNext(t)}else Dn.add(t,r.rank)}}),K_=re(t=>t.tracking(he)),Y_=re(t=>t.with(de,A,Be)),q_=re(t=>t.with(de,A,Be)),X_=[0,0,0,0],G_=ge({phase:"render",priority:90},t=>{if(K_.changed(t).length===0&&q_.addedOrRemoved(t).length===0)return;const e=he.read(t),n=he.getAabb(t,X_);if(e.canSeeBlocks&&e.lastSeenBlock!==null&&O(t,e.lastSeenBlock,Be)){const i=Be.read(t,e.lastSeenBlock);if(ee.intersects(n,i.value))return}let r=null;for(const i of Y_.current(t)){const a=Be.read(t,i);if(ee.intersects(n,a.value)){r=i;break}}const o=r!==null;if(o===e.canSeeBlocks){r!==e.lastSeenBlock&&(he.write(t).lastSeenBlock=r);return}const s=he.write(t);s.canSeeBlocks=o,s.lastSeenBlock=r}),Gm=re(t=>t.with(A).tracking(Qr)),qa=[0,0],Xa=[0,0],J_=ge({phase:"render",priority:100},t=>{const e=he.read(t),n=Nu.read(t);if(!xt.approxEqual(e.zoom,n.lastZoom)){for(const o of Gm.current(t))Jm(t,o,e.zoom);Nu.write(t).lastZoom=e.zoom}for(const o of Gm.addedOrChanged(t))Jm(t,o,e.zoom)});function Jm(t,e,n){const r=A.write(t,e),o=Qr.read(t,e),s=1/n,i=1+(s-1)*o.scaleMultiplier[0],a=1+(s-1)*o.scaleMultiplier[1];qa[0]=o.startSize[0]*i,qa[1]=o.startSize[1]*a,L.copy(Xa,o.startSize),L.sub(Xa,qa),L.multiply(Xa,o.anchor),L.copy(r.position,o.startPosition),L.add(r.position,Xa),L.copy(r.size,qa)}var Q_={name:HA,singletons:Object.values($m).filter(t=>t instanceof St),components:Object.values(Im).filter(t=>t instanceof Kt),blockDefs:[{tag:"sticky-note",components:[yn,at,No],editOptions:{canEdit:!0}},{tag:"text",components:[at],resizeMode:"text",editOptions:{canEdit:!0,removeWhenTextEmpty:!0}},{tag:"image",components:[pi,Bo],resizeMode:"scale"},{tag:"shape",components:[wn,at,No],resizeMode:"free",editOptions:{canEdit:!0}}],systems:[f_,Z_,m_,k_,T_,E_,H_,d_,J_,G_,__,$_],setup(t){const{domElement:e}=Ve(t);h_(e),y_(e),C_(e),b_(e)},teardown(t){const{domElement:e}=Ve(t);p_(e),w_(e),x_(e),S_(e)}},e2=qt({name:dt(),displayName:dt(),url:dt(),previewImage:dt().optional(),selectable:Lt().default(!0),weights:mn(Je()).default([400,700]),italics:Lt().default(!0)}),t2=class{constructor(){this.loadedFonts=new Set}async loadFonts(t){const e=t.filter(r=>!this.loadedFonts.has(r.name));if(e.length===0)return;const n=e.map(r=>this.loadSingleFont(r));await Promise.all(n)}buildGoogleFontsUrl(t){const e=t.url;if(!e.includes("fonts.googleapis.com"))return e;const n=new URL(e),r=n.searchParams.get("family");if(!r)return e;const o=r.split(":")[0],s=t.weights,i=[];if(t.italics){for(const a of s)i.push(`0,${a}`);for(const a of s)i.push(`1,${a}`);n.searchParams.set("family",`${o}:ital,wght@${i.join(";")}`)}else n.searchParams.set("family",`${o}:wght@${s.join(";")}`);return n.toString()}loadSingleFont(t){return this.loadedFonts.add(t.name),new Promise((e,n)=>{const r=document.createElement("link");r.rel="stylesheet",r.href=this.buildGoogleFontsUrl(t),r.onload=async()=>{try{const o=this.getFontLoadPromises(t);await Promise.all(o),await document.fonts.ready,e()}catch(o){n(new Error(`Failed to load font face for: ${t.name}. ${o}`))}},r.onerror=()=>{n(new Error(`Failed to load font stylesheet: ${t.name}`))},document.head.appendChild(r)})}getFontLoadPromises(t){const e=[],n=t.name;for(const r of t.weights)e.push(document.fonts.load(`${r} 12px "${n}"`)),t.italics&&e.push(document.fonts.load(`italic ${r} 12px "${n}"`));return e}isLoaded(t){return this.loadedFonts.has(t)}getLoadedFonts(){return this.loadedFonts}};function n2(t){return typeof t=="function"?t({}):t}function r2(t){const e=[],n=new Set,r=new Set,o=new Map(t.map(i=>[i.name,i]));function s(i){if(!n.has(i.name)){if(r.has(i.name))throw new Error(`Circular plugin dependency detected: ${i.name}`);r.add(i.name);for(const a of i.dependencies??[]){const l=o.get(a);if(!l)throw new Error(`Plugin "${i.name}" depends on "${a}" which is not registered`);s(l)}r.delete(i.name),n.add(i.name),e.push(i)}}for(const i of t)s(i);return e}var Qm=["input","capture","update","render"];function o2(t){const e=new Map;for(const r of Qm)e.set(r,[]);for(const r of t)e.get(r.phase).push(r);const n=[];for(const r of Qm){const o=e.get(r),s=new Map;for(const a of o){const l=s.get(a.priority)??[];l.push(a),s.set(a.priority,l)}const i=[...s.keys()].sort((a,l)=>l-a);for(const a of i)n.push(s.get(a))}return n}var s2=class{constructor(e,n){this.cursors={},this.blockDefs={},this.fonts=[],this.components=[],this.singletons=[];const r=WA.parse(n??{}),{plugins:o,maxEntities:s}=r,i=Om.parse(r.user??{});this.userData=i,this.gridOptions=VA.parse(r.grid??{}),this.controlsOptions=FA.parse(r.controls??{});const a=o.map(n2),l=r2([Q_,...a]),c=[Is,de];for(const v of l)v.components&&c.push(...v.components),v.singletons&&c.push(...v.singletons);c.push(...r.components),c.push(...r.singletons);const u=r.keybinds;if(!r.omitPluginKeybinds)for(const v of l)v.keybinds&&u.push(...v.keybinds);this.keybinds=u;const f={};for(const v of r.blockDefs){const E=Au.parse(v);f[E.tag]=E}for(const v of l)if(v.blockDefs)for(const E of v.blockDefs){const T=Au.parse(E);f[T.tag]=T}this.blockDefs=f;const h={};if(Object.assign(h,r.cursors),!r.omitPluginCursors)for(const v of l)v.cursors&&Object.assign(h,v.cursors);this.cursors=h,this.fontLoader=new t2;const p=[...r.fonts];if(!r.omitPluginFonts)for(const v of l)v.fonts&&p.push(...v.fonts);this.fonts=p.map(v=>e2.parse(v));const m={};for(const v of l)v.resources!==void 0&&(m[v.name]=v.resources);const g=new Map,y=new Map,w=new Map,k=new Map,b={domElement:e,editor:this,userId:i.userId,sessionId:i.sessionId,pluginResources:m,componentsByName:g,singletonsByName:y,componentsById:w,singletonsById:k};this.world=new oS(c,{maxEntities:s,resources:b});const S=[];for(const v of l)v.systems&&S.push(...v.systems);S.push(...r.systems),this.systemBatches=o2(S),this.plugins=new Map(l.map(v=>[v.name,v]));for(const v of l){if(v.components)for(const E of v.components){const T=E._getComponentId(this.ctx);w.set(T,E),g.set(E.name,E)}if(v.singletons)for(const E of v.singletons){const T=E._getComponentId(this.ctx);k.set(T,E),y.set(E.name,E)}}for(const v of r.components){const E=v._getComponentId(this.ctx);w.set(E,v),g.set(v.name,v)}for(const v of r.singletons){const E=v._getComponentId(this.ctx);k.set(E,v),y.set(v.name,v)}this.components=[...g.values()],this.singletons=[...y.values()]}get ctx(){return this.world._getContext()}async initialize(){this.fonts.length>0&&await this.fontLoader.loadFonts(this.fonts),Ot.copy(this.ctx,this.gridOptions),et.copy(this.ctx,this.controlsOptions),this.nextTick(e=>{const n=bt(e);J(e,n,de,{id:crypto.randomUUID()}),J(e,n,Cr,{userId:this.userData.userId,sessionId:this.userData.sessionId,color:this.userData.color,name:this.userData.name,avatar:this.userData.avatar})});for(const e of this.plugins.values())e.setup&&await e.setup(this.ctx)}async tick(){this.world.sync();for(const n of this.systemBatches){const r=n.map(o=>o._system);await this.world.execute(...r)}const e=this.ctx.eventBuffer.getWriteIndex();this.ctx.prevEventIndex=e,this.ctx.currEventIndex=e,c_(this.ctx)}nextTick(e){return this.world.nextSync(n=>{e(n)})}command(e,...n){const r=n[0];this.nextTick(o=>{e.spawn(o,r)})}subscribe(e,n){return this.world.subscribe(e,(r,o)=>{n(r,o)})}_getContext(){return this.ctx}dispose(){const e=Array.from(this.plugins.values()).reverse();for(const n of e)n.teardown&&n.teardown(this.ctx);this.world.dispose(),this.plugins.clear(),this.systemBatches=[]}};function i2(t,e,n,r){if(r.length===0)return{value:e,context:n};let o=t.resolveState({value:String(e),context:n});for(const s of r){const[i,a]=CA(t,o,s);o=i;for(const l of a)typeof l.exec=="function"&&l.exec(l.info,l.params)}return{value:o.value,context:o.context}}var a2=class extends St{constructor(t,e){super({name:t,sync:"none"},e)}getState(t){return this.read(t).state}getContext(t){const e=this.snapshot(t),n={};for(const r of Object.keys(e))r!=="state"&&(n[r]=e[r]);return n}run(t,e,n){const r=this.getState(t),o=this.getContext(t),s=i2(e,r,o,n),i=this.write(t);i.state=s.value;for(const[a,l]of Object.entries(s.context))i[a]=l;return s}};function to(t,e){return new a2(t,e)}function l2(t){const e=_s.read(t);return{type:"frame",ctx:t,delta:e.delta,frameNumber:e.number,time:e.time}}function c2(t,e){const n=[];for(const r of e)cn.isKeyDownTrigger(t,r)&&n.push({type:"keyDown",key:r,ctx:t}),cn.isKeyUpTrigger(t,r)&&n.push({type:"keyUp",key:r,ctx:t});return n}function eg(t){const e=[],n=bn.read(t),r=[n.position[0],n.position[1]],o=he.toWorld(t,r);return n.wheelTrigger&&e.push({type:"wheel",ctx:t,screenPosition:r,worldPosition:o,wheelDeltaX:n.wheelDeltaX,wheelDeltaY:n.wheelDeltaY}),n.moveTrigger&&e.push({type:"mouseMove",ctx:t,screenPosition:r,worldPosition:o,wheelDeltaX:0,wheelDeltaY:0}),e}var u2=3,d2=30,Ga=re(t=>t.tracking(Dt)),tg=new Map;function f2(t){const e=t.readerId;let n=tg.get(e);return n||(n={prevPositions:new Map,prevModifiers:{shiftDown:!1,altDown:!1,modDown:!1},prevCamera:{left:0,top:0,zoom:1}},tg.set(e,n)),n}function xr(t,e,n={}){if(e.length===0)return[];const{includeFrameEvent:r=!1,clickMoveThreshold:o=u2,clickFrameThreshold:s=d2}=n,i=f2(t),a=_s.read(t).number,l=[],c=cn.read(t),u={shiftDown:c.shiftDown,altDown:c.altDown,modDown:c.modDown},f=he.read(t),h=F=>{const j=Dt.read(t,F);return e.includes(j.button)},p=eo.getAll(t),m=(F,j)=>{const M=Dt.read(t,j),V=[M.position[0],M.position[1]],K=he.toWorld(t,V);return{type:F,ctx:t,screenPosition:V,worldPosition:K,velocity:[M._velocity[0],M._velocity[1]],pressure:M.pressure,button:M.button,pointerType:M.pointerType,obscured:M.obscured,shiftDown:u.shiftDown,altDown:u.altDown,modDown:u.modDown,cameraLeft:f.left,cameraTop:f.top,cameraZoom:f.zoom,pointerId:j,intersects:p}},g=Ga.added(t),y=Ga.removed(t),w=Ga.changed(t),k=Ga.current(t),b=g.filter(h),S=y.filter(h),v=w.filter(h),E=Array.from(k).filter(h),T=cn.isKeyDownTrigger(t,Gt.Escape),_=E.length>1&&b.length>0;if((T||_)&&E.length>0)return l.push(m("cancel",E[0])),l;if(b.length>0&&E.length===1){const F=E[0],j=Dt.read(t,F);j.obscured||(l.push(m("pointerDown",F)),i.prevPositions.set(F,[j.position[0],j.position[1]]))}if(S.length>0&&E.length===0){const F=S[0],j=Dt.read(t,F);l.push(m("pointerUp",F));const M=i.prevPositions.get(F);if(M){const V=[j.position[0],j.position[1]],K=L.distance(M,V),se=a-j.downFrame;K<o&&se<s&&l.push(m("click",F)),i.prevPositions.delete(F)}}const I=u.shiftDown!==i.prevModifiers.shiftDown||u.altDown!==i.prevModifiers.altDown||u.modDown!==i.prevModifiers.modDown,z=f.left!==i.prevCamera.left||f.top!==i.prevCamera.top||f.zoom!==i.prevCamera.zoom;return(v.length>0||I||z)&&E.length===1&&l.push(m("pointerMove",E[0])),r&&E.length===1&&l.push(m("frame",E[0])),i.prevModifiers={...u},i.prevCamera={left:f.left,top:f.top,zoom:f.zoom},l}var Jt={ECS:1,History:2,Persistence:3,Websocket:4},h2=1;function ng(t){const e=new Set,n=new Map;for(const r of t){if(e.has(r.name))throw new Error(`Duplicate migration name: "${r.name}"`);if(e.add(r.name),r.supersedes!=null){if(!e.has(r.supersedes))throw new Error(`Migration "${r.name}" supersedes "${r.supersedes}", which ${t.some(o=>o.name===r.supersedes)?"must come before it":"does not exist"}`);if(n.has(r.supersedes))throw new Error(`Migration "${r.supersedes}" is already superseded by "${n.get(r.supersedes)}"`);n.set(r.supersedes,r.name)}}}function zu(t,e){let n=null;for(const[r,o]of Object.entries(t)){if(o._exists!==!0)continue;const s=r.slice(r.indexOf("/")+1),i=e.get(s);if(!i||i.migrations.length===0)continue;const{_exists:a,_version:l,...c}=o,u=p2(c,l??null,i.migrations);u.changed&&(n||(n={...t}),n[r]={...u.data,_exists:!0,_version:u.version})}return n??t}function p2(t,e,n){if(n.length===0)return{data:t,version:e,changed:!1};const r=new Set;for(const l of n)l.supersedes!=null&&r.add(l.supersedes);let o=0;if(e!==null){const l=n.findIndex(c=>c.name===e);if(l===-1)throw new Error(`Unknown migration version "${e}" — known versions: ${n.map(c=>`"${c.name}"`).join(", ")}`);o=l+1}let s=t,i=e,a=!1;for(let l=o;l<n.length;l++){const c=n[l];r.has(c.name)||(s=c.upgrade(s,i),i=c.name,a=!0)}return{data:s,version:i,changed:a}}function $u(t,e){if(t===e)return!0;if(t===null||e===null||typeof t!=typeof e)return!1;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!$u(t[n],e[n]))return!1;return!0}if(typeof t=="object"&&typeof e=="object"){const n=t,r=e,o=Object.keys(n),s=Object.keys(r);return o.length!==s.length?!1:o.every(i=>$u(n[i],r[i]))}return!1}function un(...t){const e={},n=new Set;for(const r of t)for(const[o,s]of Object.entries(r)){const i=e[o];s._exists===!1?n.has(o)?(delete e[o],n.delete(o)):e[o]={_exists:!1}:i===void 0||i._exists===!1?(i===void 0&&s._exists===!0&&n.add(o),e[o]={...s}):e[o]={...i,...s}}return e}function rg(t,e){if(Object.keys(e).length===0)return t;const n={};for(const[r,o]of Object.entries(t)){const s=e[r];if(s===void 0){n[r]=o;continue}if(o._exists===!1){n[r]=o;continue}if(s._exists===!1)continue;const i={};let a=!1;for(const[l,c]of Object.entries(o))l in s||(i[l]=c,a=!0);a&&(n[r]=i)}return n}var m2=1e3;async function og(t,e,n){const r=await dh(t,1,{upgrade(o){o.objectStoreNames.contains(e)||o.createObjectStore(e)}});return new g2(r,e,n)}var g2=class{constructor(e,n,r){x(this,"pending",new Map);x(this,"flushTimer",null);x(this,"flushIntervalMs");this.db=e,this.storeName=n,this.flushIntervalMs=(r==null?void 0:r.flushIntervalMs)??m2}async get(e){const n=this.pending.get(e);return n?n.type==="put"?n.value:void 0:this.db.get(this.storeName,e)}put(e,n){this.pending.set(e,{type:"put",value:n}),this.scheduleFlush()}delete(e){this.pending.set(e,{type:"delete"}),this.scheduleFlush()}async getAllEntries(){const n=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName),r=await n.getAllKeys(),o=await n.getAll(),s=new Map;for(let i=0;i<r.length;i++)s.set(r[i],o[i]);for(const[i,a]of this.pending)a.type==="put"?s.set(i,a.value):s.delete(i);return Array.from(s.entries())}async clear(){this.pending.clear(),this.cancelFlush();const e=this.db.transaction(this.storeName,"readwrite");e.objectStore(this.storeName).clear(),await e.done}close(){this.flushSync(),this.db.close()}scheduleFlush(){if(this.flushIntervalMs===0){this.flush().catch(console.error);return}this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(console.error)},this.flushIntervalMs))}cancelFlush(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async flush(){if(this.pending.size===0)return;const e=new Map(this.pending);this.pending.clear();const n=this.db.transaction(this.storeName,"readwrite"),r=n.objectStore(this.storeName);for(const[o,s]of e)s.type==="put"?r.put(s.value,o):r.delete(o);await n.done}flushSync(){this.cancelFlush(),this.pending.size!==0&&this.flush().catch(console.error)}},y2=1e3/30,w2=1e3,k2=(hr=class{constructor(e){x(this,"url");x(this,"clientId");x(this,"ws",null);x(this,"pendingDocumentPatches",[]);x(this,"pendingEphemeralPatches",[]);x(this,"lastTimestamp",0);x(this,"messageCounter",0);x(this,"inFlight",new Map);x(this,"startOffline");x(this,"usePersistence");x(this,"documentId");x(this,"store",null);x(this,"offlineBuffer",{});x(this,"connectedUsers",0);x(this,"intentionallyClosed",!1);x(this,"reconnectTimer",null);x(this,"reconnectDelay",500);x(this,"documentSendBuffer",[]);x(this,"ephemeralSendBuffer",[]);x(this,"lastSendTime",0);x(this,"localEphemeralState",{});x(this,"remoteEphemeralState",{});x(this,"token");x(this,"onVersionMismatch");x(this,"onConnectivityChange");x(this,"componentsByName");this.url=e.url,this.clientId=e.clientId,this.startOffline=e.startOffline??!1,this.usePersistence=e.usePersistence,this.documentId=e.documentId,this.token=e.token,this.onVersionMismatch=e.onVersionMismatch,this.onConnectivityChange=e.onConnectivityChange;const n=new Map;for(const r of[...e.components,...e.singletons])n.set(r.name,r);this.componentsByName=n}get isOnline(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}async init(){if(this.usePersistence)try{this.store=await og(`${this.documentId}-ws`,"meta");const e=await this.store.get("offlineBuffer"),n=await this.store.get("lastTimestamp");e&&(this.offlineBuffer=e),n&&(this.lastTimestamp=n)}catch(e){console.error("Failed to load websocket offline state:",e)}if(this.startOffline){this.intentionallyClosed=!0;return}this.intentionallyClosed=!1;try{await this.connectWs()}catch(e){console.warn("WebSocket connection failed:",e),this.scheduleReconnect()}}connectWs(){return this.inFlight.clear(),new Promise((e,n)=>{const r=new URL(this.url);r.searchParams.set("roomId",this.documentId),r.searchParams.set("clientId",this.clientId),this.token&&r.searchParams.set("token",this.token);const o=new WebSocket(r.toString());o.addEventListener("open",()=>{var i;this.ws=o,(i=this.onConnectivityChange)==null||i.call(this,!0);const s={type:"reconnect",lastTimestamp:this.lastTimestamp,protocolVersion:h2,...Object.keys(this.offlineBuffer).length>0&&{documentPatches:[this.offlineBuffer]},...Object.keys(this.localEphemeralState).length>0&&{ephemeralPatches:[this.localEphemeralState]}};o.send(JSON.stringify(s)),e()}),o.addEventListener("error",()=>{n(new Error(`WebSocket failed to connect to ${this.url}`))}),o.addEventListener("message",s=>{this.handleMessage(s.data)}),o.addEventListener("close",()=>{var s;this.ws=null,(s=this.onConnectivityChange)==null||s.call(this,!1),this.clearRemoteEphemeral(),this.intentionallyClosed||this.scheduleReconnect()})})}push(e){const n=[],r=[];for(const o of e)o.origin!==Jt.Websocket&&o.origin!==Jt.Persistence&&o.syncBehavior!=="local"&&(o.syncBehavior==="ephemeral"?r.push(o.patch):n.push(o.patch));if(!this.isOnline){n.length>0&&(this.offlineBuffer=un(this.offlineBuffer,...n),this.persistOfflineBuffer()),r.length>0&&(this.localEphemeralState=un(this.localEphemeralState,...r));return}n.length>0&&this.documentSendBuffer.push(...n),r.length>0&&this.ephemeralSendBuffer.push(...r),this.flushIfReady()}get sendInterval(){return this.connectedUsers>1?y2:w2}flushIfReady(){performance.now()-this.lastSendTime>=this.sendInterval&&this.flush()}flush(){if(!this.isOnline)return;const e=[];Object.keys(this.offlineBuffer).length>0&&(e.push(this.offlineBuffer),this.offlineBuffer={}),e.push(...this.documentSendBuffer),this.documentSendBuffer=[];const n=this.ephemeralSendBuffer;if(this.ephemeralSendBuffer=[],n.length>0&&(this.localEphemeralState=un(this.localEphemeralState,...n)),e.length===0&&n.length===0)return;const r=`${this.clientId}-${++this.messageCounter}`;e.length>0&&this.inFlight.set(r,un(...e));const o={type:"patch",messageId:r,...e.length>0&&{documentPatches:e},...n.length>0&&{ephemeralPatches:n}};this.ws.send(JSON.stringify(o)),this.lastSendTime=performance.now()}pull(){const e=[];if(this.pendingDocumentPatches.length>0){const n=un(...this.pendingDocumentPatches);this.pendingDocumentPatches=[];const r=zu(n,this.componentsByName),o=zu(this.offlineBuffer,this.componentsByName),s=rg(r,o);this.clearPersistedOfflineBuffer(),Object.keys(s).length>0&&e.push({patch:s,origin:Jt.Websocket,syncBehavior:"document"})}if(this.pendingEphemeralPatches.length>0){const n=un(...this.pendingEphemeralPatches);this.pendingEphemeralPatches=[],e.push({patch:n,origin:Jt.Websocket,syncBehavior:"ephemeral"})}return e}disconnect(){this.intentionallyClosed=!0,this.clearReconnectTimer(),this.ws&&(this.ws.close(),this.ws=null)}close(){this.disconnect(),this.store&&(this.store.close(),this.store=null)}async reconnect(){this.intentionallyClosed=!1,this.reconnectDelay=hr.MIN_RECONNECT_DELAY,this.clearReconnectTimer(),await this.connectWs()}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}scheduleReconnect(){this.clearReconnectTimer(),this.reconnectTimer=setTimeout(async()=>{this.reconnectTimer=null;try{await this.connectWs(),this.reconnectDelay=hr.MIN_RECONNECT_DELAY}catch{this.reconnectDelay=Math.min(this.reconnectDelay*2,hr.MAX_RECONNECT_DELAY),this.scheduleReconnect()}},this.reconnectDelay)}handleMessage(e){var r;let n;try{n=JSON.parse(e)}catch{return}switch(n.type){case"patch":{if(this.lastTimestamp=n.timestamp,this.persistTimestamp(),n.documentPatches&&n.documentPatches.length>0){const o=this.stripInFlightFields(n.documentPatches);this.pendingDocumentPatches.push(...o)}n.ephemeralPatches&&n.ephemeralPatches.length>0&&(this.pendingEphemeralPatches.push(...n.ephemeralPatches),this.remoteEphemeralState=un(this.remoteEphemeralState,...n.ephemeralPatches));break}case"ack":this.lastTimestamp=n.timestamp,this.persistTimestamp(),this.inFlight.delete(n.messageId);break;case"clientCount":this.connectedUsers=n.count;break;case"version-mismatch":this.disconnect(),(r=this.onVersionMismatch)==null||r.call(this,n.serverProtocolVersion);break}}stripInFlightFields(e){if(this.inFlight.size===0)return e;const n=un(...Array.from(this.inFlight.values())),r=[];for(const o of e){const s=rg(o,n);Object.keys(s).length>0&&r.push(s)}return r}clearRemoteEphemeral(){const e=Object.keys(this.remoteEphemeralState);if(e.length===0)return;const n={};for(const r of e)n[r]={_exists:!1};this.pendingEphemeralPatches.push(n),this.remoteEphemeralState={}}persistOfflineBuffer(){!this.store||!this.usePersistence||this.store.put("offlineBuffer",this.offlineBuffer)}persistTimestamp(){!this.store||!this.usePersistence||this.store.put("lastTimestamp",this.lastTimestamp)}clearPersistedOfflineBuffer(){Object.keys(this.offlineBuffer).length!==0&&(this.offlineBuffer={},!(!this.store||!this.usePersistence)&&this.store.delete("offlineBuffer"))}},x(hr,"MIN_RECONNECT_DELAY",500),x(hr,"MAX_RECONNECT_DELAY",1e4),hr),sg=class extends zc{constructor(e,n){super(n,!1);x(this,"name");x(this,"sync");x(this,"migrations");x(this,"excludeFromHistory");this.name=e.name,this.sync=e.sync??"none",this.migrations=e.migrations??[],this.excludeFromHistory=e.excludeFromHistory??[],this.migrations.length>0&&ng(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(e,n){return{...super.snapshot(e,n),_exists:!0,_version:this.currentVersion}}};function v2(t,e){return new sg(t,e)}var ig=class extends Ah{constructor(e,n){super(n);x(this,"name");x(this,"sync");x(this,"migrations");x(this,"excludeFromHistory");this.name=e.name,this.sync=e.sync??"none",this.migrations=e.migrations??[],this.excludeFromHistory=e.excludeFromHistory??[],this.migrations.length>0&&ng(this.migrations)}get currentVersion(){return this.migrations.length>0?this.migrations[this.migrations.length-1].name:null}default(){return{...super.default(),_exists:!0,_version:this.currentVersion}}snapshot(e){return{...super.snapshot(e),_exists:!0,_version:this.currentVersion}}};function ag(t,e){return new ig(t,e)}var Si=$c({id:C.string().max(36)}),Lu="SINGLETON";function b2(t,e){if(t._exists===!1&&e._exists===!1)return null;if(t._exists===!1)return e;if(e._exists===!1)return null;const n={};let r=!1;for(const o in e){if(o==="_exists")continue;const s=t[o],i=e[o];$u(s,i)||(n[o]=i,r=!0)}return r?n:null}var S2=class{constructor(t){x(this,"ctx");x(this,"components");x(this,"singletons");x(this,"componentMap",new Map);x(this,"componentsByName",new Map);x(this,"stableIdToEntity",new Map);x(this,"entityToStableId",new Map);x(this,"prevState",{});x(this,"eventIndex",0);x(this,"initialized",!1);this.components=t.components,this.singletons=t.singletons}async init(){}ensureInitialized(){if(this.initialized)return;this.initialized=!0;const t=this.ctx;for(const e of[...this.components,...this.singletons]){if(e.sync==="none")continue;const n=e._getComponentId(t);this.componentMap.set(n,e),this.componentsByName.set(e.name,e)}}pull(){this.ensureInitialized();const t=this.ctx,{events:e}=t.eventBuffer.readEvents(this.eventIndex);if(e.length===0)return[];const n={},r={},o={},s=a=>a==="ephemeral"?r:a==="local"?o:n;for(const a of e){const{entityId:l,eventType:c,componentId:u}=a;if(c===Ie.REMOVED){const y=this.entityToStableId.get(l);if(!y)continue;const w=`${y}/`;for(const k of Object.keys(this.prevState))if(k.startsWith(w)){const b=k.slice(w.length),S=this.componentsByName.get(b),v=s(S==null?void 0:S.sync);v[k]={_exists:!1},this.prevState[k]={_exists:!1}}this.stableIdToEntity.delete(y),this.entityToStableId.delete(l);continue}const f=this.componentMap.get(u);if(!f||!f.isSingleton&&!O(t,l,Si,!1))continue;const h=Si.read(t,l);let p;f.isSingleton?p=Lu:(p=h.id,this.stableIdToEntity.set(p,l),this.entityToStableId.set(l,p));const m=`${p}/${f.name}`,g=s(f.sync);switch(c){case Ie.COMPONENT_ADDED:{if(f.isSingleton)continue;const y=f.snapshot(t,l),w=this.translateRefsOutbound(f,y);g[m]=w,this.prevState[m]={...w};break}case Ie.COMPONENT_REMOVED:{if(f.isSingleton)continue;g[m]={_exists:!1},this.prevState[m]={_exists:!1};break}case Ie.CHANGED:{const y=f.isSingleton?f.snapshot(t):f.snapshot(t,l),w=this.translateRefsOutbound(f,y),k=this.prevState[m]??{_exists:!1},b=b2(k,w);if(!b)continue;g[m]=b,this.prevState[m]={...w};break}}}const i=[];return Object.keys(n).length>0&&i.push({patch:n,origin:Jt.ECS,syncBehavior:"document"}),Object.keys(r).length>0&&i.push({patch:r,origin:Jt.ECS,syncBehavior:"ephemeral"}),Object.keys(o).length>0&&i.push({patch:o,origin:Jt.ECS,syncBehavior:"local"}),i}push(t){const e=this.ctx;for(const{patch:n,origin:r}of t)if(r!==Jt.ECS){for(const[o,s]of Object.entries(n)){if(!s._exists)continue;const i=o.indexOf("/"),a=o.slice(0,i);if(a!==Lu&&!this.stableIdToEntity.has(a)){const l=bt(e);J(e,l,Si,{id:a}),this.stableIdToEntity.set(a,l),this.entityToStableId.set(l,a)}}for(const[o,s]of Object.entries(n)){const i=o.indexOf("/"),a=o.slice(0,i),l=o.slice(i+1),c=this.componentsByName.get(l);if(!c)continue;if(a===Lu){if(s._exists===!1)continue;c.patch(e,s),this.prevState[o]={...this.prevState[o],...s};continue}const u=this.stableIdToEntity.get(a);if(u!==void 0){if(s._exists===!1)O(e,u,c,!1)&&nn(e,u,c),this.prevState[o]={_exists:!1};else if(s._exists){const f=this.translateRefsInbound(c,s);O(e,u,c,!1)?c.copy(e,u,f):J(e,u,c,f),this.prevState[o]={...s}}else if(u!==void 0&&O(e,u,c,!1)){const f=this.translateRefsInbound(c,s);c.patch(e,u,f),this.prevState[o]={...this.prevState[o],...s}}}}}this.eventIndex=e.eventBuffer.getWriteIndex()}translateRefsOutbound(t,e){const n=t.schema;let r=!1;for(const s in n)if(n[s].def.type==="ref"){r=!0;break}if(!r)return e;const o={...e};for(const s in n)if(n[s].def.type==="ref"&&o[s]!=null){const i=o[s];o[s]=this.entityToStableId.get(i)??null}return o}translateRefsInbound(t,e){const n=t.schema;let r=!1;for(const s in n)if(n[s].def.type==="ref"){r=!0;break}if(!r)return e;const o={...e};for(const s in n)if(n[s].def.type==="ref"&&o[s]!=null){const i=o[s];o[s]=this.stableIdToEntity.get(i)??null}return o}close(){}},E2=class{constructor(t){x(this,"state",{});x(this,"undoStack",[]);x(this,"redoStack",[]);x(this,"pendingForward",{});x(this,"pendingInverse",{});x(this,"pendingPullPatches",[]);x(this,"dirty",!1);x(this,"commitCheckpointAfterFrames");x(this,"maxHistoryStackSize");x(this,"checkpoints",new Map);x(this,"settledCallbacks",[]);x(this,"cancelCommitSettled",null);x(this,"excludedFields",new Map);this.commitCheckpointAfterFrames=t.commitCheckpointAfterFrames??60,this.maxHistoryStackSize=t.maxHistoryStackSize??100;for(const e of t.components)e.excludeFromHistory.length>0&&this.excludedFields.set(e.name,new Set(e.excludeFromHistory));for(const e of t.singletons)e.excludeFromHistory.length>0&&this.excludedFields.set(e.name,new Set(e.excludeFromHistory))}async init(){}push(t){var n;const e=t.filter(r=>r.origin===Jt.ECS&&r.syncBehavior!=="ephemeral"&&r.syncBehavior!=="local");for(const r of t)if(r.syncBehavior!=="ephemeral")if(r.origin===Jt.ECS&&r.syncBehavior!=="local"){if(Object.keys(r.patch).length===0)continue;const o=this.applyAndComputeInverse(r.patch);let s=r.patch,i=o;if(this.excludedFields.size>0&&(s=this.filterExcludedFields(r.patch),i=this.filterExcludedFields(o,!0),Object.keys(s).length===0))continue;this.pendingForward=un(this.pendingForward,s),this.pendingInverse=un(i,this.pendingInverse),this.dirty=!0,(n=this.cancelCommitSettled)==null||n.call(this),this.cancelCommitSettled=this.onSettled(()=>this.commitPendingDelta(),{frames:this.commitCheckpointAfterFrames}),this.redoStack=[]}else this.applyToState(r.patch);this.processSettledCallbacks(e.length===0)}pull(){if(this.pendingPullPatches.length===0)return[];const t=un(...this.pendingPullPatches);return this.pendingPullPatches=[],[{patch:t,origin:Jt.History,syncBehavior:"document"}]}undo(){if(this.dirty&&this.commitPendingDelta(),this.undoStack.length===0)return!1;const t=this.undoStack.pop(),e=this.applyAndComputeInverse(t.inverse);this.redoStack.push({forward:e,inverse:t.inverse}),this.pendingPullPatches.push(t.inverse);for(const[n,r]of this.checkpoints)r>this.undoStack.length&&this.checkpoints.delete(n);return!0}redo(){if(this.redoStack.length===0)return!1;const t=this.redoStack.pop(),e=this.applyAndComputeInverse(t.forward);return this.undoStack.push({forward:t.forward,inverse:e}),this.pendingPullPatches.push(t.forward),!0}canUndo(){return this.undoStack.length>0||this.dirty}canRedo(){return this.redoStack.length>0}close(){var t;(t=this.cancelCommitSettled)==null||t.call(this),this.cancelCommitSettled=null,this.settledCallbacks=[]}createCheckpoint(){const t=crypto.randomUUID();return this.checkpoints.set(t,this.undoStack.length),t}revertToCheckpoint(t){const e=this.checkpoints.get(t);if(e===void 0)return!1;if(this.commitPendingDelta(),this.undoStack.length<=e)return this.checkpoints.delete(t),!1;for(;this.undoStack.length>e;){const n=this.undoStack.pop();this.applyToState(n.inverse),this.pendingPullPatches.push(n.inverse)}return this.redoStack=[],this.checkpoints.delete(t),!0}squashToCheckpoint(t){const e=this.checkpoints.get(t);if(e===void 0)return!1;if(this.commitPendingDelta(),this.undoStack.length<=e)return this.checkpoints.delete(t),!1;const n=this.undoStack.splice(e),r=un(...n.map(s=>s.forward)),o=un(...n.map(s=>s.inverse));for(const s of Object.keys(o))s in r||delete o[s];return Object.keys(r).length===0?(this.checkpoints.delete(t),!0):(this.undoStack.push({forward:r,inverse:o}),this.checkpoints.delete(t),!0)}onSettled(t,e){const n={callback:t,requiredFrames:e.frames,quietFrames:0};return this.settledCallbacks.push(n),()=>{const r=this.settledCallbacks.indexOf(n);r!==-1&&this.settledCallbacks.splice(r,1)}}processSettledCallbacks(t){const e=this.settledCallbacks;this.settledCallbacks=[];for(const n of e)t?(n.quietFrames++,n.quietFrames>=n.requiredFrames?n.callback():this.settledCallbacks.push(n)):(n.quietFrames=0,this.settledCallbacks.push(n))}commitPendingDelta(){if(this.dirty){this.cancelCommitSettled=null,this.dirty=!1;for(const t of Object.keys(this.pendingForward))t in this.pendingInverse&&JSON.stringify(this.pendingForward[t])===JSON.stringify(this.pendingInverse[t])&&(delete this.pendingForward[t],delete this.pendingInverse[t]);if(Object.keys(this.pendingForward).length!==0)for(this.undoStack.push({forward:this.pendingForward,inverse:this.pendingInverse}),this.pendingForward={},this.pendingInverse={};this.undoStack.length>this.maxHistoryStackSize;){this.undoStack.shift();for(const[t,e]of this.checkpoints)e<=0?this.checkpoints.delete(t):this.checkpoints.set(t,e-1)}}}applyAndComputeInverse(t){const e={};for(const[n,r]of Object.entries(t)){const o=this.state[n];if(r._exists===!1)o!==void 0&&o._exists!==!1&&(e[n]={_exists:!0,...o}),this.state[n]={_exists:!1};else if(r._exists){o===void 0||o._exists===!1?e[n]={_exists:!1}:e[n]={_exists:!0,...o};const{_exists:s,...i}=r;this.state[n]=i}else{const s={};for(const a of Object.keys(r))o!==void 0&&o._exists!==!1&&a in o&&(s[a]=o[a]);Object.keys(s).length>0&&(e[n]=s);const i=(o==null?void 0:o._exists)===!1?{}:o;this.state[n]={...i,...r}}}return e}applyToState(t){for(const[e,n]of Object.entries(t))if(n._exists===!1)this.state[e]={_exists:!1};else if(n._exists){const{_exists:r,...o}=n;this.state[e]=o}else{const r=this.state[e],o=(r==null?void 0:r._exists)===!1?{}:r;this.state[e]={...o,...n}}}getExcludedFields(t){const e=t.indexOf("/");if(e===-1)return;const n=t.slice(e+1);return this.excludedFields.get(n)}filterExcludedFields(t,e=!1){const n={};for(const[r,o]of Object.entries(t)){const s=this.getExcludedFields(r);if(!s||s.size===0){n[r]=o;continue}if(o._exists===!1){n[r]=o;continue}if(e&&o._exists){n[r]=o;continue}const i={};let a=!1;for(const[l,c]of Object.entries(o))l==="_exists"?i._exists=c:l==="_version"?i._version=c:s.has(l)||(i[l]=c,a=!0);(o._exists||a)&&(n[r]=i)}return n}},C2=class{constructor(t){x(this,"store",null);x(this,"documentId");x(this,"pendingDocumentPatch",null);x(this,"pendingLocalPatch",null);x(this,"componentsByName");this.documentId=t.documentId,this.componentsByName=new Map;for(const e of[...t.components,...t.singletons])this.componentsByName.set(e.name,e)}async init(){try{this.store=await og(this.documentId,"state"),await this.loadState()}catch(t){console.error("IndexedDB error:",t)}}async loadState(){if(!this.store)return;const t=await this.store.getAllEntries(),e={};for(const[s,i]of t)e[s]=i;if(Object.keys(e).length===0)return;const n=zu(e,this.componentsByName);if(n!==e)for(const[s,i]of Object.entries(n))this.store.put(s,i);const r={},o={};for(const[s,i]of Object.entries(n)){const a=s.indexOf("/"),l=a!==-1?s.slice(a+1):s,c=this.componentsByName.get(l);(c==null?void 0:c.sync)==="local"?o[s]=i:r[s]=i}Object.keys(r).length>0&&(this.pendingDocumentPatch=r),Object.keys(o).length>0&&(this.pendingLocalPatch=o)}push(t){if(!this.store)return;const e=t.filter(n=>n.origin!==Jt.Persistence&&n.syncBehavior!=="ephemeral");e.length!==0&&this.persistMutations(e).catch(n=>{console.error("Error persisting mutations:",n)})}async persistMutations(t){if(this.store)for(const{patch:e}of t)for(const[n,r]of Object.entries(e))if(r._exists===!1)this.store.delete(n);else if(r._exists)this.store.put(n,r);else{const o=await this.store.get(n);o&&this.store.put(n,{...o,...r})}}pull(){const t=[];return this.pendingDocumentPatch&&(t.push({patch:this.pendingDocumentPatch,origin:Jt.Persistence,syncBehavior:"document"}),this.pendingDocumentPatch=null),this.pendingLocalPatch&&(t.push({patch:this.pendingLocalPatch,origin:Jt.Persistence,syncBehavior:"local"}),this.pendingLocalPatch=null),t}close(){this.store&&(this.store.close(),this.store=null)}async clearAll(){this.pendingDocumentPatch=null,this.pendingLocalPatch=null,this.store&&await this.store.clear()}},lg=class{constructor(t){x(this,"ecsAdapter");x(this,"historyAdapter",null);x(this,"websocketAdapter",null);x(this,"persistenceAdapter",null);x(this,"adapters",[]);x(this,"options");this.options=t}async initialize({components:t,singletons:e}){if(this.ecsAdapter=new S2({components:t,singletons:e}),this.adapters.push(this.ecsAdapter),this.options.persistence&&(this.persistenceAdapter=new C2({documentId:this.options.persistence.documentId,components:t,singletons:e}),this.adapters.push(this.persistenceAdapter)),this.options.history){const n=this.options.history===!0?{}:this.options.history;this.historyAdapter=new E2({components:t,singletons:e,commitCheckpointAfterFrames:n.commitCheckpointAfterFrames,maxHistoryStackSize:n.maxHistoryStackSize}),this.adapters.push(this.historyAdapter)}this.options.websocket&&(this.websocketAdapter=new k2({documentId:this.options.websocket.documentId,url:this.options.websocket.url,clientId:this.options.websocket.clientId,startOffline:this.options.websocket.startOffline,token:this.options.websocket.token,usePersistence:!!this.options.persistence,onVersionMismatch:this.options.websocket.onVersionMismatch,onConnectivityChange:this.options.websocket.onConnectivityChange,components:t,singletons:e}),this.adapters.push(this.websocketAdapter)),await Promise.all(this.adapters.map(n=>n.init()))}sync(t){this.ecsAdapter.ctx=t;const e=[];for(const n of this.adapters)e.push(...n.pull());for(const n of this.adapters)n.push(e)}undo(){var t;return((t=this.historyAdapter)==null?void 0:t.undo())??!1}redo(){var t;return((t=this.historyAdapter)==null?void 0:t.redo())??!1}canUndo(){var t;return((t=this.historyAdapter)==null?void 0:t.canUndo())??!1}canRedo(){var t;return((t=this.historyAdapter)==null?void 0:t.canRedo())??!1}createCheckpoint(){var t;return((t=this.historyAdapter)==null?void 0:t.createCheckpoint())??null}revertToCheckpoint(t){var e;return((e=this.historyAdapter)==null?void 0:e.revertToCheckpoint(t))??!1}squashToCheckpoint(t){var e;return((e=this.historyAdapter)==null?void 0:e.squashToCheckpoint(t))??!1}onSettled(t,e){var n;(n=this.historyAdapter)==null||n.onSettled(t,e)}async connect(){this.websocketAdapter&&await this.websocketAdapter.reconnect()}disconnect(){this.websocketAdapter&&this.websocketAdapter.disconnect()}close(){for(const t of this.adapters)t.close()}},x2=Object.defineProperty,Ns=(t,e)=>{for(var n in e)x2(t,n,{get:e[n],enumerable:!0})},Ei=le("drag-block"),T2=le("remove-block"),Vu=le("remove-selected"),cg=le("bring-forward-selected"),ug=le("send-backward-selected"),dg=le("clone-entities"),Fu=le("unclone-entities"),Ja=le("set-cursor"),fg=le("cut"),hg=le("copy"),pg=le("paste"),Wu=le("select-block"),M2=le("deselect-block"),mg=le("toggle-select"),Ps=le("deselect-all"),gg=le("select-all"),yg=le("add-selection-box"),wg=le("update-selection-box"),kg=le("remove-selection-box"),vg=le("add-held"),bg=le("remove-held"),Sg=le("add-transform-box"),Uu=le("update-transform-box"),Eg=le("hide-transform-box"),Cg=le("show-transform-box"),Hu=le("remove-transform-box"),xg=le("start-transform-box-edit"),A2=le("end-transform-box-edit"),Tg={};Ns(Tg,{DragStart:()=>lt,EditAfterPlacing:()=>Ci,Selected:()=>pt,SelectionBox:()=>Qa,TransformBox:()=>Ft,TransformHandle:()=>$e});var lt=Ze({name:"dragStart"},{position:C.tuple(C.float64(),2).default([0,0]),size:C.tuple(C.float64(),2).default([0,0]),rotateZ:C.float64().default(0),flip:C.tuple(C.boolean(),2).default([!1,!1]),fontSize:C.float64().default(16)}),Ci=Ze({name:"editAfterPlacing"},{}),pt=Ze({name:"selected"},{}),Qa=Ze({name:"selectionBox"},{}),Ft=Ze({name:"transformBox"},{}),_2=`
42
42
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33.94 33.94">
43
43
  <g fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
44
44
  <path d="M25.46,14.14l2.83,2.83-2.83,2.83"/>
@@ -50,7 +50,7 @@ ${d.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get eve
50
50
  <path d="M19.8,8.49l-2.83-2.83-2.83,2.83"/>
51
51
  <path d="M16.97,5.66v15.14"/>
52
52
  </g>
53
- </svg>`;function Ka(t){return`
53
+ </svg>`;function el(t){return`
54
54
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
55
55
  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
56
56
  <g transform="rotate(${t*180/Math.PI} 12 12)">
@@ -58,7 +58,7 @@ ${d.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get eve
58
58
  <path d="M8 17l4 4l4 -4"/>
59
59
  <path d="M12 3l0 18"/>
60
60
  </g>
61
- </svg>`}function Ya(t){return`
61
+ </svg>`}function tl(t){return`
62
62
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -10 34 34"
63
63
  fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
64
64
  <g transform="rotate(${t*180/Math.PI} 8 8)">
@@ -66,19 +66,19 @@ ${d.message}`)}if(u){o.push(...a.actions),s=a;break}}return s?[s]:void 0}get eve
66
66
  <path d="M14.61,1l4,4-4,4"/>
67
67
  <path d="M18.61,5h-6.02c-4.19,0-7.59,3.4-7.59,7.59v6.17"/>
68
68
  </g>
69
- </svg>`}var S2={drag:{makeSvg:()=>b2,hotspot:[12,12],rotationOffset:0},ns:{makeSvg:Ka,hotspot:[12,12],rotationOffset:0},ew:{makeSvg:Ka,hotspot:[12,12],rotationOffset:Math.PI/2},nwse:{makeSvg:Ka,hotspot:[12,12],rotationOffset:-Math.PI/4},nesw:{makeSvg:Ka,hotspot:[12,12],rotationOffset:Math.PI/4},rotateNW:{makeSvg:Ya,hotspot:[16,16],rotationOffset:0},rotateNE:{makeSvg:Ya,hotspot:[16,16],rotationOffset:Math.PI/2},rotateSW:{makeSvg:Ya,hotspot:[16,16],rotationOffset:-Math.PI/2},rotateSE:{makeSvg:Ya,hotspot:[16,16],rotationOffset:-Math.PI}},me={Idle:"idle",Pointing:"pointing",Dragging:"dragging",SelectionBoxPointing:"selectionBoxPointing",SelectionBoxDragging:"selectionBoxDragging"},Bn={None:"none",Idle:"idle",Editing:"editing"},Pn={Scale:"scale",Stretch:"stretch",Rotate:"rotate"},vn={Idle:"idle",Waiting:"waiting",Scrolling:"scrolling"},gg=qt({enabled:Lt().default(!0),edgeSizePx:Xe().default(10),edgeScrollSpeedPxPerFrame:Xe().default(15),edgeScrollDelayMs:Xe().default(250)}),E2=qt({edgeScrolling:gg.default(gg.parse({}))}),ze=He({name:"transformHandle"},{kind:E.string().max(16).default(Pn.Scale),vectorX:E.int8().default(0),vectorY:E.int8().default(0),transformBox:E.ref(),cursorKind:E.string().max(16).default("drag")}),yg="selection";function C2(t,e,n){var o;const r={...n};for(const[s,i]of Object.entries(e))if(((o=i==null?void 0:i.def)==null?void 0:o.type)==="ref"){const a=n[s];r[s]=x2(t,a)}return r}function x2(t,e){return e==null||!O(t,e,de)?null:de.read(t,e).id}function T2(t){var n;const e=[];for(const[r,o]of Object.entries(t))((n=o==null?void 0:o.def)==null?void 0:n.type)==="ref"&&e.push(r);return e}function M2(t,e,n,r,o){var i;const s=n.write(t,e);for(const[a,l]of Object.entries(n.schema))if(((i=l==null?void 0:l.def)==null?void 0:i.type)==="ref"){const c=r[a];c!=null&&(s[a]=o.get(c)??null)}}var _2=ne(t=>t.with(ht));ne(t=>t.with(_));function Ms(t,e){if(O(t,e,ht)||Tu(t,e))return;const{sessionId:n}=Le(t);G(t,e,ht,{}),O(t,e,xt)||G(t,e,xt,{sessionId:n})}function yi(t,e){O(t,e,ht)&&(nn(t,e,ht),nn(t,e,xt))}function wg(t){for(const e of _2.current(t))yi(t,e)}function A2(t){let e=0;for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e)}var I2=class{constructor(t){this.seed=typeof t=="string"?A2(t):t}next(){return this.seed=(this.seed*9301+49297)%233280,this.seed/233280}nextInt(t,e){return Math.floor(this.next()*(e-t+1))+t}nextHex(){return this.nextInt(0,15).toString(16)}};function Du(t,e){const n=t+e,r=new I2(n);let o="";for(let s=0;s<32;s++)(s===8||s===12||s===16||s===20)&&(o+="-"),s===12?o+="4":s===16?o+=["8","9","a","b"][r.nextInt(0,3)]:o+=r.nextHex();return o}var kg={};Ts(kg,{Clipboard:()=>wi,ScrollEdgesStateSingleton:()=>Ou,SelectionStateSingleton:()=>Nn,TransformBoxStateSingleton:()=>Ru});var B2={count:E.uint32().default(0),center:E.tuple(E.float64(),2).default([0,0])},qa=new WeakMap,P2=class extends bt{constructor(){super({name:"clipboard"},B2)}setEntities(t,e){const{editor:n}=Le(t);qa.set(n,e)}getEntities(t){const{editor:e}=Le(t);return qa.get(e)??[]}clearEntities(t){const{editor:e}=Le(t);qa.delete(e)}hasContent(t){const{editor:e}=Le(t),n=qa.get(e);return n!==void 0&&n.length>0}},wi=new P2,Ou=Gr("scrollEdgesState",{state:E.enum(vn).default(vn.Idle),edgeEnterStartTime:E.float64().default(0)}),Nn=Gr("selectionState",{state:E.enum(me).default(me.Idle),dragStart:E.tuple(E.float64(),2).default([0,0]),pointingStartClient:E.tuple(E.float64(),2).default([0,0]),pointingStartWorld:E.tuple(E.float64(),2).default([0,0]),draggedEntityStart:E.tuple(E.float64(),2).default([0,0]),draggedEntity:E.ref(),cloneGeneratorSeed:E.string().max(36).default(""),isCloning:E.boolean()}),Ru=Gr("transformBoxState",{state:E.string().max(32).default(Bn.None),transformBoxId:E.ref()}),vg={};Ts(vg,{hoverCursorSystem:()=>D2,scrollEdgesSystem:()=>R2,transformBoxSystem:()=>L2});var zu=ne(t=>t.with(Yr,ze).tracking(Yr)),N2=ne(t=>t.with(_,Vt).tracking(_)),D2=pe({phase:"capture"},t=>{const e=zu.added(t),n=zu.removed(t),r=zu.current(t),o=N2.changed(t);if(r.length===0&&n.length>0){kn.clearContextCursor(t);return}if((e.length>0||o.length>0)&&r.length>0){const i=r[0],a=ze.read(t,i);if(a.transformBox===null)return;const l=_.read(t,a.transformBox),c=kn.read(t);(a.cursorKind!==c.contextCursorKind||l.rotateZ!==c.contextRotation)&&kn.setContextCursor(t,a.cursorKind,l.rotateZ)}});function Ja(t){return si(t,yg).edgeScrolling}var O2=yr({guards:{isPointerNearEdge:({event:t})=>{const{edgeSizePx:e}=Ja(t.ctx),n=Nt.read(t.ctx),r=n.width,o=n.height,s=t.screenPosition[0],i=t.screenPosition[1];return s<e||s>r-e||i<e||i>o-e},isEdgeScrollDelayPassed:({context:t,event:e})=>{const{edgeScrollDelayMs:n}=Ja(e.ctx);return performance.now()-t.edgeEnterStartTime>=n}},actions:{setEdgeEnterStartTime:Oe({edgeEnterStartTime:()=>performance.now()}),moveCamera:({event:t})=>{const{edgeSizePx:e,edgeScrollSpeedPxPerFrame:n}=Ja(t.ctx),r=Nt.read(t.ctx),o=he.read(t.ctx),s=r.width,i=r.height,a=t.screenPosition[0],l=t.screenPosition[1];let c=0,u=0;const d=n/o.zoom;if(a<e?c=-d:a>s-e&&(c=d),l<e?u=-d:l>i-e&&(u=d),c===0&&u===0)return;const h=he.write(t.ctx);h.left+=c,h.top+=u},resetContext:Oe({edgeEnterStartTime:0})}}).createMachine({id:"scrollEdges",initial:vn.Idle,context:{edgeEnterStartTime:0},states:{[vn.Idle]:{entry:"resetContext",on:{pointerMove:{guard:"isPointerNearEdge",target:vn.Waiting}}},[vn.Waiting]:{entry:"setEdgeEnterStartTime",on:{pointerMove:{guard:Co("isPointerNearEdge"),target:vn.Idle},frame:{guard:"isEdgeScrollDelayPassed",target:vn.Scrolling}}},[vn.Scrolling]:{on:{frame:[{guard:Co("isPointerNearEdge"),target:vn.Idle},{actions:"moveCamera"}]}}}}),R2=pe({phase:"capture"},t=>{if(!Ja(t).enabled)return;const e=Nn.read(t).state;if(e!==me.Dragging&&e!==me.SelectionBoxDragging)return;const n=Ou.read(t).state,r=n===vn.Waiting||n===vn.Scrolling,o=Qe.getButtons(t,"select"),s=br(t,o,{includeFrameEvent:r});s.length!==0&&Ou.run(t,O2,s)}),Xa=ne(t=>t.with(_).tracking(ht)),z2=yr({guards:{isSelectionEditable:({event:t})=>$2(t.ctx),isOverTransformBox:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:O(t.ctx,t.intersects[0],Vt),isOverTransformHandle:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:O(t.ctx,t.intersects[0],ze),selectionIsTransformable:({event:t})=>{if(t.type!=="selectionChanged")return!1;if(t.selectedEntityIds.length>1)return!0;if(t.selectedEntityIds.length===0)return!1;const e=t.selectedEntityIds[0],n=_.read(t.ctx,e);return Ft(t.ctx,n.tag).resizeMode!=="groupOnly"},hasEditAfterPlacing:({event:t})=>t.type!=="selectionChanged"||t.selectedEntityIds.length!==1?!1:O(t.ctx,t.selectedEntityIds[0],gi)},actions:{addTransformBox:Oe(({context:t,event:e},n)=>{t.transformBoxId!==null&&Nu.spawn(e.ctx,{transformBoxId:t.transformBoxId});const r=vt(e.ctx);return dg.spawn(e.ctx,{transformBoxId:r,skipHandles:n==null?void 0:n.skipHandles}),{transformBoxId:r}}),updateTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Pu.spawn(e.ctx,{transformBoxId:t.transformBoxId})},hideTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&fg.spawn(e.ctx,{transformBoxId:t.transformBoxId})},showTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&hg.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Nu.spawn(e.ctx,{transformBoxId:t.transformBoxId})},clearTransformBoxId:Oe({transformBoxId:()=>null}),startTransformBoxEdit:({context:t,event:e})=>{t.transformBoxId!==null&&pg.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeEditAfterPlacing:({event:t})=>{if(t.type==="selectionChanged")for(const e of t.selectedEntityIds)O(t.ctx,e,gi)&&nn(t.ctx,e,gi)}}}).createMachine({id:"transformBox",initial:Bn.None,context:{transformBoxId:null},states:{[Bn.None]:{entry:["removeTransformBox","clearTransformBoxId"],on:{selectionChanged:[{guard:ti(["hasEditAfterPlacing","selectionIsTransformable","isSelectionEditable"]),actions:[{type:"addTransformBox",params:{skipHandles:!0}},"removeEditAfterPlacing"],target:Bn.Editing},{guard:"selectionIsTransformable",target:Bn.Idle}]}},[Bn.Idle]:{entry:["addTransformBox"],on:{selectionChanged:[{guard:Co("selectionIsTransformable"),target:Bn.None},{guard:"selectionIsTransformable",actions:"showTransformBox"},{actions:"updateTransformBox"}],pointerDown:{actions:"hideTransformBox"},pointerUp:{actions:"showTransformBox"},click:{guard:ti(["isOverTransformBox","isSelectionEditable"]),target:Bn.Editing}}},[Bn.Editing]:{entry:["hideTransformBox","startTransformBoxEdit"],on:{pointerDown:{guard:ti([Co("isOverTransformBox"),Co("isOverTransformHandle")]),target:Bn.None},selectionChanged:{target:Bn.None,actions:Ra(({event:t})=>t)}}}}});function $2(t){const e=Xa.current(t);if(e.length!==1)return!1;const n=e[0],r=_.read(t,n);return Im(t,r.tag)}var L2=pe({phase:"capture"},t=>{const e=[],n=Xa.added(t),r=Xa.removed(t);if(n.length>0||r.length>0){const i=[...Xa.current(t)],a={type:"selectionChanged",ctx:t,selectedEntityIds:i};e.push(a)}const o=Qe.getButtons(t,"select"),s=br(t,o);e.push(...s),e.length!==0&&Ru.run(t,z2,e)}),bg={};Ts(bg,{transformBoxSystem:()=>H2});var Ga=ne(t=>t.with(_,ht)),F2=ne(t=>t.with(_,wr)),V2="a",W2="b",Sg="c",U2="d",H2=pe({phase:"update",priority:-100},t=>{ie(t,Nu,(e,{transformBoxId:n})=>{j2(e,n)}),ie(t,dg,(e,{transformBoxId:n,skipHandles:r})=>{Z2(e,n,r)}),ie(t,Pu,(e,{transformBoxId:n})=>{$u(e,n)}),ie(t,fg,(e,{transformBoxId:n})=>{Y2(e,n)}),ie(t,hg,(e,{transformBoxId:n})=>{q2(e,n)}),ie(t,pg,(e,{transformBoxId:n})=>{J2(e,n)}),ie(t,v2,Lu)});function j2(t,e){if(!O(t,e,Vt)){Lu(t);return}const n=Jn(t,e,ze,"transformBox");for(const r of n)Ye(t,r);Ye(t,e),Lu(t)}function Z2(t,e,n){G(t,e,_,{tag:"transform-box",position:[0,0],size:[0,0],rotateZ:0,rank:V2}),G(t,e,Vt,{}),G(t,e,it,{position:[0,0],size:[0,0],rotateZ:0,fontSize:16}),n||$u(t,e)}function $u(t,e){if(!Rb(t,e))return;const n=Ga.current(t);if(n.length===0)return;let r=0;r=_.read(t,n[0]).rotateZ;for(let c=1;c<n.length;c++){const u=_.read(t,n[c]);if(Math.abs(r-u.rotateZ)>.01){r=0;break}}if(n.length===0)return;const s=[];for(const c of n){const u=_.getCorners(t,c);s.push(...u)}if(s.length===0)return;const i=_.write(t,e);if(i.rotateZ=r,ot.boundPoints(i.position,i.size,r,s),!(Nn.read(t).state===me.Dragging)){if(O(t,e,it)){const c=it.write(t,e);c.position=i.position,c.size=i.size,c.rotateZ=r}for(const c of n){const u=_.read(t,c),d=O(t,c,ft)?ft.read(t,c).fontSizePx:16;if(!O(t,c,it))G(t,c,it,{position:u.position,size:u.size,rotateZ:u.rotateZ,flip:u.flip,fontSize:d});else{const h=it.write(t,c);h.position=u.position,h.size=u.size,h.rotateZ=u.rotateZ,h.flip=u.flip,h.fontSize=d}}}K2(t,e)}function K2(t,e){const n=_.read(t,e),{position:r,size:o,rotateZ:s}=n,i=r[0],a=r[1],l=o[0],c=o[1],u=[i+l/2,a+c/2],d=12,h=2*d,p=1.25*d,m=[],g=["rotateNW","rotateNE","rotateSW","rotateSE"],y=Ga.current(t);let w="scale";if(y.length===1){const M=_.read(t,y[0]);w=Ft(t,M.tag).resizeMode}else y.length>1&&y.every(L=>{const q=_.read(t,L);return Ft(t,q.tag).resizeMode==="free"})&&(w="free");const k=y.every(M=>{const L=_.read(t,M);return Ft(t,L.tag).canRotate}),b=y.every(M=>{const L=_.read(t,M);return Ft(t,L.tag).canScale});let S;switch(w){case"scale":case"text":S=Pn.Scale;break;case"free":S=Pn.Stretch;break;default:S=Pn.Scale;break}const v=he.read(t),x=l*v.zoom,T=c*v.zoom,A=Math.min(x,T),P=15;for(let M=0;M<2;M++)for(let L=0;L<2;L++)M+L!==1&&A<P/2||M+L===1&&T<P||(b&&m.push({tag:"transform-handle",kind:S,vectorX:M*2-1,vectorY:L*2-1,left:i+l*M-d/2,top:a+c*L-d/2,width:d,height:d,rotateZ:s,rank:U2,cursorKind:M+L===1?"nesw":"nwse",scaleMultiplier:[1,1],anchor:[.5,.5]}),k&&m.push({tag:"transform-rotate",kind:Pn.Rotate,vectorX:M*2-1,vectorY:L*2-1,left:i+M*l-(1-M)*h,top:a+L*c-(1-L)*h,width:h,height:h,rotateZ:s,rank:W2,cursorKind:g[M+L*2],scaleMultiplier:[.5,.5],anchor:[1-M,1-L]}));if(b)for(let M=0;M<2;M++)m.push({tag:"transform-edge",kind:S,vectorX:0,vectorY:M*2-1,left:i,top:a+c*M-p/2,width:l,height:p,rotateZ:s,rank:Sg,cursorKind:"ns",scaleMultiplier:[0,1],anchor:[.5,.5]});if(b||w==="text")for(let M=0;M<2;M++)m.push({tag:"transform-edge",kind:w==="text"?Pn.Stretch:S,vectorX:M*2-1,vectorY:0,left:i+l*M-p/2,top:a,width:p,height:c,rotateZ:s,rank:Sg,cursorKind:"ew",scaleMultiplier:[1,0],anchor:[.5,.5]});const $=Jn(t,e,ze,"transformBox"),V=new Map;for(const M of $){const L=ze.read(t,M),q=`${L.kind}-${L.vectorX}-${L.vectorY}`;V.set(q,M)}const U=new Set;for(const M of m){const L=`${M.kind}-${M.vectorX}-${M.vectorY}`;let q=V.get(L);const se=[M.left+M.width/2,M.top+M.height/2],Z=z.clone(se);z.rotateAround(Z,u,s);const H=Z[0]-M.width/2,J=Z[1]-M.height/2;q||(q=vt(t),G(t,q,_),G(t,q,ze),G(t,q,it),G(t,q,Jr));const ce=_.write(t,q);ce.tag=M.tag,ce.position=[H,J],ce.size=[M.width,M.height],ce.rotateZ=M.rotateZ,ce.rank=M.rank;const Ke=ze.write(t,q);Ke.transformBox=e,Ke.kind=M.kind,Ke.vectorX=M.vectorX,Ke.vectorY=M.vectorY,Ke.cursorKind=M.cursorKind;const Be=it.write(t,q);Be.position=[H,J],Be.size=[M.width,M.height],Be.rotateZ=M.rotateZ;const tt=Jr.write(t,q);tt.startPosition=[H,J],tt.startSize=[M.width,M.height],z.copy(tt.scaleMultiplier,M.scaleMultiplier),z.copy(tt.anchor,M.anchor),U.add(q)}for(const M of $)U.has(M)||Ye(t,M)}function Y2(t,e){if(!O(t,e,Vt))return;if(!O(t,e,Ge))G(t,e,Ge,{value:0});else{const r=Ge.write(t,e);r.value=0}const n=Jn(t,e,ze,"transformBox");for(const r of n)if(!O(t,r,Ge))G(t,r,Ge,{value:0});else{const o=Ge.write(t,r);o.value=0}}function q2(t,e){if(!O(t,e,Vt))return;const n=Ga.current(t);if(n.length===0)return;if(n.length===1){const o=_.read(t,n[0]);if(Ft(t,o.tag).resizeMode==="groupOnly")return}O(t,e,Ge)&&nn(t,e,Ge);const r=Jn(t,e,ze,"transformBox");for(const o of r)O(t,o,Ge)&&nn(t,o,Ge);$u(t,e)}function J2(t,e){if(O(t,e,Vt)){const n=Jn(t,e,ze,"transformBox");for(const r of n)Ye(t,r)}for(const n of Ga.current(t))O(t,n,wr)||G(t,n,wr,{})}function Lu(t){for(const e of F2.current(t))O(t,e,wr)&&nn(t,e,wr)}var Eg={};Ts(Eg,{selectSystem:()=>eI});var X2=4,Cg=ne(t=>t.with(_,ht,de)),G2=ne(t=>t.with(_,wr)),Q2=yr({guards:{isThresholdReached:({context:t,event:e})=>z.distance(t.pointingStartClient,e.screenPosition)>=X2,isOverBlock:({event:t})=>t.intersects.length>0,isOverSyncedBlock:({event:t})=>{const e=t.ctx;for(const n of t.intersects)if(O(e,n,de))return!0;return!1},isNotHeldByRemote:({event:t})=>{const e=t.ctx,n=t.intersects[0];return n?!Tu(e,n):!0},hasEditedBlocks:({event:t})=>G2.current(t.ctx).length>0},actions:{setPointingStart:Oe({pointingStartClient:({event:t})=>t.screenPosition,pointingStartWorld:({event:t})=>t.worldPosition}),setDragStart:Oe({dragStart:({event:t})=>t.worldPosition}),addHeldToDragged:({context:t,event:e})=>{t.draggedEntity!==null&&cg.spawn(e.ctx,{entityId:t.draggedEntity})},removeHeldFromDragged:({context:t,event:e})=>{t.draggedEntity!==null&&ug.spawn(e.ctx,{entityId:t.draggedEntity})},setDragCursor:({event:t,context:e})=>{if(e.draggedEntity)if(O(t.ctx,e.draggedEntity,ze)){const n=ze.read(t.ctx,e.draggedEntity),r=n.transformBox!==null?_.read(t.ctx,n.transformBox):void 0;ja.spawn(t.ctx,{contextCursorKind:n.cursorKind,contextRotation:(r==null?void 0:r.rotateZ)??0})}else ja.spawn(t.ctx,{contextCursorKind:"drag",contextRotation:0})},unsetDragCursor:({event:t})=>{ja.spawn(t.ctx,{contextCursorKind:""})},setDraggedEntity:Oe({draggedEntity:({event:t})=>t.intersects[0]??null,draggedEntityStart:({event:t})=>{if(!t.intersects.length)return[0,0];const e=t.intersects[0],n=_.read(t.ctx,e);return[n.position[0],n.position[1]]}}),resetDragged:({context:t,event:e})=>{t.draggedEntity!==null&&(pi.spawn(e.ctx,{entityId:t.draggedEntity,position:t.draggedEntityStart}),t.isCloning&&Iu.spawn(e.ctx,{entityIds:[t.draggedEntity],seed:t.cloneGeneratorSeed}))},resetContext:Oe({dragStart:()=>[0,0],pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],draggedEntityStart:()=>[0,0],draggedEntity:()=>null,cloneGeneratorSeed:()=>crypto.randomUUID(),isCloning:()=>!1}),createSelectionBox:({event:t})=>{ig.spawn(t.ctx,void 0)},removeSelectionBox:({event:t})=>{lg.spawn(t.ctx,void 0)},updateDragged:Oe({isCloning:({context:t,event:e})=>{const n=e.ctx;if(t.draggedEntity===null)return!1;let r=t.draggedEntityStart[0]+e.worldPosition[0]-t.dragStart[0],o=t.draggedEntityStart[1]+e.worldPosition[1]-t.dragStart[1];const s=O(n,t.draggedEntity,de)||O(n,t.draggedEntity,Vt);if(e.shiftDown&&s){const a=Math.abs(e.worldPosition[0]-t.dragStart[0]),l=Math.abs(e.worldPosition[1]-t.dragStart[1]);a>l?o=t.draggedEntityStart[1]:r=t.draggedEntityStart[0]}s&&(r=Dt.snapX(n,r),o=Dt.snapY(n,o)),pi.spawn(n,{entityId:t.draggedEntity,position:[r,o]});let i=t.isCloning;if(e.altDown&&s&&!t.isCloning){const a=t.draggedEntityStart[0]-r,l=t.draggedEntityStart[1]-o;i=!0;const u=O(n,t.draggedEntity,Vt)?Array.from(Cg.current(n)):[t.draggedEntity];eg.spawn(n,{entityIds:u,offset:[a,l],seed:t.cloneGeneratorSeed})}else if(!e.altDown&&t.isCloning){const l=O(n,t.draggedEntity,Vt)?Array.from(Cg.current(n)):[t.draggedEntity];Iu.spawn(n,{entityIds:l,seed:t.cloneGeneratorSeed}),i=!1}return i}}),resizeSelectionBox:({context:t,event:e})=>{const n=Math.min(t.pointingStartWorld[0],e.worldPosition[0]),r=Math.min(t.pointingStartWorld[1],e.worldPosition[1]),o=Math.max(t.pointingStartWorld[0],e.worldPosition[0]),s=Math.max(t.pointingStartWorld[1],e.worldPosition[1]);ag.spawn(e.ctx,{bounds:[n,r,o,s],deselectOthers:!e.shiftDown})},selectIntersect:({event:t})=>{const e=t.ctx;let n;for(const r of t.intersects)if(O(e,r,de)){n=r;break}n!==void 0&&(t.shiftDown?og.spawn(e,{entityId:n}):Bu.spawn(e,{entityId:n,deselectOthers:!0}))},selectDragged:({context:t,event:e})=>{t.draggedEntity!==null&&O(e.ctx,t.draggedEntity,de)&&Bu.spawn(e.ctx,{entityId:t.draggedEntity,deselectOthers:!0})},deselectAllIfShiftNotDown:({event:t})=>{t.shiftDown||mi.spawn(t.ctx,void 0)},deselectAllIfDraggedNotSelected:({context:t,event:e})=>{t.draggedEntity!==null&&(O(e.ctx,t.draggedEntity,ht)||O(e.ctx,t.draggedEntity,Vt)||O(e.ctx,t.draggedEntity,ze)||mi.spawn(e.ctx,void 0))}}}).createMachine({id:"selection",initial:me.Idle,context:{dragStart:[0,0],pointingStartClient:[0,0],pointingStartWorld:[0,0],draggedEntityStart:[0,0],draggedEntity:null,cloneGeneratorSeed:crypto.randomUUID(),isCloning:!1},states:{[me.Idle]:{entry:["resetContext"],on:{pointerDown:[{guard:ti(["isOverBlock","isNotHeldByRemote"]),target:me.Pointing},{actions:"deselectAllIfShiftNotDown",target:me.SelectionBoxPointing}]}},[me.Pointing]:{entry:["setPointingStart","setDraggedEntity"],on:{pointerMove:{guard:ti(["isThresholdReached",Co("hasEditedBlocks")]),target:me.Dragging},pointerUp:[{guard:"isOverSyncedBlock",actions:"selectIntersect",target:me.Idle},{actions:"deselectAllIfShiftNotDown",target:me.Idle}],cancel:{target:me.Idle}}},[me.Dragging]:{entry:["setDragStart","addHeldToDragged","setDragCursor","deselectAllIfDraggedNotSelected"],exit:["unsetDragCursor"],on:{pointerMove:{actions:"updateDragged"},pointerUp:{actions:"selectDragged",target:me.Idle},cancel:{actions:["resetDragged","removeHeldFromDragged"],target:me.Idle}}},[me.SelectionBoxPointing]:{entry:["setPointingStart"],on:{pointerMove:{guard:"isThresholdReached",target:me.SelectionBoxDragging},pointerUp:{target:me.Idle},cancel:{target:me.Idle}}},[me.SelectionBoxDragging]:{entry:["setDragStart","createSelectionBox"],exit:"removeSelectionBox",on:{pointerMove:{actions:"resizeSelectionBox"},pointerUp:{target:me.Idle},cancel:{target:me.Idle}}}}}),eI=pe({phase:"capture",priority:100},t=>{let e=Qe.getButtons(t,"select");Nn.read(t).state===me.Dragging&&e.length===0&&(e=["left"]);const r=br(t,e);r.length!==0&&Nn.run(t,Q2,r)}),xg={};Ts(xg,{blockSystem:()=>tI,dragHandlerSystem:()=>aI,selectSystem:()=>pI});var _s=ne(t=>t.with(_,ht)),Tg=ne(t=>t.with(_,de)),tI=pe({phase:"update"},t=>{ie(t,pi,(e,{entityId:n,position:r})=>{if(!O(e,n,_))return;const o=_.write(e,n);o.position=r}),ie(t,Bu,(e,{entityId:n,deselectOthers:r})=>{r&&Fu(e),Ms(e,n)}),ie(t,k2,(e,{entityId:n})=>{yi(e,n)}),ie(t,og,(e,{entityId:n})=>{O(e,n,ht)?yi(e,n):Ms(e,n)}),ie(t,mi,Fu),ie(t,cg,(e,{entityId:n})=>{if(!O(e,n,de)||O(e,n,xt))return;const{sessionId:r}=Le(e);G(e,n,xt,{sessionId:r})}),ie(t,ug,(e,{entityId:n})=>{O(e,n,ht)||O(e,n,xt)&&nn(e,n,xt)}),ie(t,sg,e=>{for(const n of Tg.current(e))Ms(e,n)}),ie(t,w2,(e,{entityId:n})=>{Ye(e,n)}),ie(t,Xm,e=>{for(const n of _s.current(e))Ye(e,n)}),ie(t,Gm,nI),ie(t,Qm,rI),ie(t,ja,(e,n)=>{n.cursorKind!==void 0&&kn.setCursor(e,n.cursorKind,n.rotation??0),n.contextCursorKind!==void 0&&kn.setContextCursor(e,n.contextCursorKind,n.contextRotation??0),n.contextCursorKind===""&&kn.clearContextCursor(e)}),ie(t,ng,e=>{Mg(e)}),ie(t,tg,e=>{Mg(e);for(const n of _s.current(e))Ye(e,n)}),ie(t,rg,(e,n)=>{oI(e,n==null?void 0:n.position)}),ie(t,eg,(e,{entityIds:n,offset:r,seed:o})=>{sI(e,n,r,o)}),ie(t,Iu,(e,{entityIds:n,seed:r})=>{iI(e,n,r)})});function Fu(t){for(const e of _s.current(t))yi(t,e)}function nI(t){const e=[..._s.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=_.read(t,n),s=_.read(t,r);return!o.rank&&!s.rank?0:o.rank?s.rank?o.rank<s.rank?-1:o.rank>s.rank?1:0:1:-1});for(const n of e){const r=_.write(t,n);r.rank=In.genNext(t)}}}function rI(t){const e=[..._s.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=_.read(t,n),s=_.read(t,r);return!o.rank&&!s.rank?0:o.rank?!s.rank||s.rank<o.rank?-1:s.rank>o.rank?1:0:1});for(const n of e){const r=_.write(t,n);r.rank=In.genPrev(t)}}}function Mg(t){const e=[..._s.current(t)];if(e.length===0)return;const{componentsById:n}=Le(t),r=new Map([...n].filter(([,c])=>c.sync==="document")),o=[],s=Q.zero();let i=!1;const a=de._getComponentId(t);for(const c of e){const u=new Map;O(t,c,de)&&u.set(a,de.snapshot(t,c));for(const d of t.entityBuffer.getComponentIds(c)){if(d===a)continue;const h=r.get(d);if(h){const p=h.snapshot(t,c),m=C2(t,h.schema,p);u.set(d,m)}}if(o.push(u),O(t,c,Ae)){const{value:d}=Ae.read(t,c);i?Q.union(s,d):(Q.copy(s,d),i=!0)}}wi.setEntities(t,o);const l=wi.write(t);l.count=o.length,l.center=Q.center(s)}function oI(t,e){const n=wi.getEntities(t);if(n.length===0)return;const{componentsById:r}=Le(t),o=new Map([...r].filter(([,h])=>h.sync==="document")),s=wi.read(t),i=de._getComponentId(t),a=_._getComponentId(t);let l;if(e)l=z.clone(e),z.sub(l,s.center);else{const h=he.getWorldCenter(t);l=z.clone(h),z.sub(l,s.center),Dt.snapPosition(t,l)}const c=[...n].sort((h,p)=>{const m=h.get(a),g=p.get(a),y=(m==null?void 0:m.rank)??"",w=(g==null?void 0:g.rank)??"";return y<w?-1:y>w?1:0});Fu(t);const u=new Map,d=[];for(const h of c){const p=vt(t),m=h.get(i);m!=null&&m.id&&u.set(m.id,p),G(t,p,de,{id:crypto.randomUUID()});for(const[g,y]of h){if(g===i)continue;const w=o.get(g);if(!w)continue;const k={...y};if(g===a){const S=z.clone(k.position);z.add(S,l),k.position=S,k.rank=In.genNext(t)}const b=T2(w.schema);if(b.length>0){for(const S of b)delete k[S];d.push({entityId:p,componentDef:w,componentData:y})}G(t,p,w,k)}Ms(t,p)}for(const{entityId:h,componentDef:p,componentData:m}of d)M2(t,h,p,m,u)}function sI(t,e,n,r){const{componentsById:o}=Le(t),s=new Map([...o].filter(([,c])=>c.sync==="document")),i=de._getComponentId(t),a=_._getComponentId(t),l=new Map;for(const c of e){if(!O(t,c,de))continue;const u=de.read(t,c),d=Du(u.id,r),h=vt(t);l.set(c,h),G(t,h,de,{id:d});for(const p of t.entityBuffer.getComponentIds(c)){if(p===i)continue;const m=s.get(p);if(!m)continue;const g={...m.snapshot(t,c)};if(p===a){const y=z.clone(g.position);z.add(y,n),g.position=y,g.rank=In.genPrev(t)}G(t,h,m,g)}}_g(t,l)}function iI(t,e,n){const r=new Set;for(const i of e){if(!O(t,i,de))continue;const a=de.read(t,i);r.add(Du(a.id,n))}const o=[];for(const i of Tg.current(t)){const a=de.read(t,i);r.has(a.id)&&o.push(i)}const s=new Map;for(const i of o){const a=de.read(t,i).id;for(const l of e){if(!O(t,l,de))continue;const c=de.read(t,l).id;if(Du(c,n)===a){s.set(i,l);break}}}_g(t,s);for(const i of o)Ye(t,i)}function _g(t,e){for(const[n,r]of e){for(const o of Jn(t,n,Re,"startBlock"))Re.write(t,o).startBlock=r;for(const o of Jn(t,n,Re,"endBlock"))Re.write(t,o).endBlock=r}}var Vu=ne(t=>t.with(_,ht)),Ag=ne(t=>t.with(_,Vt,it)),aI=pe({phase:"update"},t=>{ie(t,pi,(e,{entityId:n,position:r})=>{if(O(e,n,Vt)){lI(e,n,r);return}if(O(e,n,ze)){cI(e,n,r);return}})});function lI(t,e,n){const r=it.read(t,e),o=n[0]-r.position[0],s=n[1]-r.position[1];for(const i of Vu.current(t)){if(!O(t,i,it))continue;const a=it.read(t,i),l=_.write(t,i);l.position=[a.position[0]+o,a.position[1]+s],Dt.snapPosition(t,l.position)}}function cI(t,e,n){const r=ze.read(t,e);r.kind===Pn.Rotate?uI(t,e,n):r.kind===Pn.Scale?Ig(t,e,n,!0):r.kind===Pn.Stretch&&Ig(t,e,n,!1)}function uI(t,e,n){const r=Ag.current(t);if(r.length===0){console.warn("No transform box found for rotation");return}const o=r[0],s=_.write(t,o),i=_.getCenter(t,o),a=_.read(t,e),l=[n[0]+a.size[0]/2,n[1]+a.size[1]/2],c=z.angleTo(i,l),u=it.read(t,o),d=ze.read(t,e),h=z.angle([s.size[0]*d.vectorX,s.size[1]*d.vectorY])+u.rotateZ;let p=c-h;const m=Dt.read(t),g=_n.read(t);let y=0;if(g.shiftDown?y=m.shiftSnapAngleRad:m.enabled&&(y=m.snapAngleRad),y>0){const w=u.rotateZ%y;p=Math.round(p/y)*y-w}s.rotateZ=Ct.normalizeAngle(u.rotateZ+p);for(const w of Vu.current(t)){if(!O(t,w,it))continue;const k=it.read(t,w),b=_.write(t,w);b.rotateZ=Ct.normalizeAngle(k.rotateZ+p);const S=[k.position[0]+k.size[0]/2,k.position[1]+k.size[1]/2],v=z.distance(i,S),x=z.angleTo(i,S)+p,T=z.fromPolar(v,x,i);b.position=[T[0]-b.size[0]/2,T[1]-b.size[1]/2],m.strict&&Dt.snapPosition(t,b.position)}}function Ig(t,e,n,r){const o=Ag.current(t);if(o.length===0){console.warn("No transform box found for scaling");return}const s=o[0],i=it.read(t,s),a=ze.read(t,e),l=_.read(t,e),c=[n[0]+l.size[0]/2,n[1]+l.size[1]/2];Dt.snapPosition(t,c);const u=i.rotateZ,d=[i.position[0]+i.size[0]/2,i.position[1]+i.size[1]/2],h=[-a.vectorX*i.size[0]/2,-a.vectorY*i.size[1]/2];z.rotate(h,u);const p=[d[0]+h[0],d[1]+h[1]],m=[c[0]-p[0],c[1]-p[1]],g=z.clone(m);z.rotate(g,-u);let y=a.vectorX,w=a.vectorY,k=!1,b=!1;Math.sign(g[0])!==y&&y!==0&&(y=-y,k=!0),Math.sign(g[1])!==w&&w!==0&&(w=-w,b=!0);let S=Math.max(Math.abs(g[0]),1),v=Math.max(Math.abs(g[1]),1);if(r){const U=i.size[0]/i.size[1];S/v>U?v=S/U:S=v*U}else a.vectorX===0?S=i.size[0]:a.vectorY===0&&(v=i.size[1]);const x=i.size[0]>0?S/i.size[0]:1,T=i.size[1]>0?v/i.size[1]:1,A=Dt.read(t),P=z.create(y*S,w*v);z.rotate(P,u),z.scale(P,.5);const $=z.clone(p);z.add($,P);const V=[x,T];for(const U of Vu.current(t)){if(!O(t,U,it))continue;const M=it.read(t,U),L=_.write(t,U),q=z.clone(M.position);z.add(q,[M.size[0]/2,M.size[1]/2]);const se=z.clone(q);z.sub(se,d),z.rotate(se,-u),z.multiply(se,V),k&&(se[0]=-se[0]),b&&(se[1]=-se[1]),z.rotate(se,u);const Z=z.clone($);z.add(Z,se);const H=z.clone(M.size);z.multiply(H,V);const J=Ft(t,L.tag),ce=(J==null?void 0:J.resizeMode)==="text";if(A.strict)if(ce&&r){H[1]=Math.max(A.rowHeight,Dt.snapY(t,H[1]));const Ke=M.size[0]/M.size[1];H[0]=H[1]*Ke}else Dt.snapSize(t,H);if(z.copy(L.position,Z),z.sub(L.position,[H[0]/2,H[1]/2]),A.strict&&Dt.snapPosition(t,L.position),!r&&a.vectorY===0?L.size[0]=H[0]:!r&&a.vectorX===0?L.size[1]=H[1]:z.copy(L.size,H),O(t,U,ft)){const Ke=a.kind===Pn.Stretch,Be=ft.write(t,U);if(Ke)Be.constrainWidth=!0;else{const tt=M.size[1]>0?H[1]/M.size[1]:1;Be.fontSizePx=M.fontSize*tt}}L.flip=[k!==M.flip[0],b!==M.flip[1]]}}var dI=ne(t=>t.with(_,ht)),Bg=ne(t=>t.with(_,Za)),fI=ne(t=>t.with(_,de,Ae)),hI="z",pI=pe({phase:"update"},t=>{ie(t,ig,e=>{const n=vt(e);G(e,n,_,{tag:"selection-box",position:[0,0],size:[0,0],rotateZ:0,rank:hI}),G(e,n,Za,{})}),ie(t,ag,(e,{bounds:n,deselectOthers:r})=>{const o=Bg.current(e);if(o.length===0){console.warn("Can't update selection box: not found");return}const s=o[0],i=_.write(e,s),a=n[0],l=n[1],c=n[2]-n[0],u=n[3]-n[1];i.position=[a,l],i.size=[c,u];const d=CA(e,n,fI.current(e));if(r)for(const h of dI.current(e))!d.includes(h)&&yi(e,h);for(const h of d)Ms(e,h)}),ie(t,lg,e=>{const n=Bg.current(e);if(n.length===0){console.warn("Can't remove selection box: not found");return}const r=n[0];Ye(e,r)})}),Qa=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function mI(t={}){return{name:yg,resources:E2.parse(t),components:Object.values(mg).filter(e=>e instanceof Kt),singletons:Object.values(kg).filter(e=>e instanceof bt),blockDefs:[{tag:"selection-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[Za]},{tag:"transform-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[Vt]},{tag:"transform-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[ze]},{tag:"transform-edge",stratum:"overlay",canRotate:!1,canScale:!1,components:[ze]},{tag:"transform-rotate",stratum:"overlay",canRotate:!1,canScale:!1,components:[ze]}],systems:[...Qa(Eg),...Qa(vg),...Qa(xg),...Qa(bg)],keybinds:[{command:tg.name,key:Xt.X,mod:!0},{command:ng.name,key:Xt.C,mod:!0},{command:rg.name,key:Xt.V,mod:!0},{command:Xm.name,key:Xt.Delete},{command:sg.name,key:Xt.A,mod:!0},{command:Gm.name,key:Xt.BracketRight},{command:Qm.name,key:Xt.BracketLeft}],cursors:S2}}var gI=Object.defineProperty,Pg=(t,e)=>{for(var n in e)gI(t,n,{get:e[n],enumerable:!0})},Ng={};Pg(Ng,{ArcArrow:()=>ge,ArrowHandle:()=>On,ArrowTerminal:()=>ki,ElbowArrow:()=>Se});var yI="arrows",Dg="zzzzz",wI=24,Og=50,Wu=4,kI=4,Uu=24,Qr=24,Rg=40,Dn={Idle:"idle",Pointing:"pointing",Dragging:"dragging"},As={None:"none",Idle:"idle"},Me={Start:"start",Middle:"middle",End:"end"},Ce={None:"none",V:"v",Delta:"delta",Circle:"circle",Diamond:"diamond"},Io={Arc:"arc",Elbow:"elbow"},el=0,tl=1,nl=2,rl=3,ol=4,sl=5,Hu=6,vI={value:E.tuple(E.float64(),7).default([0,0,.5,.5,1,1,Wu]),startArrowHead:E.enum(Ce).default(Ce.None),endArrowHead:E.enum(Ce).default(Ce.V),trimStart:E.float64().default(0),trimEnd:E.float64().default(1)},bI=class extends Kt{constructor(){super({name:"arcArrow",sync:"document"},vI)}getA(t,e){const{value:n}=this.read(t,e);return[n[el],n[tl]]}getB(t,e){const{value:n}=this.read(t,e);return[n[nl],n[rl]]}getC(t,e){const{value:n}=this.read(t,e);return[n[ol],n[sl]]}getThickness(t,e){const{value:n}=this.read(t,e);return n[Hu]}setA(t,e,n){const{value:r}=this.write(t,e);r[el]=n[0],r[tl]=n[1]}setB(t,e,n){const{value:r}=this.write(t,e);r[nl]=n[0],r[rl]=n[1]}setC(t,e,n){const{value:r}=this.write(t,e);r[ol]=n[0],r[sl]=n[1]}setThickness(t,e,n){const{value:r}=this.write(t,e);r[Hu]=n}getWorldArc(t,e){const{value:n}=this.read(t,e),r=_.uvToWorld(t,e,[n[el],n[tl]]),o=_.uvToWorld(t,e,[n[nl],n[rl]]),s=_.uvToWorld(t,e,[n[ol],n[sl]]);return[r[0],r[1],o[0],o[1],s[0],s[1],n[Hu]]}getWorldPoints(t,e){const{value:n}=this.read(t,e);return{a:_.uvToWorld(t,e,[n[el],n[tl]]),b:_.uvToWorld(t,e,[n[nl],n[rl]]),c:_.uvToWorld(t,e,[n[ol],n[sl]])}}isCurved(t,e){const{value:n}=this.read(t,e);return!xe.isCollinear(n)}directionAt(t,e,n){const r=this.getWorldArc(t,e);return xe.directionAt(r,n)}pointAt(t,e,n){const r=this.getWorldArc(t,e);return xe.parametricToPoint(r,n)}length(t,e){const n=this.getWorldArc(t,e);return xe.length(n)}containsPoint(t,e,n){const r=this.getWorldArc(t,e);return xe.containsPoint(r,n)}},ge=new bI,On=He({name:"arrowHandle"},{kind:E.enum(Me).default(Me.Start),arrowEntity:E.ref()}),ki=He({name:"arrowTerminal"},{blockEntity:E.ref(),terminalIndex:E.uint8().default(0)}),SI={points:E.buffer(E.float64()).size(Uu*2),pointCount:E.uint8().default(0),thickness:E.float32().default(Wu),startArrowHead:E.enum(Ce).default(Ce.None),endArrowHead:E.enum(Ce).default(Ce.V),trimStart:E.float64().default(0),trimEnd:E.float64().default(1)},EI=class extends Kt{constructor(){super({name:"elbowArrow",sync:"document"},SI)}snapshot(t,e){const n=super.snapshot(t,e);return n.points=n.points.slice(0,n.pointCount*2),n}getPoint(t,e,n){const{points:r}=this.read(t,e);return[r[n*2],r[n*2+1]]}setPoint(t,e,n,r){const{points:o}=this.write(t,e);o[n*2]=r[0],o[n*2+1]=r[1]}getPoints(t,e){const{points:n,pointCount:r}=this.read(t,e),o=[];for(let s=0;s<r;s++)o.push([n[s*2],n[s*2+1]]);return o}setPoints(t,e,n){if(n.length>Uu)throw new Error(`ElbowArrow points exceed capacity of ${Uu}`);const r=this.write(t,e);for(let o=0;o<n.length;o++)r.points[o*2]=n[o][0],r.points[o*2+1]=n[o][1];r.pointCount=n.length}getStartWorld(t,e){const n=this.getPoint(t,e,0);return _.uvToWorld(t,e,n)}getEndWorld(t,e){const{pointCount:n}=this.read(t,e),r=this.getPoint(t,e,n-1);return _.uvToWorld(t,e,r)}getWorldPoints(t,e){return this.getPoints(t,e).map(r=>_.uvToWorld(t,e,r))}getThickness(t,e){const{thickness:n}=this.read(t,e);return n}},Se=new EI,zg={};Pg(zg,{ArrowDrawState:()=>ju,ArrowTransformState:()=>$g});var ju=Gr("arrowDrawState",{state:E.string().max(16).default(Dn.Idle),activeArrow:E.ref(),kind:E.enum(Io).default(Io.Elbow),pointingStartClient:E.tuple(E.int32(),2).default([0,0]),pointingStartWorld:E.tuple(E.float64(),2).default([0,0])}),$g=Gr("arrowTransformState",{state:E.string().max(16).default(As.None),activeArrow:E.ref()}),Lg=le("arrows-add-arrow"),Fg=le("arrows-remove-arrow"),Vg=le("arrows-add-or-update-transform-handles"),Wg=le("arrows-remove-transform-handles"),Ug=le("arrows-hide-transform-handles"),Hg=le("arrows-show-transform-handles"),CI=yr({guards:{isThresholdReached:({context:t,event:e})=>z.distance(t.pointingStartClient,e.screenPosition)>=kI},actions:{setPointingStart:Oe({pointingStartClient:({event:t})=>[t.screenPosition[0],t.screenPosition[1]],pointingStartWorld:({event:t})=>[t.worldPosition[0],t.worldPosition[1]]}),resetContext:Oe({pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],activeArrow:()=>null}),addArrow:Oe({activeArrow:({context:t,event:e})=>{const n=t.kind,r=t.pointingStartWorld,o=vt(e.ctx);return Lg.spawn(e.ctx,{entityId:o,position:r,kind:n}),o}}),removeArrow:Oe({activeArrow:({context:t,event:e})=>(t.activeArrow&&Fg.spawn(e.ctx,{entityId:t.activeArrow}),null)}),exitArrowControl:({event:t})=>{const e=Qe.write(t.ctx);e.leftMouseTool="select";const n=kn.write(t.ctx);n.cursorKind="select"},deselectAll:({event:t})=>{mi.spawn(t.ctx)}}}).createMachine({id:"arrowDraw",initial:Dn.Idle,context:{activeArrow:null,kind:Io.Elbow,pointingStartClient:[0,0],pointingStartWorld:[0,0]},states:{[Dn.Idle]:{entry:"resetContext",on:{pointerDown:[{actions:"deselectAll",target:Dn.Pointing}]}},[Dn.Pointing]:{entry:"setPointingStart",on:{pointerMove:{guard:"isThresholdReached",target:Dn.Dragging},pointerUp:{target:Dn.Idle},cancel:{target:Dn.Idle}}},[Dn.Dragging]:{entry:"addArrow",exit:"exitArrowControl",on:{pointerUp:{target:Dn.Idle},cancel:{actions:"removeArrow",target:Dn.Idle}}}}}),xI=pe({phase:"capture",priority:100},t=>{const e=Qe.getButtons(t,"arc-arrow","elbow-arrow");if(e.length===0)return;const n=br(t,e);if(n.length===0)return;const r=Qe.read(t).leftMouseTool,o=ju.write(t);o.kind=r==="elbow-arrow"?Io.Elbow:Io.Arc,ju.run(t,CI,n)}),Zu=ne(t=>t.with(_).tracking(ht)),TI=yr({guards:{selectingSingleArrow:({event:t})=>{if(!("selectedEntities"in t)||t.selectedEntities.length!==1)return!1;const e=t.selectedEntities[0];return O(t.ctx,e,ge)||O(t.ctx,e,Se)}},actions:{setActiveArrow:Oe({activeArrow:({event:t})=>!("selectedEntities"in t)||t.selectedEntities.length===0?null:t.selectedEntities[0]}),addOrUpdateTransformHandles:({context:t,event:e})=>{t.activeArrow&&Vg.spawn(e.ctx,{arrowEntityId:t.activeArrow})},removeTransformHandles:({event:t})=>{Wg.spawn(t.ctx,{})},hideTransformHandles:({event:t})=>{Ug.spawn(t.ctx,{})},showTransformHandles:({event:t})=>{Hg.spawn(t.ctx,{})}}}).createMachine({id:"arrowTransform",initial:As.None,context:{activeArrow:null},states:{[As.None]:{entry:"removeTransformHandles",on:{selectionChanged:[{guard:"selectingSingleArrow",actions:"setActiveArrow",target:As.Idle}]}},[As.Idle]:{entry:"addOrUpdateTransformHandles",on:{selectionChanged:[{guard:Co("selectingSingleArrow"),target:As.None},{actions:["setActiveArrow","addOrUpdateTransformHandles"]}],pointerDown:{actions:"hideTransformHandles"},pointerUp:{actions:"showTransformHandles"}}}}}),MI=pe({phase:"capture",priority:99},t=>{const e=_I(t);e.length!==0&&$g.run(t,TI,e)});function _I(t){const e=[],n=Zu.added(t),r=Zu.removed(t);if(n.length>0||r.length>0){const i=[...Zu.current(t)];e.push({type:"selectionChanged",ctx:t,selectedEntities:i})}const o=Qe.getButtons(t,"select"),s=br(t,o);return e.push(...s),e}var AI=class{constructor(){this.heap=[],this.positions=new Map}parent(t){return Math.floor((t-1)/2)}leftChild(t){return 2*t+1}rightChild(t){return 2*t+2}swap(t,e){this.positions.set(this.heap[t].id,e),this.positions.set(this.heap[e].id,t),[this.heap[t],this.heap[e]]=[this.heap[e],this.heap[t]]}bubbleUp(t){for(;t>0&&this.heap[this.parent(t)].distance>this.heap[t].distance;)this.swap(t,this.parent(t)),t=this.parent(t)}bubbleDown(t){let e=t;const n=this.leftChild(t);n<this.heap.length&&this.heap[n].distance<this.heap[e].distance&&(e=n);const r=this.rightChild(t);r<this.heap.length&&this.heap[r].distance<this.heap[e].distance&&(e=r),t!==e&&(this.swap(t,e),this.bubbleDown(e))}insert(t,e){this.heap.push({id:t,distance:e});const n=this.heap.length-1;this.positions.set(t,n),this.bubbleUp(n)}extractMin(){if(this.heap.length===0)return null;const t=this.heap[0],e=this.heap.pop();return this.positions.delete(t.id),this.heap.length>0&&(this.heap[0]=e,this.positions.set(e.id,0),this.bubbleDown(0)),t}decreaseKey(t,e){const n=this.positions.get(t);n!==void 0&&(this.heap[n].distance=e,this.bubbleUp(n))}isEmpty(){return this.heap.length===0}contains(t){return this.positions.has(t)}};function II(t,e,n,r,o,s,i){return new BI(t,e,n,s,i).calculate(r,o)}var BI=class{constructor(t,e,n,r,o){this.ctx=t,this.padding=r,this.rotation=o;const s=z.midPoint(e,n);this.toLocal=Te.fromTranslation(-s[0],-s[1]),Te.rotate(this.toLocal,-o),this.toWorld=Te.fromRotation(o),Te.translate(this.toWorld,s[0],s[1]),this.localStart=this.transformToLocal(e),this.localEnd=this.transformToLocal(n)}transformToLocal(t){const e=z.clone(t);return Te.transformPoint(this.toLocal,e),e}transformToWorld(t){const e=z.clone(t);return Te.transformPoint(this.toWorld,e),e}calculate(t,e){const n=this.calculateRay(this.localStart,this.localEnd,t),r=this.calculateRay(this.localEnd,this.localStart,e);let o;if(t&&e){const s=this.isPointInsideBlockMargin(this.localStart,e),i=this.isPointInsideBlockMargin(this.localEnd,t);s||i?o=vi(lt.origin(n),lt.origin(r)):o=this.routeBlockToBlock(t,e,n,r)}else t&&!e?this.isPointInsideBlockMargin(this.localEnd,t)?o=vi(lt.origin(n),this.localEnd):o=this.routeBlockToPoint(t,n,this.localEnd):!t&&e?this.isPointInsideBlockMargin(this.localStart,e)?o=vi(this.localStart,lt.origin(r)):o=this.routeBlockToPoint(e,r,this.localStart).reverse():o=vi(lt.origin(n),this.localEnd);for(let s=0;s<o.length;s++)o[s]=this.transformToWorld(o[s]);return o}getBlockAabb(t){const e=_.read(this.ctx,t),n=[e.position[0]+e.size[0]/2,e.position[1]+e.size[1]/2],r=this.transformToLocal(n),o=(e.rotateZ||0)-this.rotation,s=[r[0]-e.size[0]/2,r[1]-e.size[1]/2],i=[0,0,0,0];return ot.getAabb(s,e.size,o,i),i}isPointInsideBlockMargin(t,e){const n=this.getBlockAabb(e);return Q.pad(n,this.padding),Q.containsPoint(n,t)}routeBlockToBlock(t,e,n,r){const o=this.getBlockAabb(t),s=this.getBlockAabb(e);Q.pad(o,this.padding),Q.pad(s,this.padding),OI(o,s);const i=RI(o,s),a=il(n,i),l=il(r,i),c=lt.origin(n),u=lt.origin(r);if(a===null||l===null)return console.warn("[routeBlockToBlock] Failed to add start or end node to graph"),[c,u];const d=Yg(i,a,l);if(d===null)return[c,u];const h=[c];for(const p of d){const m=i.find(g=>g.id===p);m&&h.push(m.coords)}return h.push(u),PI(h),jg(h),NI(h),h}routeBlockToPoint(t,e,n){const r=lt.origin(e),o=lt.direction(e),s=al(r,n);if(o[0]===s[0]&&o[1]===s[1])return vi(r,n);const i=this.getBlockAabb(t);Q.pad(i,this.padding);const a=lt.fromPoints(n,[-s[0],-s[1]]),l=lt.intersectAabb(a,i);l.length===0&&Q.expand(i,n);const c=Q.corners(i),u=Zg(c),d=il(a,u),h=il(e,u);if(h===null||d===null)return[r,n];const p=Yg(u,h,d);if(p===null)return[r,n];const m=[r];for(const g of p){const y=u.find(w=>w.id===g);y&&m.push(y.coords)}return l.length>0&&m.push(n),jg(m),m}calculateRay(t,e,n){let r;return n?r=this.exitClosestSide(t,n).direction:r=al(t,e),lt.fromPoints(t,r)}exitClosestSide(t,e){const n=_.read(this.ctx,e),r=_.getCenter(this.ctx,e),o=this.transformToWorld(t),s=z.clone(o),i=z.clone(r);z.sub(i,o),z.scale(i,.01),z.add(s,i);const a=[[0,-1],[1,0],[0,1],[-1,0]],l=a.map(m=>{const g=z.clone(m);return z.rotate(g,this.rotation),g}),c=[];for(let m=0;m<l.length;m++){const g=l[m],y=lt.fromPoints(s,g),w=lt.intersectRect(y,n.position,n.size,n.rotateZ);w.length!==0&&c.push({direction:a[m],distance:w[0].distance})}if(c.length===0)return console.error("[exitClosestSide] No valid exit direction found!",{point:t,nudgedPoint:s,blockPosition:n.position,blockSize:n.size,blockRotateZ:n.rotateZ,center:r}),{direction:[0,-1],distance:0};c.sort((m,g)=>m.distance-g.distance);const u=c[0],d=(o[0]-n.position[0])/n.size[0],h=(o[1]-n.position[1])/n.size[1],p=.2;if(Math.abs(d-.5)<p&&Math.abs(h-.5)<p){const m=al(t,this.localEnd),g=c.find(y=>y.direction[0]===m[0]&&y.direction[1]===m[1]);if(g)return g}return u}};function vi(t,e){const n=[];n.push(t);const r=e[0]-t[0],o=e[1]-t[1];if(Ct.approxEqual(o,0)||Ct.approxEqual(r,0))return n.push(e),n;const s=al(t,e);let i;s[0]===1?i=r:s[0]===-1?i=-r:s[1]===1?i=o:i=-o;const a=[t[0]+s[0]*i/2,t[1]+s[1]*i/2];return n.push(a),s[0]===0?n.push([e[0],a[1]]):n.push([a[0],e[1]]),n.push(e),n}function PI(t){if(t.length<2)return;const e=[t[0]];for(let n=1;n<t.length;n++){const r=e[e.length-1],o=t[n],s=Ct.approxEqual(r[0],o[0]),i=Ct.approxEqual(r[1],o[1]);(!s||!i)&&e.push(o)}t.length=0,t.push(...e)}function jg(t){if(t.length<3)return;const e=[];for(let n=1;n<t.length-1;n++){const r=t[n-1],o=t[n],s=t[n+1],i=Ct.approxEqual(r[0],o[0])&&Ct.approxEqual(o[0],s[0]),a=Ct.approxEqual(r[1],o[1])&&Ct.approxEqual(o[1],s[1]);(i||a)&&e.push(n)}for(let n=e.length-1;n>=0;n--)t.splice(e[n],1)}function NI(t){if(t.length<3)return;const e=[];for(let r=1;r<t.length-1;r++){const o=t[r-1],s=t[r],i=t[r+1],a=DI(o,s,i);e.push(a)}const n=[];for(let r=1;r<e.length-1;r++){const o=e[r-1],s=e[r],i=e[r+1];if(o==="left"&&s==="right"&&i==="left"||o==="right"&&s==="left"&&i==="right"){const l=Math.abs(t[r+1][0]-t[r][0])<1e-6,c=Math.abs(t[r+1][1]-t[r][1])<1e-6;if(l)t[r+1][0]=t[r+2][0],t[r+1][1]=t[r][1];else if(c)t[r+1][0]=t[r][0],t[r+1][1]=t[r+2][1];else continue;n.push(r),n.push(r+2)}}for(let r=n.length-1;r>=0;r--)t.splice(n[r],1)}function DI(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])>0?"left":"right"}function OI(t,e){if(!Q.intersects(t,e)){if(t[2]<e[0]){const n=(t[2]+e[0])/2;t[2]=n,e[0]=n}else if(e[2]<t[0]){const n=(e[2]+t[0])/2;e[2]=n,t[0]=n}if(t[3]<e[1]){const n=(t[3]+e[1])/2;t[3]=n,e[1]=n}else if(e[3]<t[1]){const n=(e[3]+t[1])/2;e[3]=n,t[1]=n}}}function Zg(t){const e=t.map((n,r)=>({id:r,connections:[],distances:{},coords:n}));return Kg(e,0),Kg(e,1),e}function Kg(t,e){const n={},r=1-e;for(const o of t){const s=Math.round(o.coords[e]);n[s]||(n[s]=[]),n[s].push(o)}for(const o of Object.values(n)){o.sort((s,i)=>s.coords[r]-i.coords[r]);for(let s=0;s<o.length-1;s++){const i=o[s],a=o[s+1];i.connections.push(a.id),a.connections.push(i.id);const l=Math.abs(a.coords[r]-i.coords[r]);i.distances[a.id]=l,a.distances[i.id]=l}}}function RI(t,e){if(!Q.intersects(t,e))return[];const n=[],r=Q.corners(t),o=Q.corners(e);for(const c of r)Q.containsPoint(e,c,!1)||n.push(c);for(const c of o)Q.containsPoint(t,c,!1)||n.push(c);const s=Q.clone(t);Q.intersection(s,e);const i=Q.corners(s);for(const c of i)Q.containsPoint(t,c,!1)||Q.containsPoint(e,c,!1)||n.push(c);const a=[],l=new Set;for(const c of n){const u=c.map(Math.round).join(",");l.has(u)||(a.push(c),l.add(u))}return Zg(a)}function il(t,e){const n=lt.origin(t),r=e.find(p=>p.coords[0]===n[0]&&p.coords[1]===n[1]);if(r)return r.id;let o=null,s=-1,i=-1;for(const p of e)for(const m of p.connections){if(p.id>=m)continue;const g=e.find(w=>w.id===m);if(!g)continue;const y=lt.intersectSegment(t,p.coords,g.coords);y&&(o===null||y.distance<o.distance)&&(o=y,s=p.id,i=m)}if(!o||s===-1||i===-1)return console.warn("[intersectRayAndAddNode] No intersection found for ray",t,o,s,i),null;const a=e.length,l={id:a,connections:[],distances:{},coords:o.point},c=e[s],u=e[i],d=Math.hypot(o.point[0]-c.coords[0],o.point[1]-c.coords[1]),h=Math.hypot(o.point[0]-u.coords[0],o.point[1]-u.coords[1]);return l.connections.push(s,i),l.distances[s]=d,l.distances[i]=h,c.connections.push(a),c.distances[a]=d,u.connections.push(a),u.distances[a]=h,c.connections=c.connections.filter(p=>p!==i),delete c.distances[i],u.connections=u.connections.filter(p=>p!==s),delete u.distances[s],e.push(l),a}function Yg(t,e,n){const r={},o={},s=new AI;for(const i of t)r[i.id]=Number.POSITIVE_INFINITY,o[i.id]=null;for(r[e]=0,s.insert(e,0);!s.isEmpty();){const i=s.extractMin();if(!i)break;const a=i.id;if(a===n){const c=[];let u=n;for(;u!==null;)c.unshift(u),u=o[u];return c}const l=t.find(c=>c.id===a);if(l)for(const c of l.connections){const u=r[a]+(l.distances[c]||1);u<r[c]&&(r[c]=u,o[c]=a,s.contains(c)?s.decreaseKey(c,u):s.insert(c,u))}}return null}function al(t,e){const n=e[0]-t[0],r=e[1]-t[1];return Math.abs(n)>Math.abs(r)?[Math.sign(n),0]:[0,Math.sign(r)]}function qg(t,e){if(t.length===0)return null;let n=t[0],r=z.distanceSq(t[0],e);for(let o=1;o<t.length;o++){const s=z.distanceSq(t[o],e);s<r&&(r=s,n=t[o])}return n}function zI(t,e,n){const r=[t[0]-n[0],t[1]-n[1]],o=[e[0]-n[0],e[1]-n[1]],s=Math.atan2(r[1],r[0]);let a=Math.atan2(o[1],o[0])-s;a>Math.PI&&(a-=2*Math.PI),a<-Math.PI&&(a+=2*Math.PI);const l=Math.hypot(r[0],r[1]),u=Math.hypot(o[0],o[1])-l;return{angle:a,distance:u}}function $I(t,e,n,r){const o=Math.atan2(t[1]-r[1],t[0]-r[0])+e,s=Math.hypot(t[0]-r[0],t[1]-r[1])+n;return[r[0]+Math.cos(o)*s,r[1]+Math.sin(o)*s]}var Jg=20,LI=ne(t=>t.tracking(ge,Re)),FI=ne(t=>t.tracking(Se,Re)),VI=pe({phase:"update",priority:-10},t=>{for(const e of LI.addedOrChanged(t))WI(t,e);for(const e of FI.addedOrChanged(t))UI(t,e)});function WI(t,e){O(t,e,ye)||G(t,e,ye,{});const n=ge.read(t,e),r=xe.clone(n.value);r[6]=Math.max(r[6],Jg),ye.clear(t,e),ye.addArc(t,e,r),HI(t,e)}function UI(t,e){O(t,e,ye)||G(t,e,ye,{});const n=Se.read(t,e),r=Math.max(n.thickness,Jg),o=Se.getPoints(t,e),s=ye.write(t,e),i=Math.min(o.length-1,Ss);s.capsuleCount=i,s.arcCount=0;for(let a=0;a<i;a++){const l=o[a],c=o[a+1],u=rt.create(l[0],l[1],c[0],c[1],r/2);ye.setCapsuleAt(t,e,a,u)}jI(t,e)}function HI(t,e){const n=Re.read(t,e),r=ge.getWorldArc(t,e),{a:o,c:s}=ge.getWorldPoints(t,e);let i=Xg(t,n.startBlock,r,o),a=Xg(t,n.endBlock,r,s);1-a-i<.1&&(i=0,a=0);const l=ge.read(t,e);if(!Ct.approxEqual(l.trimStart,i)||!Ct.approxEqual(l.trimEnd,a)){const u=ge.write(t,e);u.trimStart=i,u.trimEnd=a}const c=ye.read(t,e);for(let u=0;u<c.arcCount;u++){const d=ye.getArcAt(t,e,u);xe.trim(d,i,1-a),ye.setArcAt(t,e,u,d)}}function Xg(t,e,n,r){if(!e)return 0;const o=_.getCorners(t,e),s=xe.intersectRect(n,o);if(s.length===0)return 0;const i=qg(s,r);return i?xe.pointToParametric(n,i)??0:0}function jI(t,e){const n=Re.read(t,e),r=Se.getWorldPoints(t,e),o=r.length-1;if(o<1)return;const s=r[0],i=r[r.length-1],a=r[1],l=r[r.length-2],c=Gg(t,n.startBlock,s,a),u=Gg(t,n.endBlock,i,l),d=Se.read(t,e);if(!Ct.approxEqual(d.trimStart,c)||!Ct.approxEqual(d.trimEnd,u)){const g=Se.write(t,e);g.trimStart=c,g.trimEnd=u}const h=ye.getCapsuleAt(t,e,0);rt.trim(h,c,1),ye.setCapsuleAt(t,e,0,h);const p=o-1,m=ye.getCapsuleAt(t,e,p);rt.trim(m,0,1-u),ye.setCapsuleAt(t,e,p,m)}function Gg(t,e,n,r){if(!e)return 0;const o=_.getCorners(t,e),s=[];for(let d=0;d<4;d++){const h=o[d],p=o[(d+1)%4],m=ZI(n,r,h,p);m&&s.push(m)}if(s.length===0)return 0;const i=qg(s,n);if(!i)return 0;const a=r[0]-n[0],l=r[1]-n[1],c=Math.hypot(a,l);if(c<.001)return 0;const u=((i[0]-n[0])*a+(i[1]-n[1])*l)/(c*c);return Math.max(0,Math.min(1,u))}function ZI(t,e,n,r){const o=e[0]-t[0],s=e[1]-t[1],i=r[0]-n[0],a=r[1]-n[1],l=o*a-s*i;if(Math.abs(l)<1e-10)return null;const c=n[0]-t[0],u=n[1]-t[1],d=(c*a-u*i)/l,h=(c*s-u*o)/l;return d>=0&&d<=1&&h>=0&&h<=1?[t[0]+d*o,t[1]+d*s]:null}var ll=ne(t=>t.with(On,_)),KI=ne(t=>t.with(de,Ae).tracking(_)),Qg=ne(t=>t.with(ki,_)),YI=pe({phase:"update"},t=>{ie(t,Lg,(e,{entityId:n,position:r,kind:o})=>{JI(e,n,r,o)}),ie(t,Fg,(e,{entityId:n})=>{XI(e,n)}),ie(t,Vg,(e,{arrowEntityId:n})=>{Ku(e,n)}),ie(t,Wg,e=>{nB(e)}),ie(t,Ug,e=>{Yu(e)}),ie(t,Hg,e=>{rB(e)}),ie(t,pi,(e,{entityId:n,position:r})=>{GI(e,n,r)}),qI(t)});function qI(t){const e=KI.addedOrChangedOrRemoved(t);if(e.length===0)return;const n=new Set;for(const r of e){const o=Jn(t,r,Re,"startBlock",!1);for(const i of o)n.has(i)||(n.add(i),ey(t,i));const s=Jn(t,r,Re,"endBlock",!1);for(const i of s)n.has(i)||(n.add(i),ey(t,i))}}function ey(t,e){const n=Re.read(t,e);if(O(t,e,ge)){const{a:r,c:o}=ge.getWorldPoints(t,e);let s=r,i=o;n.startBlock!==null&&(s=_.uvToWorld(t,n.startBlock,n.startBlockUv),qu(t,e,Me.Start,s)),n.endBlock!==null&&(i=_.uvToWorld(t,n.endBlock,n.endBlockUv),qu(t,e,Me.End,i))}else if(O(t,e,Se)){if(n.startBlock!==null){const r=_.uvToWorld(t,n.startBlock,n.startBlockUv);Ju(t,e,Me.Start,r)}if(n.endBlock!==null){const r=_.uvToWorld(t,n.endBlock,n.endBlockUv);Ju(t,e,Me.End,r)}}}function JI(t,e,n,r){const o=Wu,s=r===Io.Elbow?"elbow-arrow":"arc-arrow",a=Xr.getAll(t).find(h=>O(t,h,de)&&Xu(t,h))??null;let l=n,c=[0,0];if(a!==null){const h=Gu(t,a,n);h!==null?(l=h.position,c=h.uv):(l=_.uvToWorld(t,a,[.5,.5]),c=[.5,.5])}G(t,e,_,{tag:s,rank:In.genNext(t),position:l,size:[o,o]}),G(t,e,de,{id:crypto.randomUUID()}),r===Io.Arc?G(t,e,ge,{value:[0,0,.5,.5,1,1,o],startArrowHead:Ce.None,endArrowHead:Ce.V}):G(t,e,Se,{points:[0,0,.5,0,.5,1,1,1],pointCount:4,thickness:o,startArrowHead:Ce.None,endArrowHead:Ce.V}),G(t,e,Re,{startBlock:a,startBlockUv:c}),Ms(t,e);const d=Ku(t,e).find(h=>On.read(t,h).kind===Me.End);if(d){const h=_.read(t,d),p=Nn.write(t);p.state=me.Dragging,p.draggedEntity=d,p.dragStart=l,p.draggedEntityStart=[h.position[0],h.position[1]],Yu(t)}}function XI(t,e){Ye(t,e)}function GI(t,e,n){O(t,e,ge)?QI(t,e):O(t,e,Se)?eB(t,e):O(t,e,On)&&tB(t,e,n)}function QI(t,e){const n=Re.read(t,e);if(n.startBlock!==null){const{a:r}=ge.getWorldPoints(t,e);bi(t,e,Me.Start,r)}if(n.endBlock!==null){const{c:r}=ge.getWorldPoints(t,e);bi(t,e,Me.End,r)}}function eB(t,e){const n=Re.read(t,e);if(n.startBlock!==null){const r=Se.getStartWorld(t,e);bi(t,e,Me.Start,r)}if(n.endBlock!==null){const r=Se.getEndWorld(t,e);bi(t,e,Me.End,r)}}function tB(t,e,n){const r=On.read(t,e),o=r.arrowEntity;if(!o)return;const s=_.read(t,e);let i=[n[0]+s.size[0]/2,n[1]+s.size[1]/2];if(r.kind!==Me.Middle){const a=lB(t,o,r.kind,i);a!==null&&(i=a)}O(t,o,ge)?qu(t,o,r.kind,i):O(t,o,Se)&&Ju(t,o,r.kind,i),r.kind!==Me.Middle&&bi(t,o,r.kind,i)}function Ku(t,e){const n=wI,r=[Me.Start,Me.End];O(t,e,ge)&&r.push(Me.Middle);const o=Array.from(ll.current(t)),s=new Map;for(const l of o){const c=On.read(t,l);s.set(c.kind,l)}const i=new Set;for(const l of r){const c=oB(t,e,l),u=c[0]-n/2,d=c[1]-n/2;let h=s.get(l);h||(h=vt(t),G(t,h,On),G(t,h,_),G(t,h,Jr),G(t,h,ze,{kind:"arrow"}));const p=On.write(t,h);p.kind=l,p.arrowEntity=e;const m=_.write(t,h);m.tag="arrow-handle",m.rank=Dg,m.position=[u,d],m.size=[n,n];const g=Jr.write(t,h);g.startPosition=[u,d],g.startSize=[n,n],i.add(h)}for(const l of o)i.has(l)||Ye(t,l);const a=Nn.read(t);return a.state===me.Dragging&&a.draggedEntity!==null&&O(t,a.draggedEntity,On)&&Yu(t),Array.from(i)}function nB(t){for(const e of ll.current(t))Ye(t,e);cl(t)}function Yu(t){for(const e of ll.current(t))if(!O(t,e,Ge))G(t,e,Ge,{value:0});else{const n=Ge.write(t,e);n.value=0}}function rB(t){const e=ll.current(t);for(const n of e)O(t,n,Ge)&&nn(t,n,Ge);if(e.length>0){const n=On.read(t,e[0]);n.arrowEntity&&Ku(t,n.arrowEntity)}cl(t)}function oB(t,e,n){if(O(t,e,ge)){const{a:r,b:o,c:s}=ge.getWorldPoints(t,e);switch(n){case Me.Start:return r;case Me.Middle:return o;case Me.End:return s}}if(O(t,e,Se))switch(n){case Me.Start:return Se.getStartWorld(t,e);case Me.End:return Se.getEndWorld(t,e)}return console.warn("Arrow entity has no recognized arrow component"),[0,0]}function qu(t,e,n,r){const{a:o,b:s,c:i}=ge.getWorldPoints(t,e);let a=o,l=s,c=i,u=[0,0],d=[0,0];if(n===Me.Start?(u=o,d=i,a=r):n===Me.Middle?l=r:(u=i,d=o,c=r),n!==Me.Middle){const{angle:w,distance:k}=zI(u,r,d);l=$I(s,w,.5*k,d)}const h=_.write(t,e),p=Math.min(a[0],l[0],c[0]),m=Math.min(a[1],l[1],c[1]),g=Math.max(a[0],l[0],c[0]),y=Math.max(a[1],l[1],c[1]);h.position=[p,m],h.size=[g-p||1,y-m||1],ge.setA(t,e,_.worldToUv(t,e,a)),ge.setB(t,e,_.worldToUv(t,e,l)),ge.setC(t,e,_.worldToUv(t,e,c))}function Ju(t,e,n,r){const o=Re.read(t,e);let s,i;n===Me.Start?(s=r,o.endBlock!==null?i=_.uvToWorld(t,o.endBlock,o.endBlockUv):i=Se.getEndWorld(t,e)):(o.startBlock!==null?s=_.uvToWorld(t,o.startBlock,o.startBlockUv):s=Se.getStartWorld(t,e),i=r);const l=_.read(t,e).rotateZ||0,c=II(t,s,i,o.startBlock,o.endBlock,Og,l),u=_.write(t,e),d=[0,0],h=[1,1];ot.boundPoints(d,h,l,c),u.position=d,u.size=[Math.max(h[0],1),Math.max(h[1],1)];const p=c.map(m=>_.worldToUv(t,e,m));Se.setPoints(t,e,p)}function bi(t,e,n,r){let s=Xr.getAll(t).find(l=>l!==e&&O(t,l,de)&&!O(t,l,Re)&&Xu(t,l))??null;const i=Re.write(t,e);if(s!==null){const l=n===Me.Start?i.endBlock:i.startBlock;s===l&&(s=null)}s!==null?aB(t,s):cl(t);let a=[0,0];if(s!==null){const l=Gu(t,s,r,Rg);l!==null?a=l.uv:a=_.worldToUv(t,s,r)}n===Me.Start?(i.startBlock=s,i.startBlockUv=a):(i.endBlock=s,i.endBlockUv=a),sB(t,e)}function sB(t,e){const n=Re.read(t,e);let r=null;for(const s of[n.startBlock,n.endBlock]){if(s===null)continue;const i=_.read(t,s).rank;(r===null||i>r)&&(r=i)}const o=_.read(t,e).rank;if(r!==null&&o<r){const s=_.write(t,e);s.rank=Aa(r,null)}}function Xu(t,e){const n=_.read(t,e).tag;return Ft(t,n).connectors.enabled}function iB(t){const e=Qg.current(t);return e.length===0?null:ki.read(t,e[0]).blockEntity}function aB(t,e){if(iB(t)===e)return;cl(t);const n=_.read(t,e).tag,r=Ft(t,n);if(!r.connectors.enabled)return;const o=r.connectors.terminals;for(let s=0;s<o.length;s++){const i=o[s],a=_.uvToWorld(t,e,i),l=vt(t);G(t,l,ki,{blockEntity:e,terminalIndex:s}),G(t,l,_,{tag:"arrow-terminal",rank:Dg,position:[a[0]-Qr/2,a[1]-Qr/2],size:[Qr,Qr]}),G(t,l,Jr,{startPosition:[a[0]-Qr/2,a[1]-Qr/2],startSize:[Qr,Qr]})}}function cl(t){for(const e of Qg.current(t))Ye(t,e)}function Gu(t,e,n,r){const o=_.read(t,e).tag,s=Ft(t,o);if(!s.connectors.enabled)return null;const i=s.connectors.terminals;if(i.length===0)return null;let a=null,l=r??1/0;for(const c of i){const u=_.uvToWorld(t,e,c),d=u[0]-n[0],h=u[1]-n[1],p=Math.sqrt(d*d+h*h);p<l&&(l=p,a={position:u,uv:c})}return a}function lB(t,e,n,r){const s=Xr.getAll(t).find(c=>c!==e&&O(t,c,de)&&!O(t,c,Re)&&Xu(t,c))??null;if(s===null)return null;const i=Re.read(t,e),a=n===Me.Start?i.endBlock:i.startBlock;if(s===a)return null;const l=Gu(t,s,r,Rg);return l===null?null:l.position}function cB(t={}){return{name:yI,components:Object.values(Ng).filter(e=>e instanceof Kt),singletons:Object.values(zg).filter(e=>e instanceof bt),blockDefs:[{tag:"arc-arrow",resizeMode:"groupOnly",components:[ge,Re,gn],connectors:{enabled:!1}},{tag:"elbow-arrow",resizeMode:"groupOnly",components:[Se,Re,gn],connectors:{enabled:!1}},{tag:"arrow-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[On],connectors:{enabled:!1}},{tag:"arrow-terminal",stratum:"overlay",canRotate:!1,canScale:!1,components:[ki],connectors:{enabled:!1}}],systems:[xI,MI,YI,VI],resources:{elbowArrowPadding:t.elbowArrowPadding??Og}}}const Qu=[{kind:Ce.None,label:"None",gap:0,svg:""},{kind:Ce.V,label:"Arrow",gap:15,svg:'<polyline points="-10,-7 -1,0 -10,7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />'},{kind:Ce.Delta,label:"Triangle",gap:20,svg:'<polygon points="-1,0 -12,-7 -12,7" fill="currentColor" />'},{kind:Ce.Circle,label:"Circle",gap:0,svg:'<circle cx="-6" cy="0" r="6" fill="currentColor" />'},{kind:Ce.Diamond,label:"Diamond",gap:0,svg:'<polygon points="0,0 -7,-6 -14,0 -7,6" fill="currentColor" />'}];function Is(t){return Qu.find(e=>e.kind===t)}const ty=Symbol("floating-menu"),ed=Symbol("toolbar"),ny=Symbol("WovenCanvasTooltip"),Rn=Symbol("woven-canvas");function pt(t,e){const n=f.inject(Rn);if(!n)throw new Error("useComponent must be used within a WovenCanvas component");const r=f.shallowRef(null),o=n.getEditor();if(o){const i=o._getContext();O(i,t,e)&&(r.value=e.snapshot(i,t))}const s=n.subscribeComponent(t,e.name,i=>{r.value=i});return f.onUnmounted(()=>{s()}),r}const uB={key:0},dB=["x1","y1","x2","y2","stroke","stroke-width"],fB=["x1","y1","x2","y2","stroke","stroke-width"],hB=["points","fill"],pB=["cx","cy","r","fill"],mB=["points","fill"],gB=15,yB=2,Sr=f.defineComponent({__name:"ArrowHead",props:{position:{},direction:{},thickness:{},color:{},arrowThickness:{},kind:{}},setup(t){const e=t,n=f.computed(()=>{const a=Math.hypot(e.direction[0],e.direction[1]);if(a===0)return null;const l=(e.arrowThickness/yB)**.33,c=gB*l,u=[e.direction[0]/a,e.direction[1]/a],d=[-u[1],u[0]];return{unitDir:u,perpDir:d,size:c}}),r=f.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=c,d=c,h=[e.position[0]-a[0]*u+l[0]*(d/2),e.position[1]-a[1]*u+l[1]*(d/2)],p=[e.position[0]-a[0]*u-l[0]*(d/2),e.position[1]-a[1]*u-l[1]*(d/2)];return{p1:h,p2:p}}),o=f.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=c,d=c,h=[a[0]*(c*.4),a[1]*(c*.4)],p=[e.position[0]-a[0]*u+h[0],e.position[1]-a[1]*u+h[1]],m=[p[0]+l[0]*(d/2),p[1]+l[1]*(d/2)],g=[p[0]-l[0]*(d/2),p[1]-l[1]*(d/2)],y=[e.position[0]+h[0],e.position[1]+h[1]];return`${y[0]},${y[1]} ${m[0]},${m[1]} ${g[0]},${g[1]}`}),s=f.computed(()=>{if(!n.value)return null;const{unitDir:a,size:l}=n.value,c=l*.8,u=[a[0]*c,a[1]*c];return{center:[e.position[0]-a[0]*c+u[0],e.position[1]-a[1]*c+u[1]],radius:c}}),i=f.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=1.6*c,d=1.6*c,h=[a[0]*(c*.8),a[1]*(c*.8)],p=[e.position[0]-a[0]*(u/2)+h[0],e.position[1]-a[1]*(u/2)+h[1]],m=[e.position[0]-a[0]*u+h[0],e.position[1]-a[1]*u+h[1]],g=[p[0]+l[0]*(d/2),p[1]+l[1]*(d/2)],y=[p[0]-l[0]*(d/2),p[1]-l[1]*(d/2)],w=[e.position[0]+h[0],e.position[1]+h[1]];return`${w[0]},${w[1]} ${g[0]},${g[1]} ${m[0]},${m[1]} ${y[0]},${y[1]}`});return(a,l)=>n.value?(f.openBlock(),f.createElementBlock("g",uB,[t.kind===f.unref(Ce).V&&r.value?(f.openBlock(),f.createElementBlock(f.Fragment,{key:0},[f.createElementVNode("line",{x1:r.value.p1[0],y1:r.value.p1[1],x2:t.position[0],y2:t.position[1],stroke:t.color,"stroke-width":t.thickness,"stroke-linecap":"round"},null,8,dB),f.createElementVNode("line",{x1:r.value.p2[0],y1:r.value.p2[1],x2:t.position[0],y2:t.position[1],stroke:t.color,"stroke-width":t.thickness,"stroke-linecap":"round"},null,8,fB)],64)):t.kind===f.unref(Ce).Delta&&o.value?(f.openBlock(),f.createElementBlock("polygon",{key:1,points:o.value,fill:t.color},null,8,hB)):t.kind===f.unref(Ce).Circle&&s.value?(f.openBlock(),f.createElementBlock("circle",{key:2,cx:s.value.center[0],cy:s.value.center[1],r:s.value.radius,fill:t.color},null,8,pB)):t.kind===f.unref(Ce).Diamond&&i.value?(f.openBlock(),f.createElementBlock("polygon",{key:3,points:i.value,fill:t.color},null,8,mB)):f.createCommentVNode("",!0)])):f.createCommentVNode("",!0)}}),wB={class:"arrow-svg",preserveAspectRatio:"none"},kB=["d","stroke","stroke-width"],vB=["x1","y1","x2","y2","stroke","stroke-width"],bB=["d"],SB=["x1","y1","x2","y2"],EB=f.defineComponent({__name:"ArcArrow",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=f.ref(null),r=f.ref(0),o=f.ref(0),s=pt(e.entityId,gn),i=pt(e.entityId,ge);let a=null;f.onMounted(()=>{n.value&&(a=new ResizeObserver(()=>{n.value&&(r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),a.observe(n.value),r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),f.onUnmounted(()=>{a==null||a.disconnect()});const l=f.computed(()=>{if(!s.value)return"#000000";const b=s.value.red.toString(16).padStart(2,"0"),S=s.value.green.toString(16).padStart(2,"0"),v=s.value.blue.toString(16).padStart(2,"0");return`#${b}${S}${v}`}),c=f.computed(()=>{var b;return((b=i.value)==null?void 0:b.value[6])??2}),u=f.computed(()=>`${c.value}px`),d=f.computed(()=>e.hovered||e.selected),h=f.computed(()=>{if(!i.value)return!1;const b=i.value.value,S=xe.create(b[0],b[1],b[2],b[3],b[4],b[5],b[6]);return!xe.isCollinear(S)}),p=f.computed(()=>{if(!i.value)return null;const b=i.value.value,S=r.value,v=o.value;return xe.create(b[0]*S,b[1]*v,b[2]*S,b[3]*v,b[4]*S,b[5]*v,b[6])}),m=f.computed(()=>!p.value||!h.value?null:xe.compute(p.value)),g=f.computed(()=>{var L,q,se,Z;if(!i.value||!p.value)return null;const b=p.value,S=i.value.startArrowHead,v=i.value.endArrowHead,x=xe.length(b);let T=i.value.trimStart;if((L=e.connector)!=null&&L.startBlock&&S!=="none"){const H=((q=Is(S))==null?void 0:q.gap)??0,J=x>0?H/x:0;T+=J}let A=i.value.trimEnd;if((se=e.connector)!=null&&se.endBlock&&v!=="none"){const H=((Z=Is(v))==null?void 0:Z.gap)??0,J=x>0?H/x:0;A+=J}const P=1-A,$=xe.parametricToPoint(b,T),V=xe.parametricToPoint(b,P),U=k(xe.directionAt(b,T)),M=xe.directionAt(b,P);return{start:$,end:V,startDir:U,endDir:M,tStart:T,tEnd:P,startHead:S,endHead:v}}),y=f.computed(()=>{if(!g.value||!m.value||!h.value)return"";const{start:b,end:S,tStart:v,tEnd:x}=g.value,{radius:T,clockwise:A,arcAngle:P}=m.value,V=P*(x-v)>Math.PI?1:0,U=A?0:1;return`M ${b[0]} ${b[1]} A ${T} ${T} 0 ${V} ${U} ${S[0]} ${S[1]}`}),w=f.computed(()=>!g.value||h.value?null:{x1:g.value.start[0],y1:g.value.start[1],x2:g.value.end[0],y2:g.value.end[1]});function k(b){return[-b[0],-b[1]]}return(b,S)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-arc-arrow"},[(f.openBlock(),f.createElementBlock("svg",wB,[h.value&&y.value?(f.openBlock(),f.createElementBlock("path",{key:0,d:y.value,stroke:l.value,fill:"none","stroke-width":u.value,"stroke-linecap":"round"},null,8,kB)):w.value?(f.openBlock(),f.createElementBlock("line",{key:1,x1:w.value.x1,y1:w.value.y1,x2:w.value.x2,y2:w.value.y2,stroke:l.value,fill:"none","stroke-width":u.value,"stroke-linecap":"round"},null,8,vB)):f.createCommentVNode("",!0),g.value?(f.openBlock(),f.createElementBlock(f.Fragment,{key:2},[g.value.startHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:0,position:g.value.start,direction:g.value.startDir,thickness:u.value,"arrow-thickness":c.value,color:l.value,kind:g.value.startHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):f.createCommentVNode("",!0),g.value.endHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:1,position:g.value.end,direction:g.value.endDir,thickness:u.value,"arrow-thickness":c.value,color:l.value,kind:g.value.endHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):f.createCommentVNode("",!0),d.value?(f.openBlock(),f.createElementBlock(f.Fragment,{key:2},[h.value&&y.value?(f.openBlock(),f.createElementBlock("path",{key:0,d:y.value,class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,bB)):w.value?(f.openBlock(),f.createElementBlock("line",{key:1,x1:w.value.x1,y1:w.value.y1,x2:w.value.x2,y2:w.value.y2,class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,SB)):f.createCommentVNode("",!0),g.value.startHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:2,position:g.value.start,direction:g.value.startDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":c.value,color:"var(--wov-highlighted-block-outline-color)",kind:g.value.startHead},null,8,["position","direction","arrow-thickness","kind"])):f.createCommentVNode("",!0),g.value.endHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:3,position:g.value.end,direction:g.value.endDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":c.value,color:"var(--wov-highlighted-block-outline-color)",kind:g.value.endHead},null,8,["position","direction","arrow-thickness","kind"])):f.createCommentVNode("",!0)],64)):f.createCommentVNode("",!0)],64)):f.createCommentVNode("",!0)]))],512))}}),Bo=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},ry=Bo(EB,[["__scopeId","data-v-bcf5b4f3"]]),CB={},xB={class:"wov-arrow-handle"};function TB(t,e){return f.openBlock(),f.createElementBlock("div",xB,[...e[0]||(e[0]=[f.createElementVNode("div",{class:"wov-arrow-handle-inner"},null,-1)])])}const oy=Bo(CB,[["render",TB]]),MB={},_B={class:"wov-arrow-terminal"};function AB(t,e){return f.openBlock(),f.createElementBlock("div",_B,[...e[0]||(e[0]=[f.createElementVNode("div",{class:"wov-arrow-terminal-ring"},[f.createElementVNode("div",{class:"wov-arrow-terminal-fill"})],-1)])])}const sy=Bo(MB,[["render",AB]]),IB={class:"arrow-svg",preserveAspectRatio:"none"},BB=["x1","y1","x2","y2"],PB=["x1","y1","x2","y2","stroke","stroke-width"],NB=["x1","y1","x2","y2"],iy=Bo(f.defineComponent({__name:"ElbowArrow",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=f.ref(null),r=f.ref(0),o=f.ref(0),s=pt(e.entityId,gn),i=pt(e.entityId,Se),a=f.computed(()=>e.hovered||e.selected);let l=null;f.onMounted(()=>{n.value&&(l=new ResizeObserver(()=>{n.value&&(r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),l.observe(n.value),r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),f.onUnmounted(()=>{l==null||l.disconnect()});const c=f.computed(()=>{if(!s.value)return"#000000";const g=s.value.red.toString(16).padStart(2,"0"),y=s.value.green.toString(16).padStart(2,"0"),w=s.value.blue.toString(16).padStart(2,"0");return`#${g}${y}${w}`}),u=f.computed(()=>{var g;return((g=i.value)==null?void 0:g.thickness)??2}),d=f.computed(()=>`${u.value}px`),h=f.computed(()=>{if(!i.value)return[];const g=i.value,y=r.value,w=o.value,k=[];for(let b=0;b<g.pointCount;b++){const S=g.points[b*2]*y,v=g.points[b*2+1]*w;k.push([S,v])}return k}),p=f.computed(()=>{const g=h.value;if(g.length<2)return[];const y=[];for(let w=0;w<g.length-1;w++)y.push({start:g[w],end:g[w+1]});return y}),m=f.computed(()=>{var P,$,V,U;if(!i.value||h.value.length<2)return null;const g=i.value,y=[...h.value.map(M=>[...M])],w=g.startArrowHead,k=g.endArrowHead,b=[y[1][0]-y[0][0],y[1][1]-y[0][1]],S=[y[y.length-1][0]-y[y.length-2][0],y[y.length-1][1]-y[y.length-2][1]];let v=g.trimStart;if((P=e.connector)!=null&&P.startBlock&&w!=="none"){const M=Math.hypot(b[0],b[1]),L=(($=Is(w))==null?void 0:$.gap)??0,q=M>0?L/M:0;v+=q}let x=g.trimEnd;if((V=e.connector)!=null&&V.endBlock&&k!=="none"){const M=Math.hypot(S[0],S[1]),L=((U=Is(k))==null?void 0:U.gap)??0,q=M>0?L/M:0;x+=q}y[0]=[y[0][0]+(y[1][0]-y[0][0])*v,y[0][1]+(y[1][1]-y[0][1])*v];const T=y.length-1;y[T]=[y[T-1][0]+(y[T][0]-y[T-1][0])*(1-x),y[T-1][1]+(y[T][1]-y[T-1][1])*(1-x)];const A=[];for(let M=0;M<y.length-1;M++)A.push({start:y[M],end:y[M+1]});return z.scale(b,-1),{points:y,lines:A,startPos:y[0],endPos:y[y.length-1],startDir:b,endDir:S,startHead:w,endHead:k}});return(g,y)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-elbow-arrow"},[(f.openBlock(),f.createElementBlock("svg",IB,[a.value&&p.value.length>0?(f.openBlock(!0),f.createElementBlock(f.Fragment,{key:0},f.renderList(p.value,(w,k)=>(f.openBlock(),f.createElementBlock("line",{key:"bg-"+k,x1:w.start[0],y1:w.start[1],x2:w.end[0],y2:w.end[1],class:"highlight-bg",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))","stroke-dasharray":"calc(12px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,BB))),128)):f.createCommentVNode("",!0),m.value?(f.openBlock(),f.createElementBlock(f.Fragment,{key:1},[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(m.value.lines,(w,k)=>(f.openBlock(),f.createElementBlock("line",{key:k,x1:w.start[0],y1:w.start[1],x2:w.end[0],y2:w.end[1],stroke:c.value,fill:"none","stroke-width":d.value,"stroke-linecap":"round"},null,8,PB))),128)),m.value.startHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:0,position:m.value.startPos,direction:m.value.startDir,thickness:d.value,"arrow-thickness":u.value,color:c.value,kind:m.value.startHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):f.createCommentVNode("",!0),m.value.endHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:1,position:m.value.endPos,direction:m.value.endDir,thickness:d.value,"arrow-thickness":u.value,color:c.value,kind:m.value.endHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):f.createCommentVNode("",!0),a.value?(f.openBlock(),f.createElementBlock(f.Fragment,{key:2},[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(m.value.lines,(w,k)=>(f.openBlock(),f.createElementBlock("line",{key:"hl-"+k,x1:w.start[0],y1:w.start[1],x2:w.end[0],y2:w.end[1],class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,NB))),128)),m.value.startHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:0,position:m.value.startPos,direction:m.value.startDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":u.value,color:"var(--wov-highlighted-block-outline-color)",kind:m.value.startHead},null,8,["position","direction","arrow-thickness","kind"])):f.createCommentVNode("",!0),m.value.endHead!=="none"?(f.openBlock(),f.createBlock(Sr,{key:1,position:m.value.endPos,direction:m.value.endDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":u.value,color:"var(--wov-highlighted-block-outline-color)",kind:m.value.endHead},null,8,["position","direction","arrow-thickness","kind"])):f.createCommentVNode("",!0)],64)):f.createCommentVNode("",!0)],64)):f.createCommentVNode("",!0)]))],512))}}),[["__scopeId","data-v-b2719db1"]]);var DB=Object.defineProperty,td=(t,e)=>{for(var n in e)DB(t,n,{get:e[n],enumerable:!0})},ay=le("start-eraser-stroke"),ly=le("add-eraser-stroke-point"),cy=le("complete-eraser-stroke"),uy=le("cancel-eraser-stroke"),dy={};td(dy,{Erased:()=>Po,EraserStroke:()=>Si});var Po=He({name:"erased"},{eraserStrokeId:E.ref()}),Bs=8,OB="eraser",tr=20,Si=He({name:"eraserStroke"},{points:E.buffer(E.float32()).size(tr*2),pointCount:E.uint32().default(0),firstPointIndex:E.uint32().default(0),radius:E.float32().default(8)}),fy={};td(fy,{EraserStateSingleton:()=>nd});var No={Idle:"idle",Erasing:"erasing"},nd=Gr("eraserState",{state:E.string().max(16).default(No.Idle),activeStroke:E.ref(),lastWorldPosition:E.tuple(E.float64(),2).default([0,0])}),hy={};td(hy,{captureEraserSystem:()=>zB,updateEraserSystem:()=>FB});var RB=yr({guards:{},actions:{startStroke:({event:t})=>{ay.spawn(t.ctx,{worldPosition:t.worldPosition})},addPoint:Oe({lastWorldPosition:({event:t,context:e})=>e.activeStroke?(ly.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition}),[t.worldPosition[0],t.worldPosition[1]]):e.lastWorldPosition}),completeStroke:({event:t,context:e})=>{e.activeStroke&&cy.spawn(t.ctx,{strokeId:e.activeStroke})},cancelStroke:({event:t,context:e})=>{e.activeStroke&&uy.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:Oe({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"eraser",initial:No.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[No.Idle]:{entry:["resetContext"],on:{pointerDown:{target:No.Erasing,actions:["startStroke"]}}},[No.Erasing]:{on:{pointerMove:{actions:["addPoint"]},frame:{actions:["addPoint"]},pointerUp:{target:No.Idle,actions:["completeStroke"]},cancel:{target:No.Idle,actions:["cancelStroke"]}}}}}),zB=pe({phase:"capture",priority:100},t=>{const e=Qe.getButtons(t,"eraser"),n=br(t,e,{includeFrameEvent:!0});n.length!==0&&nd.run(t,RB,n)}),$B=ne(t=>t.with(_,de,Ae)),LB=ne(t=>t.with(Po)),FB=pe({phase:"update"},t=>{ie(t,ay,(e,{worldPosition:n})=>{VB(e,n)}),ie(t,ly,(e,{strokeId:n,worldPosition:r})=>{WB(e,n,r)}),ie(t,cy,(e,{strokeId:n})=>{jB(e,n)}),ie(t,uy,(e,{strokeId:n})=>{ZB(e,n)})});function VB(t,e){const n=vt(t);G(t,n,_,{tag:"eraser",rank:In.genNext(t),position:[e[0]-Bs,e[1]-Bs],size:[Bs*2,Bs*2]}),G(t,n,Si,{points:e,pointCount:1,firstPointIndex:0,radius:Bs});const r=nd.write(t);r.activeStroke=n,r.lastWorldPosition=e}function WB(t,e,n){const r=Si.write(t,e),o=r.pointCount,s=(o-1)%tr*2,i=r.points[s],a=r.points[s+1],l=o%tr*2;if(r.points[l]=n[0],r.points[l+1]=n[1],r.pointCount++,r.pointCount>tr&&(r.firstPointIndex=(r.pointCount-tr)%tr),!Ae.containsPoint(t,e,n)){Ae.expandByPoint(t,e,n);const{value:g}=Ae.read(t,e),y=_.write(t,e);z.set(y.position,Q.left(g),Q.top(g)),z.set(y.size,Q.width(g),Q.height(g))}const c=n[0]-i,u=n[1]-a;if(c*c+u*u<1)return;const h=rt.create(i,a,n[0],n[1],Bs),p=UB(t,$B.current(t)),m=TA(t,h,p);for(const g of m)HB(t,g,e)}function*UB(t,e){for(const n of e)O(t,n,Po)||(yield n)}function HB(t,e,n){G(t,e,Po,{eraserStrokeId:n}),G(t,e,Ge,{value:80})}function jB(t,e){const n=Jn(t,e,Po,"eraserStrokeId");for(const r of n)Ye(t,r);Ye(t,e)}function ZB(t,e){const n=[];for(const r of LB.current(t))Po.read(t,r).eraserStrokeId===e&&n.push(r);for(const r of n)nn(t,r,Po),nn(t,r,Ge);Ye(t,e)}var KB=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e),YB=qt({tailRadius:Xe().positive().optional(),tailLength:Xe().int().min(1).max(tr).optional()});function qB(t={}){const e=YB.parse(t);return{name:OB,components:Object.values(dy).filter(n=>n instanceof Kt),singletons:Object.values(fy).filter(n=>n instanceof bt),blockDefs:[{tag:"eraser-stroke",stratum:"overlay",canRotate:!1,canScale:!1,components:[Si]}],systems:KB(hy),resources:{tailRadius:e.tailRadius??8,tailLength:e.tailLength??tr}}}function py(t,e,n,r=o=>o){return t*r(.5-e*(.5-n))}function JB(t){return[-t[0],-t[1]]}function zn(t,e){return[t[0]+e[0],t[1]+e[1]]}function bn(t,e){return[t[0]-e[0],t[1]-e[1]]}function $n(t,e){return[t[0]*e,t[1]*e]}function XB(t,e){return[t[0]/e,t[1]/e]}function Ei(t){return[t[1],-t[0]]}function my(t,e){return t[0]*e[0]+t[1]*e[1]}function GB(t,e){return t[0]===e[0]&&t[1]===e[1]}function QB(t){return Math.hypot(t[0],t[1])}function eP(t){return t[0]*t[0]+t[1]*t[1]}function gy(t,e){return eP(bn(t,e))}function yy(t){return XB(t,QB(t))}function tP(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function Ci(t,e,n){let r=Math.sin(n),o=Math.cos(n),s=t[0]-e[0],i=t[1]-e[1],a=s*o-i*r,l=s*r+i*o;return[a+e[0],l+e[1]]}function rd(t,e,n){return zn(t,$n(bn(e,t),n))}function wy(t,e,n){return zn(t,$n(e,n))}var{min:Ps,PI:nP}=Math,ky=.275,xi=nP+1e-4;function rP(t,e={}){let{size:n=16,smoothing:r=.5,thinning:o=.5,simulatePressure:s=!0,easing:i=Z=>Z,start:a={},end:l={},last:c=!1}=e,{cap:u=!0,easing:d=Z=>Z*(2-Z)}=a,{cap:h=!0,easing:p=Z=>--Z*Z*Z+1}=l;if(t.length===0||n<=0)return[];let m=t[t.length-1].runningLength,g=a.taper===!1?0:a.taper===!0?Math.max(n,m):a.taper,y=l.taper===!1?0:l.taper===!0?Math.max(n,m):l.taper,w=Math.pow(n*r,2),k=[],b=[],S=t.slice(0,10).reduce((Z,H)=>{let J=H.pressure;if(s){let ce=Ps(1,H.distance/n),Ke=Ps(1,1-ce);J=Ps(1,Z+(Ke-Z)*(ce*ky))}return(Z+J)/2},t[0].pressure),v=py(n,o,t[t.length-1].pressure,i),x,T=t[0].vector,A=t[0].point,P=A,$=A,V=P,U=!1;for(let Z=0;Z<t.length;Z++){let{pressure:H}=t[Z],{point:J,vector:ce,distance:Ke,runningLength:Be}=t[Z];if(Z<t.length-1&&m-Be<3)continue;if(o){if(s){let Zn=Ps(1,Ke/n),B=Ps(1,1-Zn);H=Ps(1,S+(B-S)*(Zn*ky))}v=py(n,o,H,i)}else v=n/2;x===void 0&&(x=v);let tt=Be<g?d(Be/g):1,ko=m-Be<y?p((m-Be)/y):1;v=Math.max(.01,v*Math.min(tt,ko));let yc=(Z<t.length-1?t[Z+1]:t[Z]).vector,na=Z<t.length-1?my(ce,yc):1,Kf=my(ce,T)<0&&!U,ra=na!==null&&na<0;if(Kf||ra){let Zn=$n(Ei(T),v);for(let B=1/13,ae=0;ae<=1;ae+=B)$=Ci(bn(J,Zn),J,xi*ae),k.push($),V=Ci(zn(J,Zn),J,xi*-ae),b.push(V);A=$,P=V,ra&&(U=!0);continue}if(U=!1,Z===t.length-1){let Zn=$n(Ei(ce),v);k.push(bn(J,Zn)),b.push(zn(J,Zn));continue}let wc=$n(Ei(rd(yc,ce,na)),v);$=bn(J,wc),(Z<=1||gy(A,$)>w)&&(k.push($),A=$),V=zn(J,wc),(Z<=1||gy(P,V)>w)&&(b.push(V),P=V),S=H,T=ce}let M=t[0].point.slice(0,2),L=t.length>1?t[t.length-1].point.slice(0,2):zn(t[0].point,[1,1]),q=[],se=[];if(t.length===1){if(!(g||y)||c){let Z=wy(M,yy(Ei(bn(M,L))),-(x||v)),H=[];for(let J=1/13,ce=J;ce<=1;ce+=J)H.push(Ci(Z,M,xi*2*ce));return H}}else{if(!(g||y&&t.length===1))if(u)for(let H=1/13,J=H;J<=1;J+=H){let ce=Ci(b[0],M,xi*J);q.push(ce)}else{let H=bn(k[0],b[0]),J=$n(H,.5),ce=$n(H,.51);q.push(bn(M,J),bn(M,ce),zn(M,ce),zn(M,J))}let Z=Ei(JB(t[t.length-1].vector));if(y||g&&t.length===1)se.push(L);else if(h){let H=wy(L,Z,v);for(let J=1/29,ce=J;ce<1;ce+=J)se.push(Ci(H,L,xi*3*ce))}else se.push(zn(L,$n(Z,v)),zn(L,$n(Z,v*.99)),bn(L,$n(Z,v*.99)),bn(L,$n(Z,v)))}return k.concat(se,b.reverse(),q)}function oP(t,e={}){var n;let{streamline:r=.5,size:o=16,last:s=!1}=e;if(t.length===0)return[];let i=.15+(1-r)*.85,a=Array.isArray(t[0])?t:t.map(({x:p,y:m,pressure:g=.5})=>[p,m,g]);if(a.length===2){let p=a[1];a=a.slice(0,-1);for(let m=1;m<5;m++)a.push(rd(a[0],p,m/4))}a.length===1&&(a=[...a,[...zn(a[0],[1,1]),...a[0].slice(2)]]);let l=[{point:[a[0][0],a[0][1]],pressure:a[0][2]>=0?a[0][2]:.25,vector:[1,1],distance:0,runningLength:0}],c=!1,u=0,d=l[0],h=a.length-1;for(let p=1;p<a.length;p++){let m=s&&p===h?a[p].slice(0,2):rd(d.point,a[p],i);if(GB(d.point,m))continue;let g=tP(m,d.point);if(u+=g,p<h&&!c){if(u<o)continue;c=!0}d={point:m,pressure:a[p][2]>=0?a[p][2]:.5,vector:yy(bn(d.point,m)),distance:g,runningLength:u},l.push(d)}return l[0].vector=((n=l[1])==null?void 0:n.vector)||[0,0],l}function od(t,e={}){return rP(oP(t,e),e)}const sP={class:"wov-eraser-stroke"},iP={preserveAspectRatio:"none"},aP=["d"],lP="#88888833",vy=f.defineComponent({__name:"Eraser",props:{entityId:{}},setup(t){const e=t,n=pt(e.entityId,Si),r=pt(e.entityId,_),o=f.shallowRef("");function s(a,l){return(a+l)/2}function i(a,l,c,u,d,h){if(a<=4)return"";const p=[],m=Math.min(a,tr);for(let S=0;S<m;S++){const v=(l+S)%tr*2;p.push([c[v]-d,c[v+1]-h])}const g=od(p,{size:u,start:{taper:66,cap:!0}});if(g.length<3)return"";let y=g[0],w=g[1];const k=g[2];let b=`M${y[0].toFixed(2)},${y[1].toFixed(2)} Q${w[0].toFixed(2)},${w[1].toFixed(2)} ${s(w[0],k[0]).toFixed(2)},${s(w[1],k[1]).toFixed(2)} T`;for(let S=2;S<g.length-1;S++)y=g[S],w=g[S+1],b+=`${s(y[0],w[0]).toFixed(2)},${s(y[1],w[1]).toFixed(2)} `;return b+=`${w[0].toFixed(2)},${w[1].toFixed(2)} `,b+="Z",b}return f.watch([n,r],([a,l])=>{if(!a||!l){o.value="";return}const c=a.radius??8,[u,d]=l.position;o.value=i(a.pointCount,a.firstPointIndex,a.points,2*c,u,d)},{immediate:!0}),(a,l)=>(f.openBlock(),f.createElementBlock("div",sP,[(f.openBlock(),f.createElementBlock("svg",iP,[f.createElementVNode("path",{d:o.value,fill:lP},null,8,aP)]))]))}}),cP={class:"wov-image-block"},uP={key:0,class:"wov-image-placeholder"},dP={key:1,class:"wov-image-placeholder wov-image-error"},fP=["src","alt"],hP={key:3,class:"wov-image-upload-overlay"},pP={class:"wov-image-upload-status"},by=f.defineComponent({__name:"ImageBlock",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=f.inject(Rn);if(!n)throw new Error("ImageBlock must be used within a WovenCanvas component");const r=n,o=pt(e.entityId,_o),s=pt(e.entityId,oi),i=f.ref(null),a=f.ref(!0),l=f.ref(!1);let c=!0;f.onUnmounted(()=>{c=!1});async function u(){const p=r.getAssetManager();if(!p){a.value=!1,l.value=!0;return}const m=o.value;if(!m){a.value=!1;return}try{a.value=!0,l.value=!1;const g=await p.getDisplayUrl(m.identifier);if(!c)return;g?(i.value=g,a.value=!1):m.uploadState===er.Failed&&(l.value=!0,a.value=!1)}catch(g){if(!c)return;console.error("Failed to get display URL:",g),l.value=!0,a.value=!1}}f.watch(()=>o.value,()=>{u()},{immediate:!0}),f.onMounted(()=>{u()});const d=f.computed(()=>{const p=o.value;if(!p)return null;switch(p.uploadState){case er.Pending:return"Loading...";case er.Uploading:return"Loading...";case er.Failed:return"Failed";default:return null}}),h=f.computed(()=>({width:"100%",height:"100%",objectFit:"fill"}));return(p,m)=>{var g;return f.openBlock(),f.createElementBlock("div",cP,[a.value&&!i.value?(f.openBlock(),f.createElementBlock("div",uP,[...m[0]||(m[0]=[f.createElementVNode("span",null,"Loading...",-1)])])):l.value?(f.openBlock(),f.createElementBlock("div",dP,[...m[1]||(m[1]=[f.createElementVNode("span",null,"Failed to load image",-1)])])):i.value?(f.openBlock(),f.createElementBlock("img",{key:2,src:i.value,alt:((g=f.unref(s))==null?void 0:g.alt)||"",style:f.normalizeStyle(h.value),draggable:"false"},null,12,fP)):f.createCommentVNode("",!0),d.value?(f.openBlock(),f.createElementBlock("div",hP,[f.createElementVNode("span",pP,f.toDisplayString(d.value),1)])):f.createCommentVNode("",!0)])}}});function mP(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Sy={exports:{}};(function(t){(function(){function e(a,l){var c=a.x-l.x,u=a.y-l.y;return c*c+u*u}function n(a,l,c){var u=l.x,d=l.y,h=c.x-u,p=c.y-d;if(h!==0||p!==0){var m=((a.x-u)*h+(a.y-d)*p)/(h*h+p*p);m>1?(u=c.x,d=c.y):m>0&&(u+=h*m,d+=p*m)}return h=a.x-u,p=a.y-d,h*h+p*p}function r(a,l){for(var c=a[0],u=[c],d,h=1,p=a.length;h<p;h++)d=a[h],e(d,c)>l&&(u.push(d),c=d);return c!==d&&u.push(d),u}function o(a,l,c,u,d){for(var h=u,p,m=l+1;m<c;m++){var g=n(a[m],a[l],a[c]);g>h&&(p=m,h=g)}h>u&&(p-l>1&&o(a,l,p,u,d),d.push(a[p]),c-p>1&&o(a,p,c,u,d))}function s(a,l){var c=a.length-1,u=[a[0]];return o(a,0,c,l,u),u.push(a[c]),u}function i(a,l,c){if(a.length<=2)return a;var u=l!==void 0?l*l:1;return a=c?a:r(a,u),a=s(a,u),a}t.exports=i,t.exports.default=i})()})(Sy);var gP=Sy.exports;const Ey=mP(gP);var yP=Object.defineProperty,sd=(t,e)=>{for(var n in e)yP(t,n,{get:e[n],enumerable:!0})},Cy=le("start-pen-stroke"),xy=le("add-pen-stroke-point"),Ty=le("complete-pen-stroke"),My=le("remove-pen-stroke"),_y={};sd(_y,{POINTS_CAPACITY:()=>ul,PenStroke:()=>Ln});var ul=256,wP={points:E.buffer(E.float32()).size(ul*2),pressures:E.buffer(E.float32()).size(ul),pointCount:E.uint32().default(0),thickness:E.float32().default(8),originalLeft:E.float32().default(0),originalTop:E.float32().default(0),originalWidth:E.float32().default(0),originalHeight:E.float32().default(0),isComplete:E.boolean().default(!1),hasPressure:E.boolean().default(!1)},kP=class extends Kt{constructor(){super({name:"penStroke",sync:"document"},wP)}snapshot(t,e){const n=super.snapshot(t,e),r=n.pointCount;return n.points=n.points.slice(0,r*2),n.pressures=n.hasPressure?n.pressures.slice(0,r):new Float32Array(0),n}},Ln=new kP,vP=8,bP="pen",Ay={};sd(Ay,{PenStateSingleton:()=>id});var Do={Idle:"idle",Drawing:"drawing"},id=Gr("penState",{state:E.string().max(16).default(Do.Idle),activeStroke:E.ref(),lastWorldPosition:E.tuple(E.float64(),2).default([0,0])}),Iy={};sd(Iy,{capturePenSystem:()=>EP,updatePenSystem:()=>xP});var SP=yr({guards:{},actions:{startStroke:({event:t})=>{const e=t.pointerType===qr.Pen?t.pressure:null;Cy.spawn(t.ctx,{worldPosition:t.worldPosition,pressure:e,thickness:vP})},addPoint:Oe({lastWorldPosition:({event:t,context:e})=>{if(!e.activeStroke)return e.lastWorldPosition;const n=t.pointerType===qr.Pen?t.pressure:null;return xy.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition,pressure:n}),t.worldPosition}}),completeStroke:({event:t,context:e})=>{e.activeStroke&&Ty.spawn(t.ctx,{strokeId:e.activeStroke})},removeStroke:({event:t,context:e})=>{e.activeStroke&&My.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:Oe({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"pen",initial:Do.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[Do.Idle]:{entry:["resetContext"],on:{pointerDown:{target:Do.Drawing,actions:["startStroke"]}}},[Do.Drawing]:{on:{pointerMove:{actions:["addPoint"]},pointerUp:{target:Do.Idle,actions:["completeStroke"]},cancel:{target:Do.Idle,actions:["removeStroke"]}}}}}),EP=pe({phase:"capture",priority:100},t=>{const e=Qe.getButtons(t,"pen"),n=br(t,e);n.length!==0&&id.run(t,SP,n)}),CP=ne(t=>t.tracking(Ln)),xP=pe({phase:"update"},t=>{ie(t,Cy,(e,{worldPosition:n,pressure:r,thickness:o})=>{TP(e,n,r,o)}),ie(t,xy,(e,{strokeId:n,worldPosition:r,pressure:o})=>{MP(e,n,r,o)}),ie(t,Ty,(e,{strokeId:n})=>{_P(e,n)}),ie(t,My,(e,{strokeId:n})=>{AP(e,n)});for(const e of CP.addedOrChanged(t))Ln.read(t,e).isComplete&&By(t,e)});function TP(t,e,n,r){const o=r/2,s=vt(t);G(t,s,de,{id:crypto.randomUUID()}),G(t,s,_,{tag:"pen-stroke",rank:In.genNext(t),position:[e[0]-o,e[1]-o],size:[o*2,o*2]}),G(t,s,gn,{});const{sessionId:i}=Le(t);G(t,s,xt,{sessionId:i});const a=n!==null;G(t,s,Ln,{points:e,pressures:[a?n:.5],pointCount:1,thickness:r,originalLeft:e[0]-o,originalTop:e[1]-o,originalWidth:o*2,originalHeight:o*2,isComplete:!1,hasPressure:a});const c=id.write(t);c.activeStroke=s,c.lastWorldPosition=e}function MP(t,e,n,r){const o=Ln.write(t,e),s=o.pointCount;if(!(s>=ul)&&(o.points[s*2]=n[0],o.points[s*2+1]=n[1],r!==null?o.pressures[s]=r:o.pressures[s]=.5,o.pointCount++,!Ae.containsPoint(t,e,n))){Ae.expandByPoint(t,e,n);const{value:i}=Ae.read(t,e),a=_.write(t,e);z.set(a.position,Q.left(i),Q.top(i)),z.set(a.size,Q.width(i),Q.height(i)),o.originalLeft=a.position[0],o.originalTop=a.position[1],o.originalWidth=a.size[0],o.originalHeight=a.size[1]}}function _P(t,e){const n=Ln.write(t,e);n.isComplete=!0,nn(t,e,xt),By(t,e)}function AP(t,e){Ye(t,e)}function By(t,e){const n=Ln.read(t,e),r=[];for(let u=0;u<n.pointCount;u++)r.push({x:n.points[u*2],y:n.points[u*2+1]});let o=n.thickness,s=Ey(r,o,!1);for(;s.length-1>Ss;)o*=2,s=Ey(r,o,!1);if(s.length===1){const u=s[0];s.push({x:u.x,y:u.y})}O(t,e,ye)?ye.clear(t,e):G(t,e,ye,{});const{originalLeft:i,originalTop:a,originalWidth:l,originalHeight:c}=n;for(let u=0;u<s.length-1;u++){const d=s[u],h=s[u+1],p=[(d.x-i)/l,(d.y-a)/c],m=[(h.x-i)/l,(h.y-a)/c];ye.addCapsuleUv(t,e,p,m,n.thickness)}}var IP=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function BP(){return{name:bP,components:Object.values(_y).filter(t=>t instanceof Kt),singletons:Object.values(Ay).filter(t=>t instanceof bt),blockDefs:[{tag:"pen-stroke",resizeMode:"free",components:[Ln,gn],connectors:{enabled:!1}}],systems:IP(Iy),resources:{}}}const PP=["data-complete"],NP={preserveAspectRatio:"none"},DP=["d","fill"],OP={key:0,class:"highlight",preserveAspectRatio:"none"},RP=["d"],Py=Bo(f.defineComponent({__name:"PenStroke",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=pt(e.entityId,Ln),r=pt(e.entityId,_),o=pt(e.entityId,gn),s=f.shallowRef(""),i=f.shallowRef("");function a(d,h){return(d+h)/2}function l(d,h,p){if(h<=4||d.length<3){const k=p/2;return`M ${k},0 a ${k},${k} 0 1 0 0.0001 0`}let m=d[0],g=d[1];const y=d[2];let w=`M${m[0].toFixed(2)},${m[1].toFixed(2)} Q${g[0].toFixed(2)},${g[1].toFixed(2)} ${a(g[0],y[0]).toFixed(2)},${a(g[1],y[1]).toFixed(2)} T`;for(let k=2;k<d.length-1;k++)m=d[k],g=d[k+1],w+=`${a(m[0],g[0]).toFixed(2)},${a(m[1],g[1]).toFixed(2)} `;return w+=`${g[0].toFixed(2)},${g[1].toFixed(2)} `,w+="Z",w}f.watch([n,r],([d,h])=>{if(!d||!h){s.value="",i.value="";return}if(!d.originalWidth||!d.originalHeight){s.value="",i.value="";return}const p=h.size[0]/d.originalWidth,m=h.size[1]/d.originalHeight,g=[];for(let w=0;w<d.pointCount;w++){const k=d.points[w*2],b=d.points[w*2+1],S=(k-d.originalLeft)*p,v=(b-d.originalTop)*m;d.hasPressure?g.push([S,v,d.pressures[w]]):g.push([S,v])}const y=od(g,{last:d.isComplete,size:d.thickness,simulatePressure:!d.hasPressure});if(s.value=l(y,d.pointCount,d.thickness),d.isComplete){const w=g.length===1?d.thickness:1,k=od(g,{last:!0,size:w,simulatePressure:!d.hasPressure});i.value=l(k,d.pointCount,w)}},{immediate:!0});const c=f.computed(()=>o.value?`rgb(${o.value.red}, ${o.value.green}, ${o.value.blue})`:"#000000"),u=f.computed(()=>e.selected||e.hovered);return(d,h)=>{var p;return f.openBlock(),f.createElementBlock("div",{class:"wov-pen-stroke","data-complete":((p=f.unref(n))==null?void 0:p.isComplete)||void 0},[(f.openBlock(),f.createElementBlock("svg",NP,[f.createElementVNode("path",{d:s.value,fill:c.value},null,8,DP)])),u.value?(f.openBlock(),f.createElementBlock("svg",OP,[f.createElementVNode("path",{d:i.value,stroke:"var(--wov-highlighted-block-outline-color)",style:{"stroke-width":"calc(1px / var(--wov-zoom))"},fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},null,8,RP)])):f.createCommentVNode("",!0)],8,PP)}}}),[["__scopeId","data-v-9b41c649"]]);function Tt(){const t=f.inject(Rn);if(!t)throw new Error("useEditorContext must be used within a WovenCanvas component");return{getEditor:()=>t.getEditor(),nextEditorTick(e){return new Promise(n=>{const r=t.getEditor();r&&r.nextTick(o=>{e==null||e(o),n(o)})})}}}const Ti={rectangle:"M0,0 L100,0 L100,100 L0,100 Z",ellipse:"M50,0 A50,50 0 1,1 50,100 A50,50 0 1,1 50,0",triangle:"M50,0 L100,100 L0,100 Z",diamond:"M50,0 L100,50 L50,100 L0,50 Z",pentagon:"M50,0 L100,38.2 L80.9,100 L19.1,100 L0,38.2 Z",hexagon:"M50,0 L100,25 L100,75 L50,100 L0,75 L0,25 Z",star:"M50,0 L61.8,38.2 L100,38.2 L69.1,61.8 L80.9,100 L50,76.4 L19.1,100 L30.9,61.8 L0,38.2 L38.2,38.2 Z",heart:"M50,16 C44,7 37,0 26,0 11,0 0,12 0,28 0,60 16,65 50,100 84,65 100,60 100,28 100,12 89,0 74,0 63,0 56,7 50,16 Z",arrow:"M0,35 L60,35 L60,0 L100,50 L60,100 L60,65 L0,65 Z"};function Mt(t){this.content=t}Mt.prototype={constructor:Mt,find:function(t){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return e==-1?void 0:this.content[e+1]},update:function(t,e,n){var r=n&&n!=t?this.remove(n):this,o=r.find(t),s=r.content.slice();return o==-1?s.push(n||t,e):(s[o+1]=e,n&&(s[o]=n)),new Mt(s)},remove:function(t){var e=this.find(t);if(e==-1)return this;var n=this.content.slice();return n.splice(e,2),new Mt(n)},addToStart:function(t,e){return new Mt([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new Mt(n)},addBefore:function(t,e,n){var r=this.remove(e),o=r.content.slice(),s=r.find(t);return o.splice(s==-1?o.length:s,0,e,n),new Mt(o)},forEach:function(t){for(var e=0;e<this.content.length;e+=2)t(this.content[e],this.content[e+1])},prepend:function(t){return t=Mt.from(t),t.size?new Mt(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=Mt.from(t),t.size?new Mt(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=Mt.from(t);for(var n=0;n<t.content.length;n+=2)e=e.remove(t.content[n]);return e},toObject:function(){var t={};return this.forEach(function(e,n){t[e]=n}),t},get size(){return this.content.length>>1}},Mt.from=function(t){if(t instanceof Mt)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Mt(e)};function Ny(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let o=t.child(r),s=e.child(r);if(o==s){n+=o.nodeSize;continue}if(!o.sameMarkup(s))return n;if(o.isText&&o.text!=s.text){for(let i=0;o.text[i]==s.text[i];i++)n++;return n}if(o.content.size||s.content.size){let i=Ny(o.content,s.content,n+1);if(i!=null)return i}n+=o.nodeSize}}function Dy(t,e,n,r){for(let o=t.childCount,s=e.childCount;;){if(o==0||s==0)return o==s?null:{a:n,b:r};let i=t.child(--o),a=e.child(--s),l=i.nodeSize;if(i==a){n-=l,r-=l;continue}if(!i.sameMarkup(a))return{a:n,b:r};if(i.isText&&i.text!=a.text){let c=0,u=Math.min(i.text.length,a.text.length);for(;c<u&&i.text[i.text.length-c-1]==a.text[a.text.length-c-1];)c++,n--,r--;return{a:n,b:r}}if(i.content.size||a.content.size){let c=Dy(i.content,a.content,n-1,r-1);if(c)return c}n-=l,r-=l}}class D{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let r=0;r<e.length;r++)this.size+=e[r].nodeSize}nodesBetween(e,n,r,o=0,s){for(let i=0,a=0;a<n;i++){let l=this.content[i],c=a+l.nodeSize;if(c>e&&r(l,o+a,s||null,i)!==!1&&l.content.size){let u=a+1;l.nodesBetween(Math.max(0,e-u),Math.min(l.content.size,n-u),r,o+u)}a=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,o){let s="",i=!0;return this.nodesBetween(e,n,(a,l)=>{let c=a.isText?a.text.slice(Math.max(e,l)-l,n-l):a.isLeaf?o?typeof o=="function"?o(a):o:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&c||a.isTextblock)&&r&&(i?i=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,o=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(o[o.length-1]=n.withText(n.text+r.text),s=1);s<e.content.length;s++)o.push(e.content[s]);return new D(o,this.size+e.size)}cut(e,n=this.size){if(e==0&&n==this.size)return this;let r=[],o=0;if(n>e)for(let s=0,i=0;i<n;s++){let a=this.content[s],l=i+a.nodeSize;l>e&&((i<e||l>n)&&(a.isText?a=a.cut(Math.max(0,e-i),Math.min(a.text.length,n-i)):a=a.cut(Math.max(0,e-i-1),Math.min(a.content.size,n-i-1))),r.push(a),o+=a.nodeSize),i=l}return new D(r,o)}cutByIndex(e,n){return e==n?D.empty:e==0&&n==this.content.length?this:new D(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let o=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return o[e]=n,new D(o,s)}addToStart(e){return new D([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new D(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;n<this.content.length;n++)if(!this.content[n].eq(e.content[n]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let n=this.content[e];if(!n)throw new RangeError("Index "+e+" out of range for "+this);return n}maybeChild(e){return this.content[e]||null}forEach(e){for(let n=0,r=0;n<this.content.length;n++){let o=this.content[n];e(o,r,n),r+=o.nodeSize}}findDiffStart(e,n=0){return Ny(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return Dy(this,e,n,r)}findIndex(e){if(e==0)return dl(0,e);if(e==this.size)return dl(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let o=this.child(n),s=r+o.nodeSize;if(s>=e)return s==e?dl(n+1,s):dl(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return D.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new D(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return D.empty;let n,r=0;for(let o=0;o<e.length;o++){let s=e[o];r+=s.nodeSize,o&&s.isText&&e[o-1].sameMarkup(s)?(n||(n=e.slice(0,o)),n[n.length-1]=s.withText(n[n.length-1].text+s.text)):n&&n.push(s)}return new D(n||e,r)}static from(e){if(!e)return D.empty;if(e instanceof D)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new D([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}D.empty=new D([],0);const ad={index:0,offset:0};function dl(t,e){return ad.index=t,ad.offset=e,ad}function fl(t,e){if(t===e)return!0;if(!(t&&typeof t=="object")||!(e&&typeof e=="object"))return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(!fl(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!fl(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let Ie=class Yf{constructor(e,n){this.type=e,this.attrs=n}addToSet(e){let n,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(this.eq(s))return e;if(this.type.excludes(s.type))n||(n=e.slice(0,o));else{if(s.type.excludes(this.type))return e;!r&&s.type.rank>this.type.rank&&(n||(n=e.slice(0,o)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return e.slice(0,n).concat(e.slice(n+1));return e}isInSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return!0;return!1}eq(e){return this==e||this.type==e.type&&fl(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Mark.fromJSON");let r=e.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);let o=r.create(n.attrs);return r.checkAttrs(o.attrs),o}static sameSet(e,n){if(e==n)return!0;if(e.length!=n.length)return!1;for(let r=0;r<e.length;r++)if(!e[r].eq(n[r]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return Yf.none;if(e instanceof Yf)return[e];let n=e.slice();return n.sort((r,o)=>r.type.rank-o.type.rank),n}};Ie.none=[];class hl extends Error{}class j{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Ry(this.content,e+this.openStart,n);return r&&new j(r,this.openStart,this.openEnd)}removeBetween(e,n){return new j(Oy(this.content,e+this.openStart,n+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,n){if(!n)return j.empty;let r=n.openStart||0,o=n.openEnd||0;if(typeof r!="number"||typeof o!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new j(D.fromJSON(e,n.content),r,o)}static maxOpen(e,n=!0){let r=0,o=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)o++;return new j(e,r,o)}}j.empty=new j(D.empty,0,0);function Oy(t,e,n){let{index:r,offset:o}=t.findIndex(e),s=t.maybeChild(r),{index:i,offset:a}=t.findIndex(n);if(o==e||s.isText){if(a!=n&&!t.child(i).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=i)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(Oy(s.content,e-o-1,n-o-1)))}function Ry(t,e,n,r){let{index:o,offset:s}=t.findIndex(e),i=t.maybeChild(o);if(s==e||i.isText)return r&&!r.canReplace(o,o,n)?null:t.cut(0,e).append(n).append(t.cut(e));let a=Ry(i.content,e-s-1,n,i);return a&&t.replaceChild(o,i.copy(a))}function zP(t,e,n){if(n.openStart>t.depth)throw new hl("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new hl("Inconsistent open depths");return zy(t,e,n,0)}function zy(t,e,n,r){let o=t.index(r),s=t.node(r);if(o==e.index(r)&&r<t.depth-n.openStart){let i=zy(t,e,n,r+1);return s.copy(s.content.replaceChild(o,i))}else if(n.content.size)if(!n.openStart&&!n.openEnd&&t.depth==r&&e.depth==r){let i=t.parent,a=i.content;return Ro(i,a.cut(0,t.parentOffset).append(n.content).append(a.cut(e.parentOffset)))}else{let{start:i,end:a}=$P(n,t);return Ro(s,Ly(t,i,a,e,r))}else return Ro(s,pl(t,e,r))}function $y(t,e){if(!e.type.compatibleContent(t.type))throw new hl("Cannot join "+e.type.name+" onto "+t.type.name)}function ld(t,e,n){let r=t.node(n);return $y(r,e.node(n)),r}function Oo(t,e){let n=e.length-1;n>=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function Mi(t,e,n,r){let o=(e||t).node(n),s=0,i=e?e.index(n):o.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Oo(t.nodeAfter,r),s++));for(let a=s;a<i;a++)Oo(o.child(a),r);e&&e.depth==n&&e.textOffset&&Oo(e.nodeBefore,r)}function Ro(t,e){return t.type.checkContent(e),t.copy(e)}function Ly(t,e,n,r,o){let s=t.depth>o&&ld(t,e,o+1),i=r.depth>o&&ld(n,r,o+1),a=[];return Mi(null,t,o,a),s&&i&&e.index(o)==n.index(o)?($y(s,i),Oo(Ro(s,Ly(t,e,n,r,o+1)),a)):(s&&Oo(Ro(s,pl(t,e,o+1)),a),Mi(e,n,o,a),i&&Oo(Ro(i,pl(n,r,o+1)),a)),Mi(r,null,o,a),new D(a)}function pl(t,e,n){let r=[];if(Mi(null,t,n,r),t.depth>n){let o=ld(t,e,n+1);Oo(Ro(o,pl(t,e,n+1)),r)}return Mi(e,null,n,r),new D(r)}function $P(t,e){let n=e.depth-t.openStart,o=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)o=e.node(s).copy(D.from(o));return{start:o.resolveNoCache(t.openStart+n),end:o.resolveNoCache(o.content.size-t.openEnd-n)}}class _i{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.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,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],o=e.child(n);return r?e.child(n).cut(r):o}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],o=n==0?0:this.path[n*3-1]+1;for(let s=0;s<e;s++)o+=r.child(s).nodeSize;return o}marks(){let e=this.parent,n=this.index();if(e.content.size==0)return Ie.none;if(this.textOffset)return e.child(n).marks;let r=e.maybeChild(n-1),o=e.maybeChild(n);if(!r){let a=r;r=o,o=a}let s=r.marks;for(var i=0;i<s.length;i++)s[i].type.spec.inclusive===!1&&(!o||!s[i].isInSet(o.marks))&&(s=s[i--].removeFromSet(s));return s}marksAcross(e){let n=this.parent.maybeChild(this.index());if(!n||!n.isInline)return null;let r=n.marks,o=e.parent.maybeChild(e.index());for(var s=0;s<r.length;s++)r[s].type.spec.inclusive===!1&&(!o||!r[s].isInSet(o.marks))&&(r=r[s--].removeFromSet(r));return r}sharedDepth(e){for(let n=this.depth;n>0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos<this.pos)return e.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);r>=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new ml(this,e,r);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<this.pos?e:this}toString(){let e="";for(let n=1;n<=this.depth;n++)e+=(e?"/":"")+this.node(n).type.name+"_"+this.index(n-1);return e+":"+this.parentOffset}static resolve(e,n){if(!(n>=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],o=0,s=n;for(let i=e;;){let{index:a,offset:l}=i.content.findIndex(s),c=s-l;if(r.push(i,a,o+l),!c||(i=i.child(a),i.isText))break;s=c-1,o+=l+1}return new _i(n,r,s)}static resolveCached(e,n){let r=Fy.get(e);if(r)for(let s=0;s<r.elts.length;s++){let i=r.elts[s];if(i.pos==n)return i}else Fy.set(e,r=new LP);let o=r.elts[r.i]=_i.resolve(e,n);return r.i=(r.i+1)%FP,o}}class LP{constructor(){this.elts=[],this.i=0}}const FP=12,Fy=new WeakMap;class ml{constructor(e,n,r){this.$from=e,this.$to=n,this.depth=r}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const VP=Object.create(null);let Er=class qf{constructor(e,n,r,o=Ie.none){this.type=e,this.attrs=n,this.marks=o,this.content=r||D.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,n,r,o=0){this.content.nodesBetween(e,n,r,o,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,n,r,o){return this.content.textBetween(e,n,r,o)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,n,r){return this.type==e&&fl(this.attrs,n||e.defaultAttrs||VP)&&Ie.sameSet(this.marks,r||Ie.none)}copy(e=null){return e==this.content?this:new qf(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new qf(this.type,this.attrs,this.content,e)}cut(e,n=this.content.size){return e==0&&n==this.content.size?this:this.copy(this.content.cut(e,n))}slice(e,n=this.content.size,r=!1){if(e==n)return j.empty;let o=this.resolve(e),s=this.resolve(n),i=r?0:o.sharedDepth(n),a=o.start(i),c=o.node(i).content.cut(o.pos-a,s.pos-a);return new j(c,o.depth-i,s.depth-i)}replace(e,n,r){return zP(this.resolve(e),this.resolve(n),r)}nodeAt(e){for(let n=this;;){let{index:r,offset:o}=n.content.findIndex(e);if(n=n.maybeChild(r),!n)return null;if(o==e||n.isText)return n;e-=o+1}}childAfter(e){let{index:n,offset:r}=this.content.findIndex(e);return{node:this.content.maybeChild(n),index:n,offset:r}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:n,offset:r}=this.content.findIndex(e);if(r<e)return{node:this.content.child(n),index:n,offset:r};let o=this.content.child(n-1);return{node:o,index:n-1,offset:r-o.nodeSize}}resolve(e){return _i.resolveCached(this,e)}resolveNoCache(e){return _i.resolve(this,e)}rangeHasMark(e,n,r){let o=!1;return n>e&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(o=!0),!o)),o}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()+")"),Vy(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=D.empty,o=0,s=r.childCount){let i=this.contentMatchAt(e).matchFragment(r,o,s),a=i&&i.matchFragment(this.content,n);if(!a||!a.validEnd)return!1;for(let l=o;l<s;l++)if(!this.type.allowsMarks(r.child(l).marks))return!1;return!0}canReplaceWith(e,n,r,o){if(o&&!this.type.allowsMarks(o))return!1;let s=this.contentMatchAt(e).matchType(r),i=s&&s.matchFragment(this.content,n);return i?i.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=Ie.none;for(let n=0;n<this.marks.length;n++){let r=this.marks[n];r.type.checkAttrs(r.attrs),e=r.addToSet(e)}if(!Ie.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(n=>n.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n 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(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let o=D.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,o,r);return s.type.checkAttrs(s.attrs),s}};Er.prototype.text=void 0;class gl extends Er{constructor(e,n,r,o){if(super(e,n,null,o),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Vy(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new gl(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new gl(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Vy(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class zo{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new WP(e,n);if(r.next==null)return zo.empty;let o=Wy(r);r.next&&r.err("Unexpected trailing text");let s=qP(YP(o));return JP(s,r),s}matchType(e){for(let n=0;n<this.next.length;n++)if(this.next[n].type==e)return this.next[n].next;return null}matchFragment(e,n=0,r=e.childCount){let o=this;for(let s=n;o&&s<r;s++)o=o.matchType(e.child(s).type);return o}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:n}=this.next[e];if(!(n.isText||n.hasRequiredAttrs()))return n}return null}compatible(e){for(let n=0;n<this.next.length;n++)for(let r=0;r<e.next.length;r++)if(this.next[n].type==e.next[r].type)return!0;return!1}fillBefore(e,n=!1,r=0){let o=[this];function s(i,a){let l=i.matchFragment(e,r);if(l&&(!n||l.validEnd))return D.from(a.map(c=>c.createAndFill()));for(let c=0;c<i.next.length;c++){let{type:u,next:d}=i.next[c];if(!(u.isText||u.hasRequiredAttrs())&&o.indexOf(d)==-1){o.push(d);let h=s(d,a.concat(u));if(h)return h}}return null}return s(this,[])}findWrapping(e){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==e)return this.wrapCache[r+1];let n=this.computeWrapping(e);return this.wrapCache.push(e,n),n}computeWrapping(e){let n=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let o=r.shift(),s=o.match;if(s.matchType(e)){let i=[];for(let a=o;a.type;a=a.via)i.push(a.type);return i.reverse()}for(let i=0;i<s.next.length;i++){let{type:a,next:l}=s.next[i];!a.isLeaf&&!a.hasRequiredAttrs()&&!(a.name in n)&&(!o.type||l.validEnd)&&(r.push({match:a.contentMatch,type:a,via:o}),n[a.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let o=0;o<r.next.length;o++)e.indexOf(r.next[o].next)==-1&&n(r.next[o].next)}return n(this),e.map((r,o)=>{let s=o+(r.validEnd?"*":" ")+" ";for(let i=0;i<r.next.length;i++)s+=(i?", ":"")+r.next[i].type.name+"->"+e.indexOf(r.next[i].next);return s}).join(`
70
- `)}}zo.empty=new zo(!0);class WP{constructor(e,n){this.string=e,this.nodeTypes=n,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 Wy(t){let e=[];do e.push(UP(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function UP(t){let e=[];do e.push(HP(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function HP(t){let e=KP(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=jP(t,e);else break;return e}function Uy(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function jP(t,e){let n=Uy(t),r=n;return t.eat(",")&&(t.next!="}"?r=Uy(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function ZP(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let o=[];for(let s in n){let i=n[s];i.isInGroup(e)&&o.push(i)}return o.length==0&&t.err("No node type or group '"+e+"' found"),o}function KP(t){if(t.eat("(")){let e=Wy(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=ZP(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function YP(t){let e=[[]];return o(s(t,0),n()),e;function n(){return e.push([])-1}function r(i,a,l){let c={term:l,to:a};return e[i].push(c),c}function o(i,a){i.forEach(l=>l.to=a)}function s(i,a){if(i.type=="choice")return i.exprs.reduce((l,c)=>l.concat(s(c,a)),[]);if(i.type=="seq")for(let l=0;;l++){let c=s(i.exprs[l],a);if(l==i.exprs.length-1)return c;o(c,a=n())}else if(i.type=="star"){let l=n();return r(a,l),o(s(i.expr,l),l),[r(l)]}else if(i.type=="plus"){let l=n();return o(s(i.expr,a),l),o(s(i.expr,l),l),[r(l)]}else{if(i.type=="opt")return[r(a)].concat(s(i.expr,a));if(i.type=="range"){let l=a;for(let c=0;c<i.min;c++){let u=n();o(s(i.expr,l),u),l=u}if(i.max==-1)o(s(i.expr,l),l);else for(let c=i.min;c<i.max;c++){let u=n();r(l,u),o(s(i.expr,l),u),l=u}return[r(l)]}else{if(i.type=="name")return[r(a,void 0,i.value)];throw new Error("Unknown expr type")}}}}function Hy(t,e){return e-t}function jy(t,e){let n=[];return r(e),n.sort(Hy);function r(o){let s=t[o];if(s.length==1&&!s[0].term)return r(s[0].to);n.push(o);for(let i=0;i<s.length;i++){let{term:a,to:l}=s[i];!a&&n.indexOf(l)==-1&&r(l)}}}function qP(t){let e=Object.create(null);return n(jy(t,0));function n(r){let o=[];r.forEach(i=>{t[i].forEach(({term:a,to:l})=>{if(!a)return;let c;for(let u=0;u<o.length;u++)o[u][0]==a&&(c=o[u][1]);jy(t,l).forEach(u=>{c||o.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new zo(r.indexOf(t.length-1)>-1);for(let i=0;i<o.length;i++){let a=o[i][1].sort(Hy);s.next.push({type:o[i][0],next:e[a.join(",")]||n(a)})}return s}}function JP(t,e){for(let n=0,r=[t];n<r.length;n++){let o=r[n],s=!o.validEnd,i=[];for(let a=0;a<o.next.length;a++){let{type:l,next:c}=o.next[a];i.push(l.name),s&&!(l.isText||l.hasRequiredAttrs())&&(s=!1),r.indexOf(c)==-1&&r.push(c)}s&&e.err("Only non-generatable nodes ("+i.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function Zy(t){let e=Object.create(null);for(let n in t){let r=t[n];if(!r.hasDefault)return null;e[n]=r.default}return e}function Ky(t,e){let n=Object.create(null);for(let r in t){let o=e&&e[r];if(o===void 0){let s=t[r];if(s.hasDefault)o=s.default;else throw new RangeError("No value supplied for attribute "+r)}n[r]=o}return n}function Yy(t,e,n,r){for(let o in e)if(!(o in t))throw new RangeError(`Unsupported attribute ${o} for ${n} of type ${o}`);for(let o in t){let s=t[o];s.validate&&s.validate(e[o])}}function qy(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new GP(t,r,e[r]);return n}let Jy=class Mv{constructor(e,n,r){this.name=e,this.schema=n,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=qy(e,r.attrs),this.defaultAttrs=Zy(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==zo.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-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:Ky(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Er(this,this.computeAttrs(e),D.from(n),Ie.setFrom(r))}createChecked(e=null,n,r){return n=D.from(n),this.checkContent(n),new Er(this,this.computeAttrs(e),n,Ie.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=D.from(n),n.size){let i=this.contentMatch.fillBefore(n);if(!i)return null;n=i.append(n)}let o=this.contentMatch.matchFragment(n),s=o&&o.fillBefore(D.empty,!0);return s?new Er(this,e,n.append(s),Ie.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r<e.childCount;r++)if(!this.allowsMarks(e.child(r).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){Yy(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;n<e.length;n++)if(!this.allowsMarkType(e[n].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let n;for(let r=0;r<e.length;r++)this.allowsMarkType(e[r].type)?n&&n.push(e[r]):n||(n=e.slice(0,r));return n?n.length?n:Ie.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,i)=>r[s]=new Mv(s,n,i));let o=n.spec.topNode||"doc";if(!r[o])throw new RangeError("Schema is missing its top node type ('"+o+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function XP(t,e,n){let r=n.split("|");return o=>{let s=o===null?"null":typeof o;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class GP{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?XP(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class yl{constructor(e,n,r,o){this.name=e,this.rank=n,this.schema=r,this.spec=o,this.attrs=qy(e,o.attrs),this.excluded=null;let s=Zy(this.attrs);this.instance=s?new Ie(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Ie(this,Ky(this.attrs,e))}static compile(e,n){let r=Object.create(null),o=0;return e.forEach((s,i)=>r[s]=new yl(s,o++,n,i)),r}removeFromSet(e){for(var n=0;n<e.length;n++)e[n].type==this&&(e=e.slice(0,n).concat(e.slice(n+1)),n--);return e}isInSet(e){for(let n=0;n<e.length;n++)if(e[n].type==this)return e[n]}checkAttrs(e){Yy(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class Xy{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let o in e)n[o]=e[o];n.nodes=Mt.from(e.nodes),n.marks=Mt.from(e.marks||{}),this.nodes=Jy.compile(this.spec.nodes,this),this.marks=yl.compile(this.spec.marks,this);let r=Object.create(null);for(let o in this.nodes){if(o in this.marks)throw new RangeError(o+" can not be both a node and a mark");let s=this.nodes[o],i=s.spec.content||"",a=s.spec.marks;if(s.contentMatch=r[i]||(r[i]=zo.parse(i,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=a=="_"?null:a?Gy(this,a.split(" ")):a==""||!s.inlineContent?[]:null}for(let o in this.marks){let s=this.marks[o],i=s.spec.excludes;s.excluded=i==null?[s]:i==""?[]:Gy(this,i.split(" "))}this.nodeFromJSON=o=>Er.fromJSON(this,o),this.markFromJSON=o=>Ie.fromJSON(this,o),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,o){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Jy){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(n,r,o)}text(e,n){let r=this.nodes.text;return new gl(r,r.defaultAttrs,e,Ie.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function Gy(t,e){let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t.marks[o],i=s;if(s)n.push(s);else for(let a in t.marks){let l=t.marks[a];(o=="_"||l.spec.group&&l.spec.group.split(" ").indexOf(o)>-1)&&n.push(i=l)}if(!i)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function QP(t){return t.tag!=null}function eN(t){return t.style!=null}class Cr{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(o=>{if(QP(o))this.tags.push(o);else if(eN(o)){let s=/[^=]*/.exec(o.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(o)}}),this.normalizeLists=!this.tags.some(o=>{if(!/^(ul|ol)\b/.test(o.tag)||!o.node)return!1;let s=e.nodes[o.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new n0(this,n,!1);return r.addAll(e,Ie.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new n0(this,n,!0);return r.addAll(e,Ie.none,n.from,n.to),j.maxOpen(r.finish())}matchTag(e,n,r){for(let o=r?this.tags.indexOf(r)+1:0;o<this.tags.length;o++){let s=this.tags[o];if(rN(e,s.tag)&&(s.namespace===void 0||e.namespaceURI==s.namespace)&&(!s.context||n.matchesContext(s.context))){if(s.getAttrs){let i=s.getAttrs(e);if(i===!1)continue;s.attrs=i||void 0}return s}}}matchStyle(e,n,r,o){for(let s=o?this.styles.indexOf(o)+1:0;s<this.styles.length;s++){let i=this.styles[s],a=i.style;if(!(a.indexOf(e)!=0||i.context&&!r.matchesContext(i.context)||a.length>e.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=n))){if(i.getAttrs){let l=i.getAttrs(n);if(l===!1)continue;i.attrs=l||void 0}return i}}}static schemaRules(e){let n=[];function r(o){let s=o.priority==null?50:o.priority,i=0;for(;i<n.length;i++){let a=n[i];if((a.priority==null?50:a.priority)<s)break}n.splice(i,0,o)}for(let o in e.marks){let s=e.marks[o].spec.parseDOM;s&&s.forEach(i=>{r(i=r0(i)),i.mark||i.ignore||i.clearMark||(i.mark=o)})}for(let o in e.nodes){let s=e.nodes[o].spec.parseDOM;s&&s.forEach(i=>{r(i=r0(i)),i.node||i.ignore||i.mark||(i.node=o)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Cr(e,Cr.schemaRules(e)))}}const Qy={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},tN={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},e0={ol:!0,ul:!0},Ai=1,cd=2,Ii=4;function t0(t,e,n){return e!=null?(e?Ai:0)|(e==="full"?cd:0):t&&t.whitespace=="pre"?Ai|cd:n&~Ii}class wl{constructor(e,n,r,o,s,i){this.type=e,this.attrs=n,this.marks=r,this.solid=o,this.options=i,this.content=[],this.activeMarks=Ie.none,this.match=s||(i&Ii?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(D.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,o;return(o=r.findWrapping(e.type))?(this.match=r,o):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Ai)){let r=this.content[this.content.length-1],o;if(r&&r.isText&&(o=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==o[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-o[0].length))}}let n=D.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(D.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Qy.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class n0{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let o=n.topNode,s,i=t0(null,n.preserveWhitespace,0)|(r?Ii:0);o?s=new wl(o.type,o.attrs,Ie.none,!0,n.topMatch||o.type.contentMatch,i):r?s=new wl(null,null,Ie.none,!0,null,i):s=new wl(e.schema.topNodeType,null,Ie.none,!0,null,i),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,o=this.top,s=o.options&cd?"full":this.localPreserveWS||(o.options&Ai)>0,{schema:i}=this.parser;if(s==="full"||o.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
71
- `);else if(i.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(i.linebreakReplacement.create())){let a=r.split(/\r?\n|\r/);for(let l=0;l<a.length;l++)l&&this.insertNode(i.linebreakReplacement.create(),n,!0),a[l]&&this.insertNode(i.text(a[l]),n,!/\S/.test(a[l]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let a=o.content[o.content.length-1],l=e.previousSibling;(!a||l&&l.nodeName=="BR"||a.isText&&/[ \t\r\n\u000c]$/.test(a.text))&&(r=r.slice(1))}r&&this.insertNode(i.text(r),n,!/\S/.test(r)),this.findInText(e)}else this.findInside(e)}addElement(e,n,r){let o=this.localPreserveWS,s=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let i=e.nodeName.toLowerCase(),a;e0.hasOwnProperty(i)&&this.parser.normalizeLists&&nN(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:tN.hasOwnProperty(i))this.findInside(e),this.ignoreFallback(e,n);else if(!l||l.skip||l.closeParent){l&&l.closeParent?this.open=Math.max(0,this.open-1):l&&l.skip.nodeType&&(e=l.skip);let c,u=this.needsBlock;if(Qy.hasOwnProperty(i))s.content.length&&s.content[0].isInline&&this.open&&(this.open--,s=this.top),c=!0,s.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,n);break e}let d=l&&l.skip?n:this.readStyles(e,n);d&&this.addAll(e,d),c&&this.sync(s),this.needsBlock=u}else{let c=this.readStyles(e,n);c&&this.addElementByRule(e,l,c,l.consuming===!1?a:void 0)}this.localPreserveWS=o}leafFallback(e,n){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
72
- `),n)}ignoreFallback(e,n){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(e,n){let r=e.style;if(r&&r.length)for(let o=0;o<this.parser.matchedStyles.length;o++){let s=this.parser.matchedStyles[o],i=r.getPropertyValue(s);if(i)for(let a=void 0;;){let l=this.parser.matchStyle(s,i,this,a);if(!l)break;if(l.ignore)return null;if(l.clearMark?n=n.filter(c=>!l.clearMark(c)):n=n.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)a=l;else break}}return n}addElementByRule(e,n,r,o){let s,i;if(n.node)if(i=this.parser.schema.nodes[n.node],i.isLeaf)this.insertNode(i.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let l=this.enter(i,n.attrs||null,r,n.preserveWhitespace);l&&(s=!0,r=l)}else{let l=this.parser.schema.marks[n.mark];r=r.concat(l.create(n.attrs))}let a=this.top;if(i&&i.isLeaf)this.findInside(e);else if(o)this.addElement(e,r,o);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=e;typeof n.contentElement=="string"?l=e.querySelector(n.contentElement):typeof n.contentElement=="function"?l=n.contentElement(e):n.contentElement&&(l=n.contentElement),this.findAround(e,l,!0),this.addAll(l,r),this.findAround(e,l,!1)}s&&this.sync(a)&&this.open--}addAll(e,n,r,o){let s=r||0;for(let i=r?e.childNodes[r]:e.firstChild,a=o==null?null:e.childNodes[o];i!=a;i=i.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(i,n);this.findAtPoint(e,s)}findPlace(e,n,r){let o,s;for(let i=this.open,a=0;i>=0;i--){let l=this.nodes[i],c=l.findWrapping(e);if(c&&(!o||o.length>c.length+a)&&(o=c,s=l,!c.length))break;if(l.solid){if(r)break;a+=2}}if(!o)return null;this.sync(s);for(let i=0;i<o.length;i++)n=this.enterInner(o[i],null,n,!1);return n}insertNode(e,n,r){if(e.isInline&&this.needsBlock&&!this.top.type){let s=this.textblockFromContext();s&&(n=this.enterInner(s,null,n))}let o=this.findPlace(e,n,r);if(o){this.closeExtra();let s=this.top;s.match&&(s.match=s.match.matchType(e.type));let i=Ie.none;for(let a of o.concat(e.marks))(s.type?s.type.allowsMarkType(a.type):o0(a.type,e.type))&&(i=a.addToSet(i));return s.content.push(e.mark(i)),!0}return!1}enter(e,n,r,o){let s=this.findPlace(e.create(n),r,!1);return s&&(s=this.enterInner(e,n,r,!0,o)),s}enterInner(e,n,r,o=!1,s){this.closeExtra();let i=this.top;i.match=i.match&&i.match.matchType(e);let a=t0(e,s,i.options);i.options&Ii&&i.content.length==0&&(a|=Ii);let l=Ie.none;return r=r.filter(c=>(i.type?i.type.allowsMarkType(c.type):o0(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new wl(e,n,l,o,null,a)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].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 n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Ai)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let o=r.length-1;o>=0;o--)e+=r[o].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==e&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&e.nodeType==1&&e.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(e,n,r){if(e!=n&&this.find)for(let o=0;o<this.find.length;o++)this.find[o].pos==null&&e.nodeType==1&&e.contains(this.find[o].node)&&n.compareDocumentPosition(this.find[o].node)&(r?2:4)&&(this.find[o].pos=this.currentPos)}findInText(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&(this.find[n].pos=this.currentPos-(e.nodeValue.length-this.find[n].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,o=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(o?0:1),i=(a,l)=>{for(;a>=0;a--){let c=n[a];if(c==""){if(a==n.length-1||a==0)continue;for(;l>=s;l--)if(i(a-1,l))return!0;return!1}else{let u=l>0||l==0&&o?this.nodes[l].type:r&&l>=s?r.node(l-s).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;l--}}return!0};return i(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function nN(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&e0.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function rN(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function r0(t){let e={};for(let n in t)e[n]=t[n];return e}function o0(t,e){let n=e.schema.nodes;for(let r in n){let o=n[r];if(!o.allowsMarkType(t))continue;let s=[],i=a=>{s.push(a);for(let l=0;l<a.edgeCount;l++){let{type:c,next:u}=a.edge(l);if(c==e||s.indexOf(u)<0&&i(u))return!0}};if(i(o.contentMatch))return!0}}class $o{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=ud(n).createDocumentFragment());let o=r,s=[];return e.forEach(i=>{if(s.length||i.marks.length){let a=0,l=0;for(;a<s.length&&l<i.marks.length;){let c=i.marks[l];if(!this.marks[c.type.name]){l++;continue}if(!c.eq(s[a][0])||c.type.spec.spanning===!1)break;a++,l++}for(;a<s.length;)o=s.pop()[1];for(;l<i.marks.length;){let c=i.marks[l++],u=this.serializeMark(c,i.isInline,n);u&&(s.push([c,o]),o.appendChild(u.dom),o=u.contentDOM||u.dom)}}o.appendChild(this.serializeNodeInner(i,n))}),r}serializeNodeInner(e,n){let{dom:r,contentDOM:o}=kl(ud(n),this.nodes[e.type.name](e),null,e.attrs);if(o){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,n,o)}return r}serializeNode(e,n={}){let r=this.serializeNodeInner(e,n);for(let o=e.marks.length-1;o>=0;o--){let s=this.serializeMark(e.marks[o],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let o=this.marks[e.type.name];return o&&kl(ud(r),o(e,n),null,e.attrs)}static renderSpec(e,n,r=null,o){return kl(e,n,r,o)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new $o(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=s0(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return s0(e.marks)}}function s0(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function ud(t){return t.document||window.document}const i0=new WeakMap;function oN(t){let e=i0.get(t);return e===void 0&&i0.set(t,e=sN(t)),e}function sN(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let o=0;o<r.length;o++)n(r[o]);else for(let o in r)n(r[o])}return n(t),e}function kl(t,e,n,r){if(typeof e=="string")return{dom:t.createTextNode(e)};if(e.nodeType!=null)return{dom:e};if(e.dom&&e.dom.nodeType!=null)return e;let o=e[0],s;if(typeof o!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(s=oN(r))&&s.indexOf(e)>-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 i=o.indexOf(" ");i>0&&(n=o.slice(0,i),o=o.slice(i+1));let a,l=n?t.createElementNS(n,o):t.createElement(o),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let d in c)if(c[d]!=null){let h=d.indexOf(" ");h>0?l.setAttributeNS(d.slice(0,h),d.slice(h+1),c[d]):d=="style"&&l.style?l.style.cssText=c[d]:l.setAttribute(d,c[d])}}for(let d=u;d<e.length;d++){let h=e[d];if(h===0){if(d<e.length-1||d>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:l,contentDOM:l}}else{let{dom:p,contentDOM:m}=kl(t,h,n,r);if(l.appendChild(p),m){if(a)throw new RangeError("Multiple content holes");a=m}}}return{dom:l,contentDOM:a}}const a0=65535,l0=Math.pow(2,16);function iN(t,e){return t+e*l0}function c0(t){return t&a0}function aN(t){return(t-(t&a0))/l0}const u0=1,d0=2,vl=4,f0=8;class dd{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&f0)>0}get deletedBefore(){return(this.delInfo&(u0|vl))>0}get deletedAfter(){return(this.delInfo&(d0|vl))>0}get deletedAcross(){return(this.delInfo&vl)>0}}class un{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&un.empty)return un.empty}recover(e){let n=0,r=c0(e);if(!this.inverted)for(let o=0;o<r;o++)n+=this.ranges[o*3+2]-this.ranges[o*3+1];return this.ranges[r*3]+n+aN(e)}mapResult(e,n=1){return this._map(e,n,!1)}map(e,n=1){return this._map(e,n,!0)}_map(e,n,r){let o=0,s=this.inverted?2:1,i=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?o:0);if(l>e)break;let c=this.ranges[a+s],u=this.ranges[a+i],d=l+c;if(e<=d){let h=c?e==l?-1:e==d?1:n:n,p=l+o+(h<0?0:u);if(r)return p;let m=e==(n<0?l:d)?null:iN(a/3,e-l),g=e==l?d0:e==d?u0:vl;return(n<0?e!=l:e!=d)&&(g|=f0),new dd(p,g,m)}o+=u-c}return r?e+o:new dd(e+o,0,null)}touches(e,n){let r=0,o=c0(n),s=this.inverted?2:1,i=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?r:0);if(l>e)break;let c=this.ranges[a+s],u=l+c;if(e<=u&&a==o*3)return!0;r+=this.ranges[a+i]-c}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let o=0,s=0;o<this.ranges.length;o+=3){let i=this.ranges[o],a=i-(this.inverted?s:0),l=i+(this.inverted?0:s),c=this.ranges[o+n],u=this.ranges[o+r];e(a,a+c,l,l+u),s+=u-c}}invert(){return new un(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?un.empty:new un(e<0?[0,-e,0]:[0,0,e])}}un.empty=new un([]);class Bi{constructor(e,n,r=0,o=e?e.length:0){this.mirror=n,this.from=r,this.to=o,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new Bi(this._maps,this.mirror,e,n)}appendMap(e,n){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),n!=null&&this.setMirror(this._maps.length-1,n)}appendMapping(e){for(let n=0,r=this._maps.length;n<e._maps.length;n++){let o=e.getMirror(n);this.appendMap(e._maps[n],o!=null&&o<n?r+o:void 0)}}getMirror(e){if(this.mirror){for(let n=0;n<this.mirror.length;n++)if(this.mirror[n]==e)return this.mirror[n+(n%2?-1:1)]}}setMirror(e,n){this.mirror||(this.mirror=[]),this.mirror.push(e,n)}appendMappingInverted(e){for(let n=e.maps.length-1,r=this._maps.length+e._maps.length;n>=0;n--){let o=e.getMirror(n);this.appendMap(e._maps[n].invert(),o!=null&&o>n?r-o-1:void 0)}}invert(){let e=new Bi;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;r<this.to;r++)e=this._maps[r].map(e,n);return e}mapResult(e,n=1){return this._map(e,n,!1)}_map(e,n,r){let o=0;for(let s=this.from;s<this.to;s++){let i=this._maps[s],a=i.mapResult(e,n);if(a.recover!=null){let l=this.getMirror(s);if(l!=null&&l>s&&l<this.to){s=l,e=this._maps[l].recover(a.recover);continue}}o|=a.delInfo,e=a.pos}return r?e:new dd(e,o,null)}}const fd=Object.create(null);class Ot{getMap(){return un.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=fd[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in fd)throw new RangeError("Duplicate use of step JSON ID "+e);return fd[e]=n,n.prototype.jsonID=e,n}}class et{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new et(e,null)}static fail(e){return new et(null,e)}static fromReplace(e,n,r,o){try{return et.ok(e.replace(n,r,o))}catch(s){if(s instanceof hl)return et.fail(s.message);throw s}}}function hd(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let s=t.child(o);s.content.size&&(s=s.copy(hd(s.content,e,s))),s.isInline&&(s=e(s,n,o)),r.push(s)}return D.fromArray(r)}class eo extends Ot{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=e.resolve(this.from),o=r.node(r.sharedDepth(this.to)),s=new j(hd(n.content,(i,a)=>!i.isAtom||!a.type.allowsMarkType(this.mark.type)?i:i.mark(this.mark.addToSet(i.marks)),o),n.openStart,n.openEnd);return et.fromReplace(e,this.from,this.to,s)}invert(){return new Fn(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new eo(n.pos,r.pos,this.mark)}merge(e){return e instanceof eo&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new eo(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,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new eo(n.from,n.to,e.markFromJSON(n.mark))}}Ot.jsonID("addMark",eo);class Fn extends Ot{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new j(hd(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),e),n.openStart,n.openEnd);return et.fromReplace(e,this.from,this.to,r)}invert(){return new eo(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Fn(n.pos,r.pos,this.mark)}merge(e){return e instanceof Fn&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Fn(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,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Fn(n.from,n.to,e.markFromJSON(n.mark))}}Ot.jsonID("removeMark",Fn);class to extends Ot{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return et.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return et.fromReplace(e,this.pos,this.pos+1,new j(D.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let o=0;o<n.marks.length;o++)if(!n.marks[o].isInSet(r))return new to(this.pos,n.marks[o]);return new to(this.pos,this.mark)}}return new Lo(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new to(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new to(n.pos,e.markFromJSON(n.mark))}}Ot.jsonID("addNodeMark",to);class Lo extends Ot{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return et.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return et.fromReplace(e,this.pos,this.pos+1,new j(D.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new to(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Lo(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new Lo(n.pos,e.markFromJSON(n.mark))}}Ot.jsonID("removeNodeMark",Lo);class mt extends Ot{constructor(e,n,r,o=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=o}apply(e){return this.structure&&pd(e,this.from,this.to)?et.fail("Structure replace would overwrite content"):et.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new un([this.from,this.to-this.from,this.slice.size])}invert(e){return new mt(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new mt(n.pos,Math.max(n.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof mt)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let n=this.slice.size+e.slice.size==0?j.empty:new j(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new mt(this.from,this.to+(e.to-e.from),n,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let n=this.slice.size+e.slice.size==0?j.empty:new j(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new mt(e.from,this.to,n,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new mt(n.from,n.to,j.fromJSON(e,n.slice),!!n.structure)}}Ot.jsonID("replace",mt);class gt extends Ot{constructor(e,n,r,o,s,i,a=!1){super(),this.from=e,this.to=n,this.gapFrom=r,this.gapTo=o,this.slice=s,this.insert=i,this.structure=a}apply(e){if(this.structure&&(pd(e,this.from,this.gapFrom)||pd(e,this.gapTo,this.to)))return et.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return et.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?et.fromReplace(e,this.from,this.to,r):et.fail("Content does not fit in gap")}getMap(){return new un([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new gt(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),o=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),s=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||o<n.pos||s>r.pos?null:new gt(n.pos,r.pos,o,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,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new gt(n.from,n.to,n.gapFrom,n.gapTo,j.fromJSON(e,n.slice),n.insert,!!n.structure)}}Ot.jsonID("replaceAround",gt);function pd(t,e,n){let r=t.resolve(e),o=n-e,s=r.depth;for(;o>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,o--;if(o>0){let i=r.node(s).maybeChild(r.indexAfter(s));for(;o>0;){if(!i||i.isLeaf)return!0;i=i.firstChild,o--}}return!1}function lN(t,e,n,r){let o=[],s=[],i,a;t.doc.nodesBetween(e,n,(l,c,u)=>{if(!l.isInline)return;let d=l.marks;if(!r.isInSet(d)&&u.type.allowsMarkType(r.type)){let h=Math.max(c,e),p=Math.min(c+l.nodeSize,n),m=r.addToSet(d);for(let g=0;g<d.length;g++)d[g].isInSet(m)||(i&&i.to==h&&i.mark.eq(d[g])?i.to=p:o.push(i=new Fn(h,p,d[g])));a&&a.to==h?a.to=p:s.push(a=new eo(h,p,r))}}),o.forEach(l=>t.step(l)),s.forEach(l=>t.step(l))}function cN(t,e,n,r){let o=[],s=0;t.doc.nodesBetween(e,n,(i,a)=>{if(!i.isInline)return;s++;let l=null;if(r instanceof yl){let c=i.marks,u;for(;u=r.isInSet(c);)(l||(l=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(i.marks)&&(l=[r]):l=i.marks;if(l&&l.length){let c=Math.min(a+i.nodeSize,n);for(let u=0;u<l.length;u++){let d=l[u],h;for(let p=0;p<o.length;p++){let m=o[p];m.step==s-1&&d.eq(o[p].style)&&(h=m)}h?(h.to=c,h.step=s):o.push({style:d,from:Math.max(a,e),to:c,step:s})}}}),o.forEach(i=>t.step(new Fn(i.from,i.to,i.style)))}function md(t,e,n,r=n.contentMatch,o=!0){let s=t.doc.nodeAt(e),i=[],a=e+1;for(let l=0;l<s.childCount;l++){let c=s.child(l),u=a+c.nodeSize,d=r.matchType(c.type);if(!d)i.push(new mt(a,u,j.empty));else{r=d;for(let h=0;h<c.marks.length;h++)n.allowsMarkType(c.marks[h].type)||t.step(new Fn(a,u,c.marks[h]));if(o&&c.isText&&n.whitespace!="pre"){let h,p=/\r?\n|\r/g,m;for(;h=p.exec(c.text);)m||(m=new j(D.from(n.schema.text(" ",n.allowedMarks(c.marks))),0,0)),i.push(new mt(a+h.index,a+h.index+h[0].length,m))}}a=u}if(!r.validEnd){let l=r.fillBefore(D.empty,!0);t.replace(a,a,new j(l,0,0))}for(let l=i.length-1;l>=0;l--)t.step(i[l])}function uN(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ns(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,o=0,s=0;;--r){let i=t.$from.node(r),a=t.$from.index(r)+o,l=t.$to.indexAfter(r)-s;if(r<t.depth&&i.canReplace(a,l,n))return r;if(r==0||i.type.spec.isolating||!uN(i,a,l))break;a&&(o=1),l<i.childCount&&(s=1)}return null}function dN(t,e,n){let{$from:r,$to:o,depth:s}=e,i=r.before(s+1),a=o.after(s+1),l=i,c=a,u=D.empty,d=0;for(let m=s,g=!1;m>n;m--)g||r.index(m)>0?(g=!0,u=D.from(r.node(m).copy(u)),d++):l--;let h=D.empty,p=0;for(let m=s,g=!1;m>n;m--)g||o.after(m+1)<o.end(m)?(g=!0,h=D.from(o.node(m).copy(h)),p++):c++;t.step(new gt(l,c,i,a,new j(u.append(h),d,p),u.size-d,!0))}function h0(t,e,n=null,r=t){let o=fN(t,e),s=o&&hN(r,e);return s?o.map(p0).concat({type:e,attrs:n}).concat(s.map(p0)):null}function p0(t){return{type:t,attrs:null}}function fN(t,e){let{parent:n,startIndex:r,endIndex:o}=t,s=n.contentMatchAt(r).findWrapping(e);if(!s)return null;let i=s.length?s[0]:e;return n.canReplaceWith(r,o,i)?s:null}function hN(t,e){let{parent:n,startIndex:r,endIndex:o}=t,s=n.child(r),i=e.contentMatch.findWrapping(s.type);if(!i)return null;let l=(i.length?i[i.length-1]:e).contentMatch;for(let c=r;l&&c<o;c++)l=l.matchType(n.child(c).type);return!l||!l.validEnd?null:i}function pN(t,e,n){let r=D.empty;for(let i=n.length-1;i>=0;i--){if(r.size){let a=n[i].type.contentMatch.matchFragment(r);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=D.from(n[i].type.create(n[i].attrs,r))}let o=e.start,s=e.end;t.step(new gt(o,s,o,s,new j(r,0,0),n.length,!0))}function mN(t,e,n,r,o){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(i,a)=>{let l=typeof o=="function"?o(i):o;if(i.isTextblock&&!i.hasMarkup(r,l)&&gN(t.doc,t.mapping.slice(s).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",m=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!m?c=!1:!p&&m&&(c=!0)}c===!1&&g0(t,i,a,s),md(t,t.mapping.slice(s).map(a,1),r,void 0,c===null);let u=t.mapping.slice(s),d=u.map(a,1),h=u.map(a+i.nodeSize,1);return t.step(new gt(d,h,d+1,h-1,new j(D.from(r.create(l,null,i.marks)),0,0),1,!0)),c===!0&&m0(t,i,a,s),!1}})}function m0(t,e,n,r){e.forEach((o,s)=>{if(o.isText){let i,a=/\r?\n|\r/g;for(;i=a.exec(o.text);){let l=t.mapping.slice(r).map(n+1+s+i.index);t.replaceWith(l,l+1,e.type.schema.linebreakReplacement.create())}}})}function g0(t,e,n,r){e.forEach((o,s)=>{if(o.type==o.type.schema.linebreakReplacement){let i=t.mapping.slice(r).map(n+1+s);t.replaceWith(i,i+1,e.type.schema.text(`
73
- `))}})}function gN(t,e,n){let r=t.resolve(e),o=r.index();return r.parent.canReplaceWith(o,o+1,n)}function yN(t,e,n,r,o){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let i=n.create(r,null,o||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,i);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new gt(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new j(D.from(i),0,0),1,!0))}function xr(t,e,n=1,r){let o=t.resolve(e),s=o.depth-n,i=r&&r[r.length-1]||o.parent;if(s<0||o.parent.type.spec.isolating||!o.parent.canReplace(o.index(),o.parent.childCount)||!i.type.validContent(o.parent.content.cutByIndex(o.index(),o.parent.childCount)))return!1;for(let c=o.depth-1,u=n-2;c>s;c--,u--){let d=o.node(c),h=o.index(c);if(d.type.spec.isolating)return!1;let p=d.content.cutByIndex(h,d.childCount),m=r&&r[u+1];m&&(p=p.replaceChild(0,m.type.create(m.attrs)));let g=r&&r[u]||d;if(!d.canReplace(h+1,d.childCount)||!g.type.validContent(p))return!1}let a=o.indexAfter(s),l=r&&r[0];return o.node(s).canReplaceWith(a,a,l?l.type:o.node(s+1).type)}function wN(t,e,n=1,r){let o=t.doc.resolve(e),s=D.empty,i=D.empty;for(let a=o.depth,l=o.depth-n,c=n-1;a>l;a--,c--){s=D.from(o.node(a).copy(s));let u=r&&r[c];i=D.from(u?u.type.create(u.attrs,i):o.node(a).copy(i))}t.step(new mt(e,e,new j(s.append(i),n,n),!0))}function Fo(t,e){let n=t.resolve(e),r=n.index();return y0(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function kN(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let o=0;o<e.childCount;o++){let s=e.child(o),i=s.type==r?t.type.schema.nodes.text:s.type;if(n=n.matchType(i),!n||!t.type.allowsMarks(s.marks))return!1}return n.validEnd}function y0(t,e){return!!(t&&e&&!t.isLeaf&&kN(t,e))}function bl(t,e,n=-1){let r=t.resolve(e);for(let o=r.depth;;o--){let s,i,a=r.index(o);if(o==r.depth?(s=r.nodeBefore,i=r.nodeAfter):n>0?(s=r.node(o+1),a++,i=r.node(o).maybeChild(a)):(s=r.node(o).maybeChild(a-1),i=r.node(o+1)),s&&!s.isTextblock&&y0(s,i)&&r.node(o).canReplace(a,a+1))return e;if(o==0)break;e=n<0?r.before(o):r.after(o)}}function vN(t,e,n){let r=null,{linebreakReplacement:o}=t.doc.type.schema,s=t.doc.resolve(e-n),i=s.node().type;if(o&&i.inlineContent){let u=i.whitespace=="pre",d=!!i.contentMatch.matchType(o);u&&!d?r=!1:!u&&d&&(r=!0)}let a=t.steps.length;if(r===!1){let u=t.doc.resolve(e+n);g0(t,u.node(),u.before(),a)}i.inlineContent&&md(t,e+n-1,i,s.node().contentMatchAt(s.index()),r==null);let l=t.mapping.slice(a),c=l.map(e-n);if(t.step(new mt(c,l.map(e+n,-1),j.empty,!0)),r===!0){let u=t.doc.resolve(c);m0(t,u.node(),u.before(),t.steps.length)}return t}function bN(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let o=r.depth-1;o>=0;o--){let s=r.index(o);if(r.node(o).canReplaceWith(s,s,n))return r.before(o+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let o=r.depth-1;o>=0;o--){let s=r.indexAfter(o);if(r.node(o).canReplaceWith(s,s,n))return r.after(o+1);if(s<r.node(o).childCount)return null}return null}function w0(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let o=n.content;for(let s=0;s<n.openStart;s++)o=o.firstChild.content;for(let s=1;s<=(n.openStart==0&&n.size?2:1);s++)for(let i=r.depth;i>=0;i--){let a=i==r.depth?0:r.pos<=(r.start(i+1)+r.end(i+1))/2?-1:1,l=r.index(i)+(a>0?1:0),c=r.node(i),u=!1;if(s==1)u=c.canReplace(l,l,o);else{let d=c.contentMatchAt(l).findWrapping(o.firstChild.type);u=d&&c.canReplaceWith(l,l,d[0])}if(u)return a==0?r.pos:a<0?r.before(i+1):r.after(i+1)}return null}function Sl(t,e,n=e,r=j.empty){if(e==n&&!r.size)return null;let o=t.resolve(e),s=t.resolve(n);return k0(o,s,r)?new mt(e,n,r):new SN(o,s,r).fit()}function k0(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class SN{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=D.empty;for(let o=0;o<=e.depth;o++){let s=e.node(o);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(o))})}for(let o=e.depth;o>0;o--)this.placed=D.from(e.node(o).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,o=this.close(e<0?this.$to:r.doc.resolve(e));if(!o)return null;let s=this.placed,i=r.depth,a=o.depth;for(;i&&a&&s.childCount==1;)s=s.firstChild.content,i--,a--;let l=new j(s,i,a);return e>-1?new gt(r.pos,e,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new mt(r.pos,o.pos,l):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,o=this.unplaced.openEnd;r<e;r++){let s=n.firstChild;if(n.childCount>1&&(o=0),s.type.spec.isolating&&o<=r){e=r;break}n=s.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let o,s=null;r?(s=gd(this.unplaced.content,r-1).firstChild,o=s.content):o=this.unplaced.content;let i=o.firstChild;for(let a=this.depth;a>=0;a--){let{type:l,match:c}=this.frontier[a],u,d=null;if(n==1&&(i?c.matchType(i.type)||(d=c.fillBefore(D.from(i),!1)):s&&l.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:a,parent:s,inject:d};if(n==2&&i&&(u=c.findWrapping(i.type)))return{sliceDepth:r,frontierDepth:a,parent:s,wrap:u};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,o=gd(e,n);return!o.childCount||o.firstChild.isLeaf?!1:(this.unplaced=new j(e,n+1,Math.max(r,o.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,o=gd(e,n);if(o.childCount<=1&&n>0){let s=e.size-n<=n+o.size;this.unplaced=new j(Pi(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new j(Pi(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:o,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let g=0;g<s.length;g++)this.openFrontierNode(s[g]);let i=this.unplaced,a=r?r.content:i.content,l=i.openStart-e,c=0,u=[],{match:d,type:h}=this.frontier[n];if(o){for(let g=0;g<o.childCount;g++)u.push(o.child(g));d=d.matchFragment(o)}let p=a.size+e-(i.content.size-i.openEnd);for(;c<a.childCount;){let g=a.child(c),y=d.matchType(g.type);if(!y)break;c++,(c>1||l==0||g.content.size)&&(d=y,u.push(v0(g.mark(h.allowedMarks(g.marks)),c==1?l:0,c==a.childCount?p:-1)))}let m=c==a.childCount;m||(p=-1),this.placed=Ni(this.placed,n,D.from(u)),this.frontier[n].match=d,m&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,y=a;g<p;g++){let w=y.lastChild;this.frontier.push({type:w.type,match:w.contentMatchAt(w.childCount)}),y=w.content}this.unplaced=m?e==0?j.empty:new j(Pi(i.content,e-1,1),e-1,p<0?i.openEnd:e-1):new j(Pi(i.content,e,c),i.openStart,i.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],n;if(!e.type.isTextblock||!yd(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(n=this.findCloseLevel(this.$to))&&n.depth==this.depth)return-1;let{depth:r}=this.$to,o=this.$to.after(r);for(;r>1&&o==this.$to.end(--r);)++o;return o}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:o}=this.frontier[n],s=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),i=yd(e,n,o,r,s);if(i){for(let a=n-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=yd(e,a,c,l,!0);if(!u||u.childCount)continue e}return{depth:n,fit:i,move:s?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Ni(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let o=e.node(r),s=o.type.contentMatch.fillBefore(o.content,!0,e.index(r));this.openFrontierNode(o.type,o.attrs,s)}return e}openFrontierNode(e,n=null,r){let o=this.frontier[this.depth];o.match=o.match.matchType(e),this.placed=Ni(this.placed,this.depth,D.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(D.empty,!0);n.childCount&&(this.placed=Ni(this.placed,this.frontier.length,n))}}function Pi(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Pi(t.firstChild.content,e-1,n)))}function Ni(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Ni(t.lastChild.content,e-1,n)))}function gd(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function v0(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,v0(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(D.empty,!0)))),t.copy(r)}function yd(t,e,n,r,o){let s=t.node(e),i=o?t.indexAfter(e):t.index(e);if(i==s.childCount&&!n.compatibleContent(s.type))return null;let a=r.fillBefore(s.content,!0,i);return a&&!EN(n,s.content,i)?a:null}function EN(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function CN(t){return t.spec.defining||t.spec.definingForContent}function xN(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let o=t.doc.resolve(e),s=t.doc.resolve(n);if(k0(o,s,r))return t.step(new mt(e,n,r));let i=S0(o,s);i[i.length-1]==0&&i.pop();let a=-(o.depth+1);i.unshift(a);for(let h=o.depth,p=o.pos-1;h>0;h--,p--){let m=o.node(h).type.spec;if(m.defining||m.definingAsContext||m.isolating)break;i.indexOf(h)>-1?a=h:o.before(h)==p&&i.splice(1,0,-h)}let l=i.indexOf(a),c=[],u=r.openStart;for(let h=r.content,p=0;;p++){let m=h.firstChild;if(c.push(m),p==r.openStart)break;h=m.content}for(let h=u-1;h>=0;h--){let p=c[h],m=CN(p.type);if(m&&!p.sameMarkup(o.node(Math.abs(a)-1)))u=h;else if(m||!p.type.isTextblock)break}for(let h=r.openStart;h>=0;h--){let p=(h+u+1)%(r.openStart+1),m=c[p];if(m)for(let g=0;g<i.length;g++){let y=i[(g+l)%i.length],w=!0;y<0&&(w=!1,y=-y);let k=o.node(y-1),b=o.index(y-1);if(k.canReplaceWith(b,b,m.type,m.marks))return t.replace(o.before(y),w?s.after(y):n,new j(b0(r.content,0,r.openStart,p),p,r.openEnd))}}let d=t.steps.length;for(let h=i.length-1;h>=0&&(t.replace(e,n,r),!(t.steps.length>d));h--){let p=i[h];p<0||(e=o.before(p),n=s.after(p))}}function b0(t,e,n,r,o){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(b0(s.content,e+1,n,r,s)))}if(e>r){let s=o.contentMatchAt(0),i=s.fillBefore(t).append(t);t=i.append(s.matchFragment(i).fillBefore(D.empty,!0))}return t}function TN(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let o=bN(t.doc,e,r.type);o!=null&&(e=n=o)}t.replaceRange(e,n,new j(D.from(r),0,0))}function MN(t,e,n){let r=t.doc.resolve(e),o=t.doc.resolve(n),s=S0(r,o);for(let i=0;i<s.length;i++){let a=s[i],l=i==s.length-1;if(l&&a==0||r.node(a).type.contentMatch.validEnd)return t.delete(r.start(a),o.end(a));if(a>0&&(l||r.node(a-1).canReplace(r.index(a-1),o.indexAfter(a-1))))return t.delete(r.before(a),o.after(a))}for(let i=1;i<=r.depth&&i<=o.depth;i++)if(e-r.start(i)==r.depth-i&&n>r.end(i)&&o.end(i)-n!=o.depth-i&&r.start(i-1)==o.start(i-1)&&r.node(i-1).canReplace(r.index(i-1),o.index(i-1)))return t.delete(r.before(i),n);t.delete(e,n)}function S0(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let o=r;o>=0;o--){let s=t.start(o);if(s<t.pos-(t.depth-o)||e.end(o)>e.pos+(e.depth-o)||t.node(o).type.spec.isolating||e.node(o).type.spec.isolating)break;(s==e.start(o)||o==t.depth&&o==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&o&&e.start(o-1)==s-1)&&n.push(o)}return n}class Ds extends Ot{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return et.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let o=n.type.create(r,null,n.marks);return et.fromReplace(e,this.pos,this.pos+1,new j(D.from(o),0,n.isLeaf?0:1))}getMap(){return un.empty}invert(e){return new Ds(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Ds(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Ds(n.pos,n.attr,n.value)}}Ot.jsonID("attr",Ds);class Di extends Ot{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let o in e.attrs)n[o]=e.attrs[o];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return et.ok(r)}getMap(){return un.empty}invert(e){return new Di(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Di(n.attr,n.value)}}Ot.jsonID("docAttr",Di);let Os=class extends Error{};Os=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n},Os.prototype=Object.create(Error.prototype),Os.prototype.constructor=Os,Os.prototype.name="TransformError";class E0{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Bi}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Os(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let o=this.mapping.maps[r];r&&(e=o.map(e,1),n=o.map(n,-1)),o.forEach((s,i,a,l)=>{e=Math.min(e,a),n=Math.max(n,l)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=j.empty){let o=Sl(this.doc,e,n,r);return o&&this.step(o),this}replaceWith(e,n,r){return this.replace(e,n,new j(D.from(r),0,0))}delete(e,n){return this.replace(e,n,j.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return xN(this,e,n,r),this}replaceRangeWith(e,n,r){return TN(this,e,n,r),this}deleteRange(e,n){return MN(this,e,n),this}lift(e,n){return dN(this,e,n),this}join(e,n=1){return vN(this,e,n),this}wrap(e,n){return pN(this,e,n),this}setBlockType(e,n=e,r,o=null){return mN(this,e,n,r,o),this}setNodeMarkup(e,n,r=null,o){return yN(this,e,n,r,o),this}setNodeAttribute(e,n,r){return this.step(new Ds(e,n,r)),this}setDocAttribute(e,n){return this.step(new Di(e,n)),this}addNodeMark(e,n){return this.step(new to(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof Ie)n.isInSet(r.marks)&&this.step(new Lo(e,n));else{let o=r.marks,s,i=[];for(;s=n.isInSet(o);)i.push(new Lo(e,s)),o=s.removeFromSet(o);for(let a=i.length-1;a>=0;a--)this.step(i[a])}return this}split(e,n=1,r){return wN(this,e,n,r),this}addMark(e,n,r){return lN(this,e,n,r),this}removeMark(e,n,r){return cN(this,e,n,r),this}clearIncompatible(e,n,r){return md(this,e,n,r),this}}const wd=Object.create(null);class fe{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new _N(e.min(n),e.max(n))]}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 n=0;n<e.length;n++)if(e[n].$from.pos!=e[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,n=j.empty){let r=n.content.lastChild,o=null;for(let a=0;a<n.openEnd;a++)o=r,r=r.lastChild;let s=e.steps.length,i=this.ranges;for(let a=0;a<i.length;a++){let{$from:l,$to:c}=i[a],u=e.mapping.slice(s);e.replaceRange(u.map(l.pos),u.map(c.pos),a?j.empty:n),a==0&&T0(e,s,(r?r.isInline:o&&o.isTextblock)?-1:1)}}replaceWith(e,n){let r=e.steps.length,o=this.ranges;for(let s=0;s<o.length;s++){let{$from:i,$to:a}=o[s],l=e.mapping.slice(r),c=l.map(i.pos),u=l.map(a.pos);s?e.deleteRange(c,u):(e.replaceRangeWith(c,u,n),T0(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let o=e.parent.inlineContent?new ue(e):Rs(e.node(0),e.parent,e.pos,e.index(),n,r);if(o)return o;for(let s=e.depth-1;s>=0;s--){let i=n<0?Rs(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Rs(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(i)return i}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new dn(e.node(0))}static atStart(e){return Rs(e,e,0,0,1)||new dn(e)}static atEnd(e){return Rs(e,e,e.content.size,e.childCount,-1)||new dn(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=wd[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in wd)throw new RangeError("Duplicate use of selection JSON ID "+e);return wd[e]=n,n.prototype.jsonID=e,n}getBookmark(){return ue.between(this.$anchor,this.$head).getBookmark()}}fe.prototype.visible=!0;class _N{constructor(e,n){this.$from=e,this.$to=n}}let C0=!1;function x0(t){!C0&&!t.parent.inlineContent&&(C0=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class ue extends fe{constructor(e,n=e){x0(e),x0(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return fe.near(r);let o=e.resolve(n.map(this.anchor));return new ue(o.parent.inlineContent?o:r,r)}replace(e,n=j.empty){if(super.replace(e,n),n==j.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof ue&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new El(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new ue(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let o=e.resolve(n);return new this(o,r==n?o:e.resolve(r))}static between(e,n,r){let o=e.pos-n.pos;if((!r||o)&&(r=o>=0?1:-1),!n.parent.inlineContent){let s=fe.findFrom(n,r,!0)||fe.findFrom(n,-r,!0);if(s)n=s.$head;else return fe.near(n,r)}return e.parent.inlineContent||(o==0?e=n:(e=(fe.findFrom(e,-r,!0)||fe.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=o<0&&(e=n))),new ue(e,n)}}fe.jsonID("text",ue);class El{constructor(e,n){this.anchor=e,this.head=n}map(e){return new El(e.map(this.anchor),e.map(this.head))}resolve(e){return ue.between(e.resolve(this.anchor),e.resolve(this.head))}}class re extends fe{constructor(e){let n=e.nodeAfter,r=e.node(0).resolve(e.pos+n.nodeSize);super(e,r),this.node=n}map(e,n){let{deleted:r,pos:o}=n.mapResult(this.anchor),s=e.resolve(o);return r?fe.near(s):new re(s)}content(){return new j(D.from(this.node),0,0)}eq(e){return e instanceof re&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new kd(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new re(e.resolve(n.anchor))}static create(e,n){return new re(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}re.prototype.visible=!1,fe.jsonID("node",re);class kd{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new El(r,r):new kd(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&re.isSelectable(r)?new re(n):fe.near(n)}}class dn extends fe{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=j.empty){if(n==j.empty){e.delete(0,e.doc.content.size);let r=fe.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new dn(e)}map(e){return new dn(e)}eq(e){return e instanceof dn}getBookmark(){return AN}}fe.jsonID("all",dn);const AN={map(){return this},resolve(t){return new dn(t)}};function Rs(t,e,n,r,o,s=!1){if(e.inlineContent)return ue.create(t,n);for(let i=r-(o>0?0:1);o>0?i<e.childCount:i>=0;i+=o){let a=e.child(i);if(a.isAtom){if(!s&&re.isSelectable(a))return re.create(t,n-(o<0?a.nodeSize:0))}else{let l=Rs(t,a,n+o,o<0?a.childCount:0,o,s);if(l)return l}n+=a.nodeSize*o}return null}function T0(t,e,n){let r=t.steps.length-1;if(r<e)return;let o=t.steps[r];if(!(o instanceof mt||o instanceof gt))return;let s=t.mapping.maps[r],i;s.forEach((a,l,c,u)=>{i==null&&(i=u)}),t.setSelection(fe.near(t.doc.resolve(i),n))}const M0=1,Cl=2,_0=4;class IN extends E0{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.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(e){if(e.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=e,this.curSelectionFor=this.steps.length,this.updated=(this.updated|M0)&~Cl,this.storedMarks=null,this}get selectionSet(){return(this.updated&M0)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Cl,this}ensureMarks(e){return Ie.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&Cl)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~Cl,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Ie.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let o=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(o.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let i=this.doc.resolve(n);s=r==n?i.marks():i.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,o.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(fe.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,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|=_0,this}get scrolledIntoView(){return(this.updated&_0)>0}}function A0(t,e){return!e||!t?t:t.bind(e)}class Oi{constructor(e,n,r){this.name=e,this.init=A0(n.init,r),this.apply=A0(n.apply,r)}}const BN=[new Oi("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Oi("selection",{init(t,e){return t.selection||fe.atStart(e.doc)},apply(t){return t.selection}}),new Oi("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Oi("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class vd{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=BN.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Oi(r.key,r.spec.state,r))})}}class zs{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,n=-1){for(let r=0;r<this.config.plugins.length;r++)if(r!=n){let o=this.config.plugins[r];if(o.spec.filterTransaction&&!o.spec.filterTransaction.call(o,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let n=[e],r=this.applyInner(e),o=null;for(;;){let s=!1;for(let i=0;i<this.config.plugins.length;i++){let a=this.config.plugins[i];if(a.spec.appendTransaction){let l=o?o[i].n:0,c=o?o[i].state:this,u=l<n.length&&a.spec.appendTransaction.call(a,l?n.slice(l):n,c,r);if(u&&r.filterTransaction(u,i)){if(u.setMeta("appendedTransaction",e),!o){o=[];for(let d=0;d<this.config.plugins.length;d++)o.push(d<i?{state:r,n:n.length}:{state:this,n:0})}n.push(u),r=r.applyInner(u),s=!0}o&&(o[i]={state:r,n:n.length})}}if(!s)return{state:r,transactions:n}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new zs(this.config),r=this.config.fields;for(let o=0;o<r.length;o++){let s=r[o];n[s.name]=s.apply(e,this[s.name],this,n)}return n}get tr(){return new IN(this)}static create(e){let n=new vd(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new zs(n);for(let o=0;o<n.fields.length;o++)r[n.fields[o].name]=n.fields[o].init(e,r);return r}reconfigure(e){let n=new vd(this.schema,e.plugins),r=n.fields,o=new zs(n);for(let s=0;s<r.length;s++){let i=r[s].name;o[i]=this.hasOwnProperty(i)?this[i]:r[s].init(e,o)}return o}toJSON(e){let n={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(n.storedMarks=this.storedMarks.map(r=>r.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let o=e[r],s=o.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(o,this[o.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let o=new vd(e.schema,e.plugins),s=new zs(o);return o.fields.forEach(i=>{if(i.name=="doc")s.doc=Er.fromJSON(e.schema,n.doc);else if(i.name=="selection")s.selection=fe.fromJSON(s.doc,n.selection);else if(i.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let a in r){let l=r[a],c=l.spec.state;if(l.key==i.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(n,a)){s[i.name]=c.fromJSON.call(l,e,n[a],s);return}}s[i.name]=i.init(e,s)}}),s}}function I0(t,e,n){for(let r in t){let o=t[r];o instanceof Function?o=o.bind(e):r=="handleDOMEvents"&&(o=I0(o,e,{})),n[r]=o}return n}class at{constructor(e){this.spec=e,this.props={},e.props&&I0(e.props,this,this.props),this.key=e.key?e.key.key:B0("plugin")}getState(e){return e[this.key]}}const bd=Object.create(null);function B0(t){return t in bd?t+"$"+ ++bd[t]:(bd[t]=0,t+"$")}class Wt{constructor(e="key"){this.key=B0(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Sd=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function P0(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const N0=(t,e,n)=>{let r=P0(t,n);if(!r)return!1;let o=Ed(r);if(!o){let i=r.blockRange(),a=i&&Ns(i);return a==null?!1:(e&&e(t.tr.lift(i,a).scrollIntoView()),!0)}let s=o.nodeBefore;if(W0(t,o,e,-1))return!0;if(r.parent.content.size==0&&($s(s,"end")||re.isSelectable(s)))for(let i=r.depth;;i--){let a=Sl(t.doc,r.before(i),r.after(i),j.empty);if(a&&a.slice.size<a.to-a.from){if(e){let l=t.tr.step(a);l.setSelection($s(s,"end")?fe.findFrom(l.doc.resolve(l.mapping.map(o.pos,-1)),-1):re.create(l.doc,o.pos-s.nodeSize)),e(l.scrollIntoView())}return!0}if(i==1||r.node(i-1).childCount>1)break}return s.isAtom&&o.depth==r.depth-1?(e&&e(t.tr.delete(o.pos-s.nodeSize,o.pos).scrollIntoView()),!0):!1},PN=(t,e,n)=>{let r=P0(t,n);if(!r)return!1;let o=Ed(r);return o?D0(t,o,e):!1},NN=(t,e,n)=>{let r=R0(t,n);if(!r)return!1;let o=Cd(r);return o?D0(t,o,e):!1};function D0(t,e,n){let r=e.nodeBefore,o=r,s=e.pos-1;for(;!o.isTextblock;s--){if(o.type.spec.isolating)return!1;let u=o.lastChild;if(!u)return!1;o=u}let i=e.nodeAfter,a=i,l=e.pos+1;for(;!a.isTextblock;l++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let c=Sl(t.doc,s,l,j.empty);if(!c||c.from!=s||c instanceof mt&&c.slice.size>=l-s)return!1;if(n){let u=t.tr.step(c);u.setSelection(ue.create(u.doc,s)),n(u.scrollIntoView())}return!0}function $s(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const O0=(t,e,n)=>{let{$head:r,empty:o}=t.selection,s=r;if(!o)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=Ed(r)}let i=s&&s.nodeBefore;return!i||!re.isSelectable(i)?!1:(e&&e(t.tr.setSelection(re.create(t.doc,s.pos-i.nodeSize)).scrollIntoView()),!0)};function Ed(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function R0(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const z0=(t,e,n)=>{let r=R0(t,n);if(!r)return!1;let o=Cd(r);if(!o)return!1;let s=o.nodeAfter;if(W0(t,o,e,1))return!0;if(r.parent.content.size==0&&($s(s,"start")||re.isSelectable(s))){let i=Sl(t.doc,r.before(),r.after(),j.empty);if(i&&i.slice.size<i.to-i.from){if(e){let a=t.tr.step(i);a.setSelection($s(s,"start")?fe.findFrom(a.doc.resolve(a.mapping.map(o.pos)),1):re.create(a.doc,a.mapping.map(o.pos))),e(a.scrollIntoView())}return!0}}return s.isAtom&&o.depth==r.depth-1?(e&&e(t.tr.delete(o.pos,o.pos+s.nodeSize).scrollIntoView()),!0):!1},$0=(t,e,n)=>{let{$head:r,empty:o}=t.selection,s=r;if(!o)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;s=Cd(r)}let i=s&&s.nodeAfter;return!i||!re.isSelectable(i)?!1:(e&&e(t.tr.setSelection(re.create(t.doc,s.pos)).scrollIntoView()),!0)};function Cd(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let n=t.node(e);if(t.index(e)+1<n.childCount)return t.doc.resolve(t.after(e+1));if(n.type.spec.isolating)break}return null}const DN=(t,e)=>{let n=t.selection,r=n instanceof re,o;if(r){if(n.node.isTextblock||!Fo(t.doc,n.from))return!1;o=n.from}else if(o=bl(t.doc,n.from,-1),o==null)return!1;if(e){let s=t.tr.join(o);r&&s.setSelection(re.create(s.doc,o-t.doc.resolve(o).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},ON=(t,e)=>{let n=t.selection,r;if(n instanceof re){if(n.node.isTextblock||!Fo(t.doc,n.to))return!1;r=n.to}else if(r=bl(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},RN=(t,e)=>{let{$from:n,$to:r}=t.selection,o=n.blockRange(r),s=o&&Ns(o);return s==null?!1:(e&&e(t.tr.lift(o,s).scrollIntoView()),!0)},L0=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(`
74
- `).scrollIntoView()),!0)};function xd(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}const zN=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let o=n.node(-1),s=n.indexAfter(-1),i=xd(o.contentMatchAt(s));if(!i||!o.canReplaceWith(s,s,i))return!1;if(e){let a=n.after(),l=t.tr.replaceWith(a,a,i.createAndFill());l.setSelection(fe.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},F0=(t,e)=>{let n=t.selection,{$from:r,$to:o}=n;if(n instanceof dn||r.parent.inlineContent||o.parent.inlineContent)return!1;let s=xd(o.parent.contentMatchAt(o.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let i=(!r.parentOffset&&o.index()<o.parent.childCount?r:o).pos,a=t.tr.insert(i,s.createAndFill());a.setSelection(ue.create(a.doc,i+1)),e(a.scrollIntoView())}return!0},V0=(t,e)=>{let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let s=n.before();if(xr(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),o=r&&Ns(r);return o==null?!1:(e&&e(t.tr.lift(r,o).scrollIntoView()),!0)};function $N(t){return(e,n)=>{let{$from:r,$to:o}=e.selection;if(e.selection instanceof re&&e.selection.node.isBlock)return!r.parentOffset||!xr(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],i,a,l=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){l=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),a=xd(r.node(p-1).contentMatchAt(r.indexAfter(p-1))),s.unshift(l&&a?{type:a}:null),i=p;break}else{if(p==1)return!1;s.unshift(null)}let u=e.tr;(e.selection instanceof ue||e.selection instanceof dn)&&u.deleteSelection();let d=u.mapping.map(r.pos),h=xr(u.doc,d,s.length,s);if(h||(s[0]=a?{type:a}:null,h=xr(u.doc,d,s.length,s)),!h)return!1;if(u.split(d,s.length,s),!l&&c&&r.node(i).type!=a){let p=u.mapping.map(r.before(i)),m=u.doc.resolve(p);a&&r.node(i-1).canReplaceWith(m.index(),m.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(i)),a)}return n&&n(u.scrollIntoView()),!0}}const LN=$N(),FN=(t,e)=>{let{$from:n,to:r}=t.selection,o,s=n.sharedDepth(r);return s==0?!1:(o=n.before(s),e&&e(t.tr.setSelection(re.create(t.doc,o))),!0)};function VN(t,e,n){let r=e.nodeBefore,o=e.nodeAfter,s=e.index();return!r||!o||!r.type.compatibleContent(o.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(o.isTextblock||Fo(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function W0(t,e,n,r){let o=e.nodeBefore,s=e.nodeAfter,i,a,l=o.type.spec.isolating||s.type.spec.isolating;if(!l&&VN(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(i=(a=o.contentMatchAt(o.childCount)).findWrapping(s.type))&&a.matchType(i[0]||s.type).validEnd){if(n){let p=e.pos+s.nodeSize,m=D.empty;for(let w=i.length-1;w>=0;w--)m=D.from(i[w].create(null,m));m=D.from(o.copy(m));let g=t.tr.step(new gt(e.pos-1,p,e.pos,p,new j(m,1,0),i.length,!0)),y=g.doc.resolve(p+2*i.length);y.nodeAfter&&y.nodeAfter.type==o.type&&Fo(g.doc,y.pos)&&g.join(y.pos),n(g.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&l?null:fe.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),h=d&&Ns(d);if(h!=null&&h>=e.depth)return n&&n(t.tr.lift(d,h).scrollIntoView()),!0;if(c&&$s(s,"start",!0)&&$s(o,"end")){let p=o,m=[];for(;m.push(p),!p.isTextblock;)p=p.lastChild;let g=s,y=1;for(;!g.isTextblock;g=g.firstChild)y++;if(p.canReplace(p.childCount,p.childCount,g.content)){if(n){let w=D.empty;for(let b=m.length-1;b>=0;b--)w=D.from(m[b].copy(w));let k=t.tr.step(new gt(e.pos-m.length,e.pos+s.nodeSize,e.pos+y,e.pos+s.nodeSize-y,new j(w,m.length,0),0,!0));n(k.scrollIntoView())}return!0}}return!1}function U0(t){return function(e,n){let r=e.selection,o=t<0?r.$from:r.$to,s=o.depth;for(;o.node(s).isInline;){if(!s)return!1;s--}return o.node(s).isTextblock?(n&&n(e.tr.setSelection(ue.create(e.doc,t<0?o.start(s):o.end(s)))),!0):!1}}const WN=U0(-1),UN=U0(1);function HN(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s),a=i&&h0(i,t,e);return a?(r&&r(n.tr.wrap(i,a).scrollIntoView()),!0):!1}}function H0(t,e=null){return function(n,r){let o=!1;for(let s=0;s<n.selection.ranges.length&&!o;s++){let{$from:{pos:i},$to:{pos:a}}=n.selection.ranges[s];n.doc.nodesBetween(i,a,(l,c)=>{if(o)return!1;if(!(!l.isTextblock||l.hasMarkup(t,e)))if(l.type==t)o=!0;else{let u=n.doc.resolve(c),d=u.index();o=u.parent.canReplaceWith(d,d+1,t)}})}if(!o)return!1;if(r){let s=n.tr;for(let i=0;i<n.selection.ranges.length;i++){let{$from:{pos:a},$to:{pos:l}}=n.selection.ranges[i];s.setBlockType(a,l,t,e)}r(s.scrollIntoView())}return!0}}function Td(...t){return function(e,n,r){for(let o=0;o<t.length;o++)if(t[o](e,n,r))return!0;return!1}}Td(Sd,N0,O0),Td(Sd,z0,$0),Td(L0,F0,V0,LN),typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function jN(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s);if(!i)return!1;let a=r?n.tr:null;return ZN(a,i,t,e)?(r&&r(a.scrollIntoView()),!0):!1}}function ZN(t,e,n,r=null){let o=!1,s=e,i=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let l=i.resolve(e.start-2);s=new ml(l,l,e.depth),e.endIndex<e.parent.childCount&&(e=new ml(e.$from,i.resolve(e.$to.end(e.depth)),e.depth)),o=!0}let a=h0(s,n,r,e);return a?(t&&KN(t,e,a,o,n),!0):!1}function KN(t,e,n,r,o){let s=D.empty;for(let u=n.length-1;u>=0;u--)s=D.from(n[u].type.create(n[u].attrs,s));t.step(new gt(e.start-(r?2:0),e.end,e.start,e.end,new j(s,0,0),n.length,!0));let i=0;for(let u=0;u<n.length;u++)n[u].type==o&&(i=u+1);let a=n.length-i,l=e.start+n.length-(r?2:0),c=e.parent;for(let u=e.startIndex,d=e.endIndex,h=!0;u<d;u++,h=!1)!h&&xr(t.doc,l,a)&&(t.split(l,a),l+=2*a),l+=c.child(u).nodeSize;return t}function YN(t){return function(e,n){let{$from:r,$to:o}=e.selection,s=r.blockRange(o,i=>i.childCount>0&&i.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?qN(e,n,t,s):JN(e,n,s):!0:!1}}function qN(t,e,n,r){let o=t.tr,s=r.end,i=r.$to.end(r.depth);s<i&&(o.step(new gt(s-1,i,s,i,new j(D.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new ml(o.doc.resolve(r.$from.pos),o.doc.resolve(i),r.depth));const a=Ns(r);if(a==null)return!1;o.lift(r,a);let l=o.doc.resolve(o.mapping.map(s,-1)-1);return Fo(o.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&o.join(l.pos),e(o.scrollIntoView()),!0}function JN(t,e,n){let r=t.tr,o=n.parent;for(let p=n.end,m=n.endIndex-1,g=n.startIndex;m>g;m--)p-=o.child(m).nodeSize,r.delete(p-1,p+1);let s=r.doc.resolve(n.start),i=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let a=n.startIndex==0,l=n.endIndex==o.childCount,c=s.node(-1),u=s.index(-1);if(!c.canReplace(u+(a?0:1),u+1,i.content.append(l?D.empty:D.from(o))))return!1;let d=s.pos,h=d+i.nodeSize;return r.step(new gt(d-(a?1:0),h+(l?1:0),d+1,h-1,new j((a?D.empty:D.from(o.copy(D.empty))).append(l?D.empty:D.from(o.copy(D.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function XN(t){return function(e,n){let{$from:r,$to:o}=e.selection,s=r.blockRange(o,c=>c.childCount>0&&c.firstChild.type==t);if(!s)return!1;let i=s.startIndex;if(i==0)return!1;let a=s.parent,l=a.child(i-1);if(l.type!=t)return!1;if(n){let c=l.lastChild&&l.lastChild.type==a.type,u=D.from(c?t.create():null),d=new j(D.from(t.create(null,D.from(a.type.create(null,u)))),c?3:1,0),h=s.start,p=s.end;n(e.tr.step(new gt(h-(c?3:1),p,h,p,d,1,!0)).scrollIntoView())}return!0}}const _t=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Ls=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let Md=null;const Tr=function(t,e,n){let r=Md||(Md=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},GN=function(){Md=null},Vo=function(t,e,n,r){return n&&(j0(t,e,n,r,-1)||j0(t,e,n,r,1))},QN=/^(img|br|input|textarea|hr)$/i;function j0(t,e,n,r,o){for(var s;;){if(t==n&&e==r)return!0;if(e==(o<0?0:Sn(t))){let i=t.parentNode;if(!i||i.nodeType!=1||Ri(t)||QN.test(t.nodeName)||t.contentEditable=="false")return!1;e=_t(t)+(o<0?0:1),t=i}else if(t.nodeType==1){let i=t.childNodes[e+(o<0?-1:0)];if(i.nodeType==1&&i.contentEditable=="false")if(!((s=i.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=o;else return!1;else t=i,e=o<0?Sn(t):0}else return!1}}function Sn(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function eD(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=Sn(t)}else if(t.parentNode&&!Ri(t))e=_t(t),t=t.parentNode;else return null}}function tD(t,e){for(;;){if(t.nodeType==3&&e<t.nodeValue.length)return t;if(t.nodeType==1&&e<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[e],e=0}else if(t.parentNode&&!Ri(t))e=_t(t)+1,t=t.parentNode;else return null}}function nD(t,e,n){for(let r=e==0,o=e==Sn(t);r||o;){if(t==n)return!0;let s=_t(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,o=o&&s==Sn(t)}}function Ri(t){let e;for(let n=t;n&&!(e=n.pmViewDesc);n=n.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}const xl=function(t){return t.focusNode&&Vo(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Wo(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function rD(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function oD(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(Sn(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(Sn(r.startContainer),r.startOffset)}}}const nr=typeof navigator<"u"?navigator:null,Z0=typeof document<"u"?document:null,no=nr&&nr.userAgent||"",_d=/Edge\/(\d+)/.exec(no),K0=/MSIE \d/.exec(no),Ad=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(no),Qt=!!(K0||Ad||_d),ro=K0?document.documentMode:Ad?+Ad[1]:_d?+_d[1]:0,En=!Qt&&/gecko\/(\d+)/i.test(no);En&&+(/Firefox\/(\d+)/.exec(no)||[0,0])[1];const Id=!Qt&&/Chrome\/(\d+)/.exec(no),yt=!!Id,Y0=Id?+Id[1]:0,At=!Qt&&!!nr&&/Apple Computer/.test(nr.vendor),Fs=At&&(/Mobile\/\w+/.test(no)||!!nr&&nr.maxTouchPoints>2),Cn=Fs||(nr?/Mac/.test(nr.platform):!1),q0=nr?/Win/.test(nr.platform):!1,Mr=/Android \d/.test(no),zi=!!Z0&&"webkitFontSmoothing"in Z0.documentElement.style,sD=zi?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function iD(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function _r(t,e){return typeof t=="number"?t:t[e]}function aD(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function J0(t,e,n){let r=t.someProp("scrollThreshold")||0,o=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let i=n||t.dom;i;){if(i.nodeType!=1){i=Ls(i);continue}let a=i,l=a==s.body,c=l?iD(s):aD(a),u=0,d=0;if(e.top<c.top+_r(r,"top")?d=-(c.top-e.top+_r(o,"top")):e.bottom>c.bottom-_r(r,"bottom")&&(d=e.bottom-e.top>c.bottom-c.top?e.top+_r(o,"top")-c.top:e.bottom-c.bottom+_r(o,"bottom")),e.left<c.left+_r(r,"left")?u=-(c.left-e.left+_r(o,"left")):e.right>c.right-_r(r,"right")&&(u=e.right-c.right+_r(o,"right")),u||d)if(l)s.defaultView.scrollBy(u,d);else{let p=a.scrollLeft,m=a.scrollTop;d&&(a.scrollTop+=d),u&&(a.scrollLeft+=u);let g=a.scrollLeft-p,y=a.scrollTop-m;e={left:e.left-g,top:e.top-y,right:e.right-g,bottom:e.bottom-y}}let h=l?"fixed":getComputedStyle(i).position;if(/^(fixed|sticky)$/.test(h))break;i=h=="absolute"?i.offsetParent:Ls(i)}}function lD(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,o;for(let s=(e.left+e.right)/2,i=n+1;i<Math.min(innerHeight,e.bottom);i+=5){let a=t.root.elementFromPoint(s,i);if(!a||a==t.dom||!t.dom.contains(a))continue;let l=a.getBoundingClientRect();if(l.top>=n-20){r=a,o=l.top;break}}return{refDOM:r,refTop:o,stack:X0(t.dom)}}function X0(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Ls(r));return e}function cD({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;G0(n,r==0?0:r-e)}function G0(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:o,left:s}=t[n];r.scrollTop!=o+e&&(r.scrollTop=o+e),r.scrollLeft!=s&&(r.scrollLeft=s)}}let Vs=null;function uD(t){if(t.setActive)return t.setActive();if(Vs)return t.focus(Vs);let e=X0(t);t.focus(Vs==null?{get preventScroll(){return Vs={preventScroll:!0},!0}}:void 0),Vs||(Vs=!1,G0(e,0))}function Q0(t,e){let n,r=2e8,o,s=0,i=e.top,a=e.top,l,c;for(let u=t.firstChild,d=0;u;u=u.nextSibling,d++){let h;if(u.nodeType==1)h=u.getClientRects();else if(u.nodeType==3)h=Tr(u).getClientRects();else continue;for(let p=0;p<h.length;p++){let m=h[p];if(m.top<=i&&m.bottom>=a){i=Math.max(m.bottom,i),a=Math.min(m.top,a);let g=m.left>e.left?m.left-e.left:m.right<e.left?e.left-m.right:0;if(g<r){n=u,r=g,o=g&&n.nodeType==3?{left:m.right<e.left?m.right:m.left,top:e.top}:e,u.nodeType==1&&g&&(s=d+(e.left>=(m.left+m.right)/2?1:0));continue}}else m.top>e.top&&!l&&m.left<=e.left&&m.right>=e.left&&(l=u,c={left:Math.max(m.left,Math.min(m.right,e.left)),top:m.top});!n&&(e.left>=m.right&&e.top>=m.top||e.left>=m.left&&e.top>=m.bottom)&&(s=d+1)}}return!n&&l&&(n=l,o=c,r=0),n&&n.nodeType==3?dD(n,o):!n||r&&n.nodeType==1?{node:t,offset:s}:Q0(n,o)}function dD(t,e){let n=t.nodeValue.length,r=document.createRange(),o;for(let s=0;s<n;s++){r.setEnd(t,s+1),r.setStart(t,s);let i=oo(r,1);if(i.top!=i.bottom&&Bd(e,i)){o={node:t,offset:s+(e.left>=(i.left+i.right)/2?1:0)};break}}return r.detach(),o||{node:t,offset:0}}function Bd(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function fD(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function hD(t,e,n){let{node:r,offset:o}=Q0(e,n),s=-1;if(r.nodeType==1&&!r.firstChild){let i=r.getBoundingClientRect();s=i.left!=i.right&&n.left>(i.left+i.right)/2?1:-1}return t.docView.posFromDOM(r,o,s)}function pD(t,e,n,r){let o=-1;for(let s=e,i=!1;s!=t.dom;){let a=t.docView.nearestDesc(s,!0),l;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((l=a.dom.getBoundingClientRect()).width||l.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!i&&l.left>r.left||l.top>r.top?o=a.posBefore:(!i&&l.right<r.left||l.bottom<r.top)&&(o=a.posAfter),i=!0),!a.contentDOM&&o<0&&!a.node.isText))return(a.node.isBlock?r.top<(l.top+l.bottom)/2:r.left<(l.left+l.right)/2)?a.posBefore:a.posAfter;s=a.dom.parentNode}return o>-1?o:t.docView.posFromDOM(e,n,-1)}function ew(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let o=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),s=o;;){let i=t.childNodes[s];if(i.nodeType==1){let a=i.getClientRects();for(let l=0;l<a.length;l++){let c=a[l];if(Bd(e,c))return ew(i,e,c)}}if((s=(s+1)%r)==o)break}return t}function mD(t,e){let n=t.dom.ownerDocument,r,o=0,s=oD(n,e.left,e.top);s&&({node:r,offset:o}=s);let i=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top),a;if(!i||!t.dom.contains(i.nodeType!=1?i.parentNode:i)){let c=t.dom.getBoundingClientRect();if(!Bd(e,c)||(i=ew(t.dom,e,c),!i))return null}if(At)for(let c=i;r&&c;c=Ls(c))c.draggable&&(r=void 0);if(i=fD(i,e),r){if(En&&r.nodeType==1&&(o=Math.min(o,r.childNodes.length),o<r.childNodes.length)){let u=r.childNodes[o],d;u.nodeName=="IMG"&&(d=u.getBoundingClientRect()).right<=e.left&&d.bottom>e.top&&o++}let c;zi&&o&&r.nodeType==1&&(c=r.childNodes[o-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&o--,r==t.dom&&o==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?a=t.state.doc.content.size:(o==0||r.nodeType!=1||r.childNodes[o-1].nodeName!="BR")&&(a=pD(t,r,o,e))}a==null&&(a=hD(t,i,e));let l=t.docView.nearestDesc(i,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function tw(t){return t.top<t.bottom||t.left<t.right}function oo(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(tw(r))return r}return Array.prototype.find.call(n,tw)||t.getBoundingClientRect()}const gD=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function nw(t,e,n){let{node:r,offset:o,atom:s}=t.docView.domFromPos(e,n<0?-1:1),i=zi||En;if(r.nodeType==3)if(i&&(gD.test(r.nodeValue)||(n<0?!o:o==r.nodeValue.length))){let l=oo(Tr(r,o,o),n);if(En&&o&&/\s/.test(r.nodeValue[o-1])&&o<r.nodeValue.length){let c=oo(Tr(r,o-1,o-1),-1);if(c.top==l.top){let u=oo(Tr(r,o,o+1),-1);if(u.top!=l.top)return $i(u,u.left<c.left)}}return l}else{let l=o,c=o,u=n<0?1:-1;return n<0&&!o?(c++,u=-1):n>=0&&o==r.nodeValue.length?(l--,u=1):n<0?l--:c++,$i(oo(Tr(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&o&&(n<0||o==Sn(r))){let l=r.childNodes[o-1];if(l.nodeType==1)return Pd(l.getBoundingClientRect(),!1)}if(s==null&&o<Sn(r)){let l=r.childNodes[o];if(l.nodeType==1)return Pd(l.getBoundingClientRect(),!0)}return Pd(r.getBoundingClientRect(),n>=0)}if(s==null&&o&&(n<0||o==Sn(r))){let l=r.childNodes[o-1],c=l.nodeType==3?Tr(l,Sn(l)-(i?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return $i(oo(c,1),!1)}if(s==null&&o<Sn(r)){let l=r.childNodes[o];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?Tr(l,0,i?0:1):l.nodeType==1?l:null:null;if(c)return $i(oo(c,-1),!0)}return $i(oo(r.nodeType==3?Tr(r):r,-n),n>=0)}function $i(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Pd(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function rw(t,e,n){let r=t.state,o=t.root.activeElement;r!=e&&t.updateState(e),o!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),o!=t.dom&&o&&o.focus()}}function yD(t,e,n){let r=e.selection,o=n=="up"?r.$from:r.$to;return rw(t,e,()=>{let{node:s}=t.docView.domFromPos(o.pos,n=="up"?-1:1);for(;;){let a=t.docView.nearestDesc(s,!0);if(!a)break;if(a.node.isBlock){s=a.contentDOM||a.dom;break}s=a.dom.parentNode}let i=nw(t,o.pos,1);for(let a=s.firstChild;a;a=a.nextSibling){let l;if(a.nodeType==1)l=a.getClientRects();else if(a.nodeType==3)l=Tr(a,0,a.nodeValue.length).getClientRects();else continue;for(let c=0;c<l.length;c++){let u=l[c];if(u.bottom>u.top+1&&(n=="up"?i.top-u.top>(u.bottom-i.top)*2:u.bottom-i.bottom>(i.bottom-u.top)*2))return!1}}return!0})}const wD=/[\u0590-\u08ac]/;function kD(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let o=r.parentOffset,s=!o,i=o==r.parent.content.size,a=t.domSelection();return a?!wD.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?s:i:rw(t,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:d}=t.domSelectionRange(),h=a.caretBidiLevel;a.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:m,focusOffset:g}=t.domSelectionRange(),y=m&&!p.contains(m.nodeType==1?m:m.parentNode)||l==m&&c==g;try{a.collapse(u,d),l&&(l!=u||c!=d)&&a.extend&&a.extend(l,c)}catch{}return h!=null&&(a.caretBidiLevel=h),y}):r.pos==r.start()||r.pos==r.end()}let ow=null,sw=null,iw=!1;function vD(t,e,n){return ow==e&&sw==n?iw:(ow=e,sw=n,iw=n=="up"||n=="down"?yD(t,e,n):kD(t,e,n))}const xn=0,aw=1,Uo=2,rr=3;class Li{constructor(e,n,r,o){this.parent=e,this.children=n,this.dom=r,this.contentDOM=o,this.dirty=xn,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n<this.children.length;n++)e+=this.children[n].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let n=0,r=this.posAtStart;;n++){let o=this.children[n];if(o==e)return r;r+=o.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,n,r){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(r<0){let s,i;if(e==this.contentDOM)s=e.childNodes[n-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.previousSibling}for(;s&&!((i=s.pmViewDesc)&&i.parent==this);)s=s.previousSibling;return s?this.posBeforeChild(i)+i.size:this.posAtStart}else{let s,i;if(e==this.contentDOM)s=e.childNodes[n];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.nextSibling}for(;s&&!((i=s.pmViewDesc)&&i.parent==this);)s=s.nextSibling;return s?this.posBeforeChild(i):this.posAtEnd}let o;if(e==this.dom&&this.contentDOM)o=n>_t(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))o=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){o=!1;break}if(s.previousSibling)break}if(o==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){o=!0;break}if(s.nextSibling)break}}return o??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,o=e;o;o=o.parentNode){let s=this.getDesc(o),i;if(s&&(!n||s.node))if(r&&(i=s.nodeDOM)&&!(i.nodeType==1?i.contains(e.nodeType==1?e:e.parentNode):i==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let o=e;o;o=o.parentNode){let s=this.getDesc(o);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;n<this.children.length;n++){let o=this.children[n],s=r+o.size;if(r==e&&s!=r){for(;!o.border&&o.children.length;)for(let i=0;i<o.children.length;i++){let a=o.children[i];if(a.size){o=a;break}}return o}if(e<s)return o.descAt(e-r-o.border);r=s}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,o=0;for(let s=0;r<this.children.length;r++){let i=this.children[r],a=s+i.size;if(a>e||i instanceof uw){o=e-s;break}s=a}if(o)return this.children[r].domFromPos(o-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof lw&&s.side>=0;r--);if(n<=0){let s,i=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,i=!1);return s&&n&&i&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?_t(s.dom)+1:0}}else{let s,i=!0;for(;s=r<this.children.length?this.children[r]:null,!(!s||s.dom.parentNode==this.contentDOM);r++,i=!1);return s&&i&&!s.border&&!s.domAtom?s.domFromPos(0,n):{node:this.contentDOM,offset:s?_t(s.dom):this.contentDOM.childNodes.length}}}parseRange(e,n,r=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:n,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let o=-1,s=-1;for(let i=r,a=0;;a++){let l=this.children[a],c=i+l.size;if(o==-1&&e<=c){let u=i+l.border;if(e>=u&&n<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(e,n,u);e=i;for(let d=a;d>0;d--){let h=this.children[d-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){o=_t(h.dom)+1;break}e-=h.size}o==-1&&(o=0)}if(o>-1&&(c>n||a==this.children.length-1)){n=c;for(let u=a+1;u<this.children.length;u++){let d=this.children[u];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(-1)){s=_t(d.dom);break}n+=d.size}s==-1&&(s=this.contentDOM.childNodes.length);break}i=c}return{node:this.contentDOM,from:e,to:n,fromOffset:o,toOffset:s}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let n=this.children[e<0?0:this.children.length-1];return n.size==0||n.emptyChildAt(e)}domAfterPos(e){let{node:n,offset:r}=this.domFromPos(e,0);if(n.nodeType!=1||r==n.childNodes.length)throw new RangeError("No node after pos "+e);return n.childNodes[r]}setSelection(e,n,r,o=!1){let s=Math.min(e,n),i=Math.max(e,n);for(let p=0,m=0;p<this.children.length;p++){let g=this.children[p],y=m+g.size;if(s>m&&i<y)return g.setSelection(e-m-g.border,n-m-g.border,r,o);m=y}let a=this.domFromPos(e,e?-1:1),l=n==e?a:this.domFromPos(n,n?-1:1),c=r.root.getSelection(),u=r.domSelectionRange(),d=!1;if((En||At)&&e==n){let{node:p,offset:m}=a;if(p.nodeType==3){if(d=!!(m&&p.nodeValue[m-1]==`
75
- `),d&&m==p.nodeValue.length)for(let g=p,y;g;g=g.parentNode){if(y=g.nextSibling){y.nodeName=="BR"&&(a=l={node:y.parentNode,offset:_t(y)+1});break}let w=g.pmViewDesc;if(w&&w.node&&w.node.isBlock)break}}else{let g=p.childNodes[m-1];d=g&&(g.nodeName=="BR"||g.contentEditable=="false")}}if(En&&u.focusNode&&u.focusNode!=l.node&&u.focusNode.nodeType==1){let p=u.focusNode.childNodes[u.focusOffset];p&&p.contentEditable=="false"&&(o=!0)}if(!(o||d&&At)&&Vo(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Vo(l.node,l.offset,u.focusNode,u.focusOffset))return;let h=!1;if((c.extend||e==n)&&!(d&&En)){c.collapse(a.node,a.offset);try{e!=n&&c.extend(l.node,l.offset),h=!0}catch{}}if(!h){if(e>n){let m=a;a=l,l=m}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(a.node,a.offset),c.removeAllRanges(),c.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,n){for(let r=0,o=0;o<this.children.length;o++){let s=this.children[o],i=r+s.size;if(r==i?e<=i&&n>=r:e<i&&n>r){let a=r+s.border,l=i-s.border;if(e>=a&&n<=l){this.dirty=e==r||n==i?Uo:aw,e==a&&n==l&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=rr:s.markDirty(e-a,n-a);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Uo:rr}r=i}this.dirty=Uo}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Uo:aw;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class lw extends Li{constructor(e,n,r,o){let s,i=n.type.toDOM;if(typeof i=="function"&&(i=i(r,()=>{if(!s)return o;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(i.nodeType!=1){let a=document.createElement("span");a.appendChild(i),i=a}i.contentEditable="false",i.classList.add("ProseMirror-widget")}super(e,[],i,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==xn&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(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 ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class bD extends Li{constructor(e,n,r,o){super(e,[],n,null),this.textDOM=r,this.text=o}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Ho extends Li{constructor(e,n,r,o,s){super(e,[],r,o),this.mark=n,this.spec=s}static create(e,n,r,o){let s=o.nodeViews[n.type.name],i=s&&s(n,o,r);return(!i||!i.dom)&&(i=$o.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Ho(e,n,i.dom,i.contentDOM||i.dom,i)}parseRule(){return this.dirty&rr||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=rr&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=xn){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=xn}}slice(e,n,r){let o=Ho.create(this.parent,this.mark,!0,r),s=this.children,i=this.size;n<i&&(s=Dd(s,n,i,r)),e>0&&(s=Dd(s,0,e,r));for(let a=0;a<s.length;a++)s[a].parent=o;return o.children=s,o}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class so extends Li{constructor(e,n,r,o,s,i,a,l,c){super(e,[],s,i),this.node=n,this.outerDeco=r,this.innerDeco=o,this.nodeDOM=a}static create(e,n,r,o,s,i){let a=s.nodeViews[n.type.name],l,c=a&&a(n,s,()=>{if(!l)return i;if(l.parent)return l.parent.posBeforeChild(l)},r,o),u=c&&c.dom,d=c&&c.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:d}=$o.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!d&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let h=u;return u=hw(u,r,n),c?l=new SD(e,n,r,o,u,d||null,h,c,s,i+1):n.isText?new Tl(e,n,r,o,u,h,s):new so(e,n,r,o,u,d||null,h,s,i+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 n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>D.empty)}return e}matchesNode(e,n,r){return this.dirty==xn&&e.eq(this.node)&&Ml(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,o=n,s=e.composing?this.localCompositionInfo(e,n):null,i=s&&s.pos>-1?s:null,a=s&&s.pos<0,l=new CD(this,i&&i.node,e);MD(this.node,this.innerDeco,(c,u,d)=>{c.spec.marks?l.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!d&&l.syncToMarks(u==this.node.childCount?Ie.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,o)},(c,u,d,h)=>{l.syncToMarks(c.marks,r,e,h);let p;l.findNodeMatch(c,u,d,h)||a&&e.state.selection.from>o&&e.state.selection.to<o+c.nodeSize&&(p=l.findIndexWithChild(s.node))>-1&&l.updateNodeAt(c,u,d,p,e)||l.updateNextNode(c,u,d,e,h,o)||l.addNode(c,u,d,e,o),o+=c.nodeSize}),l.syncToMarks([],r,e,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==Uo)&&(i&&this.protectLocalComposition(e,i),dw(this.contentDOM,this.children,e),Fs&&_D(this.dom))}localCompositionInfo(e,n){let{from:r,to:o}=e.state.selection;if(!(e.state.selection instanceof ue)||r<n||o>n+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 i=s.nodeValue,a=AD(this.node.content,i,r-n,o-n);return a<0?null:{node:s,pos:a,text:i}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:o}){if(this.getDesc(n))return;let s=n;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 i=new bD(this,s,n,o);e.input.compositionNodes.push(i),this.children=Dd(this.children,r,r+o.length,e,i)}update(e,n,r,o){return this.dirty==rr||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,o),!0)}updateInner(e,n,r,o){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(o,this.posAtStart),this.dirty=xn}updateOuterDeco(e){if(Ml(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=fw(this.dom,this.nodeDOM,Nd(this.outerDeco,this.node,n),Nd(e,this.node,n)),this.dom!=r&&(r.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.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function cw(t,e,n,r,o){hw(r,e,t);let s=new so(void 0,t,e,n,r,r,r,o,0);return s.contentDOM&&s.updateChildren(o,0),s}class Tl extends so{constructor(e,n,r,o,s,i,a){super(e,n,r,o,s,null,i,a,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,o){return this.dirty==rr||this.dirty!=xn&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=xn||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,o.trackWrites==this.nodeDOM&&(o.trackWrites=null)),this.node=e,this.dirty=xn,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let o=this.node.cut(e,n),s=document.createTextNode(o.text);return new Tl(this.parent,o,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=rr)}get domAtom(){return!1}isText(e){return this.node.text==e}}class uw extends Li{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==xn&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class SD extends so{constructor(e,n,r,o,s,i,a,l,c,u){super(e,n,r,o,s,i,a,c,u),this.spec=l}update(e,n,r,o){if(this.dirty==rr)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,o),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,o)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,o){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,o)}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 dw(t,e,n){let r=t.firstChild,o=!1;for(let s=0;s<e.length;s++){let i=e[s],a=i.dom;if(a.parentNode==t){for(;a!=r;)r=pw(r),o=!0;r=r.nextSibling}else o=!0,t.insertBefore(a,r);if(i instanceof Ho){let l=r?r.previousSibling:t.lastChild;dw(i.contentDOM,i.children,n),r=l?l.nextSibling:t.firstChild}}for(;r;)r=pw(r),o=!0;o&&n.trackWrites==t&&(n.trackWrites=null)}const Fi=function(t){t&&(this.nodeName=t)};Fi.prototype=Object.create(null);const jo=[new Fi];function Nd(t,e,n){if(t.length==0)return jo;let r=n?jo[0]:new Fi,o=[r];for(let s=0;s<t.length;s++){let i=t[s].type.attrs;if(i){i.nodeName&&o.push(r=new Fi(i.nodeName));for(let a in i){let l=i[a];l!=null&&(n&&o.length==1&&o.push(r=new Fi(e.isInline?"span":"div")),a=="class"?r.class=(r.class?r.class+" ":"")+l:a=="style"?r.style=(r.style?r.style+";":"")+l:a!="nodeName"&&(r[a]=l))}}}return o}function fw(t,e,n,r){if(n==jo&&r==jo)return e;let o=e;for(let s=0;s<r.length;s++){let i=r[s],a=n[s];if(s){let l;a&&a.nodeName==i.nodeName&&o!=t&&(l=o.parentNode)&&l.nodeName.toLowerCase()==i.nodeName||(l=document.createElement(i.nodeName),l.pmIsDeco=!0,l.appendChild(o),a=jo[0]),o=l}ED(o,a||jo[0],i)}return o}function ED(t,e,n){for(let r in e)r!="class"&&r!="style"&&r!="nodeName"&&!(r in n)&&t.removeAttribute(r);for(let r in n)r!="class"&&r!="style"&&r!="nodeName"&&n[r]!=e[r]&&t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],o=n.class?n.class.split(" ").filter(Boolean):[];for(let s=0;s<r.length;s++)o.indexOf(r[s])==-1&&t.classList.remove(r[s]);for(let s=0;s<o.length;s++)r.indexOf(o[s])==-1&&t.classList.add(o[s]);t.classList.length==0&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,o;for(;o=r.exec(e.style);)t.style.removeProperty(o[1])}n.style&&(t.style.cssText+=n.style)}}function hw(t,e,n){return fw(t,t,jo,Nd(e,n,t.nodeType!=1))}function Ml(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].type.eq(e[n].type))return!1;return!0}function pw(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class CD{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=xD(e.node.content,e)}destroyBetween(e,n){if(e!=n){for(let r=e;r<n;r++)this.top.children[r].destroy();this.top.children.splice(e,n-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,n,r,o){let s=0,i=this.stack.length>>1,a=Math.min(i,e.length);for(;s<a&&(s==i-1?this.top:this.stack[s+1<<1]).matchesMark(e[s])&&e[s].type.spec.spanning!==!1;)s++;for(;s<i;)this.destroyRest(),this.top.dirty=xn,this.index=this.stack.pop(),this.top=this.stack.pop(),i--;for(;i<e.length;){this.stack.push(this.top,this.index+1);let l=-1,c=this.top.children.length;o<this.preMatch.index&&(c=Math.min(this.index+3,c));for(let u=this.index;u<c;u++){let d=this.top.children[u];if(d.matchesMark(e[i])&&!this.isLocked(d.dom)){l=u;break}}if(l>-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let u=Ho.create(this.top,e[i],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,i++}}findNodeMatch(e,n,r,o){let s=-1,i;if(o>=this.preMatch.index&&(i=this.preMatch.matches[o-this.preMatch.index]).parent==this.top&&i.matchesNode(e,n,r))s=this.top.children.indexOf(i,this.index);else for(let a=this.index,l=Math.min(this.top.children.length,a+5);a<l;a++){let c=this.top.children[a];if(c.matchesNode(e,n,r)&&!this.preMatch.matched.has(c)){s=a;break}}return s<0?!1:(this.destroyBetween(this.index,s),this.index++,!0)}updateNodeAt(e,n,r,o,s){let i=this.top.children[o];return i.dirty==rr&&i.dom==i.contentDOM&&(i.dirty=Uo),i.update(e,n,r,s)?(this.destroyBetween(this.index,o),this.index++,!0):!1}findIndexWithChild(e){for(;;){let n=e.parentNode;if(!n)return-1;if(n==this.top.contentDOM){let r=e.pmViewDesc;if(r){for(let o=this.index;o<this.top.children.length;o++)if(this.top.children[o]==r)return o}return-1}e=n}}updateNextNode(e,n,r,o,s,i){for(let a=this.index;a<this.top.children.length;a++){let l=this.top.children[a];if(l instanceof so){let c=this.preMatch.matched.get(l);if(c!=null&&c!=s)return!1;let u=l.dom,d,h=this.isLocked(u)&&!(e.isText&&l.node&&l.node.isText&&l.nodeDOM.nodeValue==e.text&&l.dirty!=rr&&Ml(n,l.outerDeco));if(!h&&l.update(e,n,r,o))return this.destroyBetween(this.index,a),l.dom!=u&&(this.changed=!0),this.index++,!0;if(!h&&(d=this.recreateWrapper(l,e,n,r,o,i)))return this.destroyBetween(this.index,a),this.top.children[this.index]=d,d.contentDOM&&(d.dirty=Uo,d.updateChildren(o,i+1),d.dirty=xn),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,r,o,s,i){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!Ml(r,e.outerDeco)||!o.eq(e.innerDeco))return null;let a=so.create(this.top,n,r,o,s,i);if(a.contentDOM){a.children=e.children,e.children=[];for(let l of a.children)l.parent=a}return e.destroy(),a}addNode(e,n,r,o,s){let i=so.create(this.top,e,n,r,o,s);i.contentDOM&&i.updateChildren(o,s+1),this.top.children.splice(this.index++,0,i),this.changed=!0}placeWidget(e,n,r){let o=this.index<this.top.children.length?this.top.children[this.index]:null;if(o&&o.matchesWidget(e)&&(e==o.widget||!o.widget.type.toDOM.parentNode))this.index++;else{let s=new lw(this.top,e,n,r);this.top.children.splice(this.index++,0,s),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],n=this.top;for(;e instanceof Ho;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof Tl)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((At||yt)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",n),this.addHackNode("BR",this.top))}addHackNode(e,n){if(n==this.top&&this.index<n.children.length&&n.children[this.index].matchesHack(e))this.index++;else{let r=document.createElement(e);e=="IMG"&&(r.className="ProseMirror-separator",r.alt=""),e=="BR"&&(r.className="ProseMirror-trailingBreak");let o=new uw(this.top,[],r,null);n!=this.top?n.children.push(o):n.children.splice(this.index++,0,o),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function xD(t,e){let n=e,r=n.children.length,o=t.childCount,s=new Map,i=[];e:for(;o>0;){let a;for(;;)if(r){let c=n.children[r-1];if(c instanceof Ho)n=c,r=c.children.length;else{a=c,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let l=a.node;if(l){if(l!=t.child(o-1))break;--o,s.set(a,o),i.push(a)}}return{index:o,matched:s,matches:i.reverse()}}function TD(t,e){return t.type.side-e.type.side}function MD(t,e,n,r){let o=e.locals(t),s=0;if(o.length==0){for(let c=0;c<t.childCount;c++){let u=t.child(c);r(u,o,e.forChild(s,u),c),s+=u.nodeSize}return}let i=0,a=[],l=null;for(let c=0;;){let u,d;for(;i<o.length&&o[i].to==s;){let y=o[i++];y.widget&&(u?(d||(d=[u])).push(y):u=y)}if(u)if(d){d.sort(TD);for(let y=0;y<d.length;y++)n(d[y],c,!!l)}else n(u,c,!!l);let h,p;if(l)p=-1,h=l,l=null;else if(c<t.childCount)p=c,h=t.child(c++);else break;for(let y=0;y<a.length;y++)a[y].to<=s&&a.splice(y--,1);for(;i<o.length&&o[i].from<=s&&o[i].to>s;)a.push(o[i++]);let m=s+h.nodeSize;if(h.isText){let y=m;i<o.length&&o[i].from<y&&(y=o[i].from);for(let w=0;w<a.length;w++)a[w].to<y&&(y=a[w].to);y<m&&(l=h.cut(y-s),h=h.cut(0,y-s),m=y,p=-1)}else for(;i<o.length&&o[i].to<m;)i++;let g=h.isInline&&!h.isLeaf?a.filter(y=>!y.inline):a.slice();r(h,g,e.forChild(s,h),p),s=m}}function _D(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function AD(t,e,n,r){for(let o=0,s=0;o<t.childCount&&s<=r;){let i=t.child(o++),a=s;if(s+=i.nodeSize,!i.isText)continue;let l=i.text;for(;o<t.childCount;){let c=t.child(o++);if(s+=c.nodeSize,!c.isText)break;l+=c.text}if(s>=n){if(s>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let c=a<r?l.lastIndexOf(e,r-a-1):-1;if(c>=0&&c+e.length+a>=n)return a+c;if(n==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}function Dd(t,e,n,r,o){let s=[];for(let i=0,a=0;i<t.length;i++){let l=t[i],c=a,u=a+=l.size;c>=n||u<=e?s.push(l):(c<e&&s.push(l.slice(0,e-c,r)),o&&(s.push(o),o=void 0),u>n&&s.push(l.slice(n-c,l.size,r)))}return s}function Od(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let o=t.docView.nearestDesc(n.focusNode),s=o&&o.size==0,i=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(i<0)return null;let a=r.resolve(i),l,c;if(xl(n)){for(l=i;o&&!o.node;)o=o.parent;let d=o.node;if(o&&d.isAtom&&re.isSelectable(d)&&o.parent&&!(d.isInline&&nD(n.focusNode,n.focusOffset,o.dom))){let h=o.posBefore;c=new re(i==h?a:r.resolve(h))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let d=i,h=i;for(let p=0;p<n.rangeCount;p++){let m=n.getRangeAt(p);d=Math.min(d,t.docView.posFromDOM(m.startContainer,m.startOffset,1)),h=Math.max(h,t.docView.posFromDOM(m.endContainer,m.endOffset,-1))}if(d<0)return null;[l,i]=h==t.state.selection.anchor?[h,d]:[d,h],a=r.resolve(i)}else l=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(l<0)return null}let u=r.resolve(l);if(!c){let d=e=="pointer"||t.state.selection.head<a.pos&&!s?1:-1;c=zd(t,u,a,d)}return c}function mw(t){return t.editable?t.hasFocus():Sw(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function Ar(t,e=!1){let n=t.state.selection;if(kw(t,n),!!mw(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&yt){let r=t.domSelectionRange(),o=t.domObserver.currentSelection;if(r.anchorNode&&o.anchorNode&&Vo(r.anchorNode,r.anchorOffset,o.anchorNode,o.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)BD(t);else{let{anchor:r,head:o}=n,s,i;gw&&!(n instanceof ue)&&(n.$from.parent.inlineContent||(s=yw(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(i=yw(t,n.to))),t.docView.setSelection(r,o,t,e),gw&&(s&&ww(s),i&&ww(i)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&ID(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const gw=At||yt&&Y0<63;function yw(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),o=r<n.childNodes.length?n.childNodes[r]:null,s=r?n.childNodes[r-1]:null;if(At&&o&&o.contentEditable=="false")return Rd(o);if((!o||o.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(o)return Rd(o);if(s)return Rd(s)}}function Rd(t){return t.contentEditable="true",At&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function ww(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function ID(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,o=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=o)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!mw(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function BD(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,_t(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&Qt&&ro<=11&&(n.disabled=!0,n.disabled=!1)}function kw(t,e){if(e instanceof re){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(vw(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else vw(t)}function vw(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function zd(t,e,n,r){return t.someProp("createSelectionBetween",o=>o(t,e,n))||ue.between(e,n,r)}function bw(t){return t.editable&&!t.hasFocus()?!1:Sw(t)}function Sw(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function PD(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Vo(e.node,e.offset,n.anchorNode,n.anchorOffset)}function $d(t,e){let{$anchor:n,$head:r}=t.selection,o=e>0?n.max(r):n.min(r),s=o.parent.inlineContent?o.depth?t.doc.resolve(e>0?o.after():o.before()):null:o;return s&&fe.findFrom(s,e)}function io(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function Ew(t,e,n){let r=t.state.selection;if(r instanceof ue)if(n.indexOf("s")>-1){let{$head:o}=r,s=o.textOffset?null:e<0?o.nodeBefore:o.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let i=t.state.doc.resolve(o.pos+s.nodeSize*(e<0?-1:1));return io(t,new ue(r.$anchor,i))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let o=$d(t.state,e);return o&&o instanceof re?io(t,o):!1}else if(!(Cn&&n.indexOf("m")>-1)){let o=r.$head,s=o.textOffset?null:e<0?o.nodeBefore:o.nodeAfter,i;if(!s||s.isText)return!1;let a=e<0?o.pos-s.nodeSize:o.pos;return s.isAtom||(i=t.docView.descAt(a))&&!i.contentDOM?re.isSelectable(s)?io(t,new re(e<0?t.state.doc.resolve(o.pos-s.nodeSize):o)):zi?io(t,new ue(t.state.doc.resolve(e<0?a:a+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof re&&r.node.isInline)return io(t,new ue(e>0?r.$to:r.$from));{let o=$d(t.state,e);return o?io(t,o):!1}}}function _l(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function Vi(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Ws(t,e){return e<0?ND(t):DD(t)}function ND(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,s,i=!1;for(En&&n.nodeType==1&&r<_l(n)&&Vi(n.childNodes[r],-1)&&(i=!0);;)if(r>0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(Vi(a,-1))o=n,s=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(Cw(n))break;{let a=n.previousSibling;for(;a&&Vi(a,-1);)o=n.parentNode,s=_t(a),a=a.previousSibling;if(a)n=a,r=_l(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}i?Ld(t,n,r):o&&Ld(t,o,s)}function DD(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o=_l(n),s,i;for(;;)if(r<o){if(n.nodeType!=1)break;let a=n.childNodes[r];if(Vi(a,1))s=n,i=++r;else break}else{if(Cw(n))break;{let a=n.nextSibling;for(;a&&Vi(a,1);)s=a.parentNode,i=_t(a)+1,a=a.nextSibling;if(a)n=a,r=0,o=_l(n);else{if(n=n.parentNode,n==t.dom)break;r=o=0}}}s&&Ld(t,s,i)}function Cw(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function OD(t,e){for(;t&&e==t.childNodes.length&&!Ri(t);)e=_t(t)+1,t=t.parentNode;for(;t&&e<t.childNodes.length;){let n=t.childNodes[e];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=0}}function RD(t,e){for(;t&&!e&&!Ri(t);)e=_t(t),t=t.parentNode;for(;t&&e;){let n=t.childNodes[e-1];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=t.childNodes.length}}function Ld(t,e,n){if(e.nodeType!=3){let s,i;(i=OD(e,n))?(e=i,n=0):(s=RD(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(xl(r)){let s=document.createRange();s.setEnd(e,n),s.setStart(e,n),r.removeAllRanges(),r.addRange(s)}else r.extend&&r.extend(e,n);t.domObserver.setCurSelection();let{state:o}=t;setTimeout(()=>{t.state==o&&Ar(t)},50)}function xw(t,e){let n=t.state.doc.resolve(e);if(!(yt||q0)&&n.parent.inlineContent){let o=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),i=(s.top+s.bottom)/2;if(i>o.top&&i<o.bottom&&Math.abs(s.left-o.left)>1)return s.left<o.left?"ltr":"rtl"}if(e<n.end()){let s=t.coordsAtPos(e+1),i=(s.top+s.bottom)/2;if(i>o.top&&i<o.bottom&&Math.abs(s.left-o.left)>1)return s.left>o.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function Tw(t,e,n){let r=t.state.selection;if(r instanceof ue&&!r.empty||n.indexOf("s")>-1||Cn&&n.indexOf("m")>-1)return!1;let{$from:o,$to:s}=r;if(!o.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let i=$d(t.state,e);if(i&&i instanceof re)return io(t,i)}if(!o.parent.inlineContent){let i=e<0?o:s,a=r instanceof dn?fe.near(i,e):fe.findFrom(i,e);return a?io(t,a):!1}return!1}function Mw(t,e){if(!(t.state.selection instanceof ue))return!0;let{$head:n,$anchor:r,empty:o}=t.state.selection;if(!n.sameParent(r))return!0;if(!o)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let i=t.state.tr;return e<0?i.delete(n.pos-s.nodeSize,n.pos):i.delete(n.pos,n.pos+s.nodeSize),t.dispatch(i),!0}return!1}function _w(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function zD(t){if(!At||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;_w(t,r,"true"),setTimeout(()=>_w(t,r,"false"),20)}return!1}function $D(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function LD(t,e){let n=e.keyCode,r=$D(e);if(n==8||Cn&&n==72&&r=="c")return Mw(t,-1)||Ws(t,-1);if(n==46&&!e.shiftKey||Cn&&n==68&&r=="c")return Mw(t,1)||Ws(t,1);if(n==13||n==27)return!0;if(n==37||Cn&&n==66&&r=="c"){let o=n==37?xw(t,t.state.selection.from)=="ltr"?-1:1:-1;return Ew(t,o,r)||Ws(t,o)}else if(n==39||Cn&&n==70&&r=="c"){let o=n==39?xw(t,t.state.selection.from)=="ltr"?1:-1:1;return Ew(t,o,r)||Ws(t,o)}else{if(n==38||Cn&&n==80&&r=="c")return Tw(t,-1,r)||Ws(t,-1);if(n==40||Cn&&n==78&&r=="c")return zD(t)||Tw(t,1,r)||Ws(t,1);if(r==(Cn?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function Fd(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:o,openEnd:s}=e;for(;o>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){o--,s--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let i=t.someProp("clipboardSerializer")||$o.fromSchema(t.state.schema),a=Rw(),l=a.createElement("div");l.appendChild(i.serializeFragment(r,{document:a}));let c=l.firstChild,u,d=0;for(;c&&c.nodeType==1&&(u=Dw[c.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let m=a.createElement(u[p]);for(;l.firstChild;)m.appendChild(l.firstChild);l.appendChild(m),d++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${o} ${s}${d?` -${d}`:""} ${JSON.stringify(n)}`);let h=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,`
76
-
77
- `);return{dom:l,text:h,slice:e}}function Aw(t,e,n,r,o){let s=o.parent.type.spec.code,i,a;if(!n&&!e)return null;let l=!!e&&(r||s||!n);if(l){if(t.someProp("transformPastedText",h=>{e=h(e,s||r,t)}),s)return a=new j(D.from(t.state.schema.text(e.replace(/\r\n?/g,`
78
- `))),0,0),t.someProp("transformPasted",h=>{a=h(a,t,!0)}),a;let d=t.someProp("clipboardTextParser",h=>h(e,o,r,t));if(d)a=d;else{let h=o.marks(),{schema:p}=t.state,m=$o.fromSchema(p);i=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(g=>{let y=i.appendChild(document.createElement("p"));g&&y.appendChild(m.serializeNode(p.text(g,h)))})}}else t.someProp("transformPastedHTML",d=>{n=d(n,t)}),i=UD(n),zi&&HD(i);let c=i&&i.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let d=+u[3];d>0;d--){let h=i.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;i=h}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||Cr.fromSchema(t.state.schema)).parseSlice(i,{preserveWhitespace:!!(l||u),context:o,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!FD.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)a=jD(Nw(a,+u[1],+u[2]),u[4]);else if(a=j.maxOpen(VD(a.content,o),!0),a.openStart||a.openEnd){let d=0,h=0;for(let p=a.content.firstChild;d<a.openStart&&!p.type.spec.isolating;d++,p=p.firstChild);for(let p=a.content.lastChild;h<a.openEnd&&!p.type.spec.isolating;h++,p=p.lastChild);a=Nw(a,d,h)}return t.someProp("transformPasted",d=>{a=d(a,t,l)}),a}const FD=/^(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 VD(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let o=e.node(n).contentMatchAt(e.index(n)),s,i=[];if(t.forEach(a=>{if(!i)return;let l=o.findWrapping(a.type),c;if(!l)return i=null;if(c=i.length&&s.length&&Bw(l,s,a,i[i.length-1],0))i[i.length-1]=c;else{i.length&&(i[i.length-1]=Pw(i[i.length-1],s.length));let u=Iw(a,l);i.push(u),o=o.matchType(u.type),s=l}}),i)return D.from(i)}return t}function Iw(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,D.from(t));return t}function Bw(t,e,n,r,o){if(o<t.length&&o<e.length&&t[o]==e[o]){let s=Bw(t,e,n,r.lastChild,o+1);if(s)return r.copy(r.content.replaceChild(r.childCount-1,s));if(r.contentMatchAt(r.childCount).matchType(o==t.length-1?n.type:t[o+1]))return r.copy(r.content.append(D.from(Iw(n,t,o+1))))}}function Pw(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,Pw(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(D.empty,!0);return t.copy(n.append(r))}function Vd(t,e,n,r,o,s){let i=e<0?t.firstChild:t.lastChild,a=i.content;return t.childCount>1&&(s=0),o<r-1&&(a=Vd(a,e,n,r,o+1,s)),o>=n&&(a=e<0?i.contentMatchAt(0).fillBefore(a,s<=o).append(a):a.append(i.contentMatchAt(i.childCount).fillBefore(D.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,i.copy(a))}function Nw(t,e,n){return e<t.openStart&&(t=new j(Vd(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new j(Vd(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Dw={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};let Ow=null;function Rw(){return Ow||(Ow=document.implementation.createHTMLDocument("title"))}let Wd=null;function WD(t){let e=window.trustedTypes;return e?(Wd||(Wd=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),Wd.createHTML(t)):t}function UD(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Rw().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),o;if((o=r&&Dw[r[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=WD(t),o)for(let s=0;s<o.length;s++)n=n.querySelector(o[s])||n;return n}function HD(t){let e=t.querySelectorAll(yt?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent==" "&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function jD(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:o,openStart:s,openEnd:i}=t;for(let a=r.length-2;a>=0;a-=2){let l=n.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;o=D.from(l.create(r[a+1],o)),s++,i++}return new j(o,s,i)}const Ut={},Ht={},ZD={touchstart:!0,touchmove:!0};class KD{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},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.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function YD(t){for(let e in Ut){let n=Ut[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{JD(t,r)&&!Hd(t,r)&&(t.editable||!(r.type in Ht))&&n(t,r)},ZD[e]?{passive:!0}:void 0)}At&&t.dom.addEventListener("input",()=>null),Ud(t)}function ao(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function qD(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function Ud(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>Hd(t,r))})}function Hd(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function JD(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function XD(t,e){!Hd(t,e)&&Ut[e.type]&&(t.editable||!(e.type in Ht))&&Ut[e.type](t,e)}Ht.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!$w(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Mr&&yt&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Fs&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",o=>o(t,Wo(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||LD(t,n)?n.preventDefault():ao(t,"key")},Ht.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)},Ht.keypress=(t,e)=>{let n=e;if($w(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Cn&&n.metaKey)return;if(t.someProp("handleKeyPress",o=>o(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof ue)||!r.$from.sameParent(r.$to)){let o=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(o).scrollIntoView();!/[\r\n]/.test(o)&&!t.someProp("handleTextInput",i=>i(t,r.$from.pos,r.$to.pos,o,s))&&t.dispatch(s()),n.preventDefault()}};function Al(t){return{left:t.clientX,top:t.clientY}}function GD(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function jd(t,e,n,r,o){if(r==-1)return!1;let s=t.state.doc.resolve(r);for(let i=s.depth+1;i>0;i--)if(t.someProp(e,a=>i>s.depth?a(t,n,s.nodeAfter,s.before(i),o,!0):a(t,n,s.node(i),s.before(i),o,!1)))return!0;return!1}function Us(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function QD(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&re.isSelectable(r)?(Us(t,new re(n)),!0):!1}function eO(t,e){if(e==-1)return!1;let n=t.state.selection,r,o;n instanceof re&&(r=n.node);let s=t.state.doc.resolve(e);for(let i=s.depth+1;i>0;i--){let a=i>s.depth?s.nodeAfter:s.node(i);if(re.isSelectable(a)){r&&n.$from.depth>0&&i>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?o=s.before(n.$from.depth):o=s.before(i);break}}return o!=null?(Us(t,re.create(t.state.doc,o)),!0):!1}function tO(t,e,n,r,o){return jd(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(o?eO(t,n):QD(t,n))}function nO(t,e,n,r){return jd(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",o=>o(t,e,r))}function rO(t,e,n,r){return jd(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",o=>o(t,e,r))||oO(t,n,r)}function oO(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(Us(t,ue.create(r,0,r.content.size)),!0):!1;let o=r.resolve(e);for(let s=o.depth+1;s>0;s--){let i=s>o.depth?o.nodeAfter:o.node(s),a=o.before(s);if(i.inlineContent)Us(t,ue.create(r,a+1,a+1+i.content.size));else if(re.isSelectable(i))Us(t,re.create(r,a));else continue;return!0}}function Zd(t){return Il(t)}const zw=Cn?"metaKey":"ctrlKey";Ut.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Zd(t),o=Date.now(),s="singleClick";o-t.input.lastClick.time<500&&GD(n,t.input.lastClick)&&!n[zw]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:o,x:n.clientX,y:n.clientY,type:s,button:n.button};let i=t.posAtCoords(Al(n));i&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new sO(t,i,n,!!r)):(s=="doubleClick"?nO:rO)(t,i.pos,i.inside,n)?n.preventDefault():ao(t,"pointer"))};class sO{constructor(e,n,r,o){this.view=e,this.pos=n,this.event=r,this.flushed=o,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[zw],this.allowDefault=r.shiftKey;let s,i;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),i=n.inside;else{let u=e.state.doc.resolve(n.pos);s=u.parent,i=u.depth?u.before():0}const a=o?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof re&&c.from<=i&&c.to>i)&&(this.mightDrag={node:s,pos:i,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&En&&!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)),ao(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(()=>Ar(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Al(e))),this.updateAllowDefault(e),this.allowDefault||!n?ao(this.view,"pointer"):tO(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||At&&this.mightDrag&&!this.mightDrag.node.isAtom||yt&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(Us(this.view,fe.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):ao(this.view,"pointer")}move(e){this.updateAllowDefault(e),ao(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)}}Ut.touchstart=t=>{t.input.lastTouch=Date.now(),Zd(t),ao(t,"pointer")},Ut.touchmove=t=>{t.input.lastTouch=Date.now(),ao(t,"pointer")},Ut.contextmenu=t=>Zd(t);function $w(t,e){return t.composing?!0:At&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const iO=Mr?5e3:-1;Ht.compositionstart=Ht.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof ue&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||yt&&q0&&aO(t)))t.markCursor=t.state.storedMarks||n.marks(),Il(t,!0),t.markCursor=null;else if(Il(t,!e.selection.empty),En&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let o=r.focusNode,s=r.focusOffset;o&&o.nodeType==1&&s!=0;){let i=s<0?o.lastChild:o.childNodes[s-1];if(!i)break;if(i.nodeType==3){let a=t.domSelection();a&&a.collapse(i,i.nodeValue.length);break}else o=i,s=-1}}t.input.composing=!0}Lw(t,iO)};function aO(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Ht.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,Lw(t,20))};function Lw(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Il(t),e))}function Fw(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=cO());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function lO(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=eD(e.focusNode,e.focusOffset),r=tD(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let o=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!o||!o.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let i=n.pmViewDesc;if(!(!i||!i.isText(n.nodeValue)))return r}}return n||r}function cO(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function Il(t,e=!1){if(!(Mr&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),Fw(t),e||t.docView&&t.docView.dirty){let n=Od(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function uO(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),o=document.createRange();o.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(o),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const Wi=Qt&&ro<15||Fs&&sD<604;Ut.copy=Ht.cut=(t,e)=>{let n=e,r=t.state.selection,o=n.type=="cut";if(r.empty)return;let s=Wi?null:n.clipboardData,i=r.content(),{dom:a,text:l}=Fd(t,i);s?(n.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",l)):uO(t,a),o&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function dO(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function fO(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let o=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?Ui(t,r.value,null,o,e):Ui(t,r.textContent,r.innerHTML,o,e)},50)}function Ui(t,e,n,r,o){let s=Aw(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,o,s||j.empty)))return!0;if(!s)return!1;let i=dO(s),a=i?t.state.tr.replaceSelectionWith(i,r):t.state.tr.replaceSelection(s);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Vw(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Ht.paste=(t,e)=>{let n=e;if(t.composing&&!Mr)return;let r=Wi?null:n.clipboardData,o=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Ui(t,Vw(r),r.getData("text/html"),o,n)?n.preventDefault():fO(t,n)};class Ww{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const hO=Cn?"altKey":"ctrlKey";function Uw(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[hO]}Ut.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let o=t.state.selection,s=o.empty?null:t.posAtCoords(Al(n)),i;if(!(s&&s.pos>=o.from&&s.pos<=(o instanceof re?o.to-1:o.to))){if(r&&r.mightDrag)i=re.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let d=t.docView.nearestDesc(n.target,!0);d&&d.node.type.spec.draggable&&d!=t.docView&&(i=re.create(t.state.doc,d.posBefore))}}let a=(i||t.state.selection).content(),{dom:l,text:c,slice:u}=Fd(t,a);(!n.dataTransfer.files.length||!yt||Y0>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Wi?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Wi||n.dataTransfer.setData("text/plain",c),t.dragging=new Ww(u,Uw(t,n),i)},Ut.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)},Ht.dragover=Ht.dragenter=(t,e)=>e.preventDefault(),Ht.drop=(t,e)=>{try{pO(t,e,t.dragging)}finally{t.dragging=null}};function pO(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Al(e));if(!r)return;let o=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",p=>{s=p(s,t,!1)}):s=Aw(t,Vw(e.dataTransfer),Wi?null:e.dataTransfer.getData("text/html"),!1,o);let i=!!(n&&Uw(t,e));if(t.someProp("handleDrop",p=>p(t,e,s||j.empty,i))){e.preventDefault();return}if(!s)return;e.preventDefault();let a=s?w0(t.state.doc,o.pos,s):o.pos;a==null&&(a=o.pos);let l=t.state.tr;if(i){let{node:p}=n;p?p.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,d=l.doc;if(u?l.replaceRangeWith(c,c,s.content.firstChild):l.replaceRange(c,c,s),l.doc.eq(d))return;let h=l.doc.resolve(c);if(u&&re.isSelectable(s.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(s.content.firstChild))l.setSelection(new re(h));else{let p=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((m,g,y,w)=>p=w),l.setSelection(zd(t,h,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}Ut.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Ar(t)},20))},Ut.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)},Ut.beforeinput=(t,e)=>{if(yt&&Mr&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,Wo(8,"Backspace")))))return;let{$cursor:o}=t.state.selection;o&&o.pos>0&&t.dispatch(t.state.tr.delete(o.pos-1,o.pos).scrollIntoView())},50)}};for(let t in Ht)Ut[t]=Ht[t];function Hi(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class Bl{constructor(e,n){this.toDOM=e,this.spec=n||Zo,this.side=this.spec.side||0}map(e,n,r,o){let{pos:s,deleted:i}=e.mapResult(n.from+o,this.side<0?-1:1);return i?null:new jt(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof Bl&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Hi(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class lo{constructor(e,n){this.attrs=e,this.spec=n||Zo}map(e,n,r,o){let s=e.map(n.from+o,this.spec.inclusiveStart?-1:1)-r,i=e.map(n.to+o,this.spec.inclusiveEnd?1:-1)-r;return s>=i?null:new jt(s,i,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof lo&&Hi(this.attrs,e.attrs)&&Hi(this.spec,e.spec)}static is(e){return e.type instanceof lo}destroy(){}}class Kd{constructor(e,n){this.attrs=e,this.spec=n||Zo}map(e,n,r,o){let s=e.mapResult(n.from+o,1);if(s.deleted)return null;let i=e.mapResult(n.to+o,-1);return i.deleted||i.pos<=s.pos?null:new jt(s.pos-r,i.pos-r,this)}valid(e,n){let{index:r,offset:o}=e.content.findIndex(n.from),s;return o==n.from&&!(s=e.child(r)).isText&&o+s.nodeSize==n.to}eq(e){return this==e||e instanceof Kd&&Hi(this.attrs,e.attrs)&&Hi(this.spec,e.spec)}destroy(){}}class jt{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new jt(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new jt(e,e,new Bl(n,r))}static inline(e,n,r,o){return new jt(e,n,new lo(r,o))}static node(e,n,r,o){return new jt(e,n,new Kd(r,o))}get spec(){return this.type.spec}get inline(){return this.type instanceof lo}get widget(){return this.type instanceof Bl}}const Hs=[],Zo={};class Ue{constructor(e,n){this.local=e.length?e:Hs,this.children=n.length?n:Hs}static create(e,n){return n.length?Pl(n,e,0,Zo):Rt}find(e,n,r){let o=[];return this.findInner(e??0,n??1e9,o,0,r),o}findInner(e,n,r,o,s){for(let i=0;i<this.local.length;i++){let a=this.local[i];a.from<=n&&a.to>=e&&(!s||s(a.spec))&&r.push(a.copy(a.from+o,a.to+o))}for(let i=0;i<this.children.length;i+=3)if(this.children[i]<n&&this.children[i+1]>e){let a=this.children[i]+1;this.children[i+2].findInner(e-a,n-a,r,o+a,s)}}map(e,n,r){return this==Rt||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Zo)}mapInner(e,n,r,o,s){let i;for(let a=0;a<this.local.length;a++){let l=this.local[a].map(e,r,o);l&&l.type.valid(n,l)?(i||(i=[])).push(l):s.onRemove&&s.onRemove(this.local[a].spec)}return this.children.length?mO(this.children,i||[],e,n,r,o,s):i?new Ue(i.sort(Ko),Hs):Rt}add(e,n){return n.length?this==Rt?Ue.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let o,s=0;e.forEach((a,l)=>{let c=l+r,u;if(u=jw(n,a,c)){for(o||(o=this.children.slice());s<o.length&&o[s]<l;)s+=3;o[s]==l?o[s+2]=o[s+2].addInner(a,u,c+1):o.splice(s,0,l,l+a.nodeSize,Pl(u,a,c+1,Zo)),s+=3}});let i=Hw(s?Zw(n):n,-r);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||i.splice(a--,1);return new Ue(i.length?this.local.concat(i).sort(Ko):this.local,o||this.children)}remove(e){return e.length==0||this==Rt?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,o=this.local;for(let s=0;s<r.length;s+=3){let i,a=r[s]+n,l=r[s+1]+n;for(let u=0,d;u<e.length;u++)(d=e[u])&&d.from>a&&d.to<l&&(e[u]=null,(i||(i=[])).push(d));if(!i)continue;r==this.children&&(r=this.children.slice());let c=r[s+2].removeInner(i,a+1);c!=Rt?r[s+2]=c:(r.splice(s,3),s-=3)}if(o.length){for(let s=0,i;s<e.length;s++)if(i=e[s])for(let a=0;a<o.length;a++)o[a].eq(i,n)&&(o==this.local&&(o=this.local.slice()),o.splice(a--,1))}return r==this.children&&o==this.local?this:o.length||r.length?new Ue(o,r):Rt}forChild(e,n){if(this==Rt)return this;if(n.isLeaf)return Ue.empty;let r,o;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(r=this.children[a+2]);break}let s=e+1,i=s+n.content.size;for(let a=0;a<this.local.length;a++){let l=this.local[a];if(l.from<i&&l.to>s&&l.type instanceof lo){let c=Math.max(s,l.from)-s,u=Math.min(i,l.to)-s;c<u&&(o||(o=[])).push(l.copy(c,u))}}if(o){let a=new Ue(o.sort(Ko),Hs);return r?new co([a,r]):a}return r||Rt}eq(e){if(this==e)return!0;if(!(e instanceof Ue)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(e.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=e.children[n]||this.children[n+1]!=e.children[n+1]||!this.children[n+2].eq(e.children[n+2]))return!1;return!0}locals(e){return Yd(this.localsInner(e))}localsInner(e){if(this==Rt)return Hs;if(e.inlineContent||!this.local.some(lo.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof lo||n.push(this.local[r]);return n}forEachSet(e){e(this)}}Ue.empty=new Ue([],[]),Ue.removeOverlap=Yd;const Rt=Ue.empty;class co{constructor(e){this.members=e}map(e,n){const r=this.members.map(o=>o.map(e,n,Zo));return co.from(r)}forChild(e,n){if(n.isLeaf)return Ue.empty;let r=[];for(let o=0;o<this.members.length;o++){let s=this.members[o].forChild(e,n);s!=Rt&&(s instanceof co?r=r.concat(s.members):r.push(s))}return co.from(r)}eq(e){if(!(e instanceof co)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let o=0;o<this.members.length;o++){let s=this.members[o].localsInner(e);if(s.length)if(!n)n=s;else{r&&(n=n.slice(),r=!1);for(let i=0;i<s.length;i++)n.push(s[i])}}return n?Yd(r?n:n.sort(Ko)):Hs}static from(e){switch(e.length){case 0:return Rt;case 1:return e[0];default:return new co(e.every(n=>n instanceof Ue)?e:e.reduce((n,r)=>n.concat(r instanceof Ue?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function mO(t,e,n,r,o,s,i){let a=t.slice();for(let c=0,u=s;c<n.maps.length;c++){let d=0;n.maps[c].forEach((h,p,m,g)=>{let y=g-m-(p-h);for(let w=0;w<a.length;w+=3){let k=a[w+1];if(k<0||h>k+u-d)continue;let b=a[w]+u-d;p>=b?a[w+1]=h<=b?-2:-1:h>=u&&y&&(a[w]+=y,a[w+1]+=y)}d+=y}),u=n.maps[c].map(u,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(a[c+1]==-2){l=!0,a[c+1]=-1;continue}let u=n.map(t[c]+s),d=u-o;if(d<0||d>=r.content.size){l=!0;continue}let h=n.map(t[c+1]+s,-1),p=h-o,{index:m,offset:g}=r.content.findIndex(d),y=r.maybeChild(m);if(y&&g==d&&g+y.nodeSize==p){let w=a[c+2].mapInner(n,y,u+1,t[c]+s+1,i);w!=Rt?(a[c]=d,a[c+1]=p,a[c+2]=w):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=gO(a,t,e,n,o,s,i),u=Pl(c,r,0,i);e=u.local;for(let d=0;d<a.length;d+=3)a[d+1]<0&&(a.splice(d,3),d-=3);for(let d=0,h=0;d<u.children.length;d+=3){let p=u.children[d];for(;h<a.length&&a[h]<p;)h+=3;a.splice(h,0,u.children[d],u.children[d+1],u.children[d+2])}}return new Ue(e.sort(Ko),a)}function Hw(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let o=t[r];n.push(new jt(o.from+e,o.to+e,o.type))}return n}function gO(t,e,n,r,o,s,i){function a(l,c){for(let u=0;u<l.local.length;u++){let d=l.local[u].map(r,o,c);d?n.push(d):i.onRemove&&i.onRemove(l.local[u].spec)}for(let u=0;u<l.children.length;u+=3)a(l.children[u+2],l.children[u]+c+1)}for(let l=0;l<t.length;l+=3)t[l+1]==-1&&a(t[l+2],e[l]+s+1);return n}function jw(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,o=null;for(let s=0,i;s<t.length;s++)(i=t[s])&&i.from>n&&i.to<r&&((o||(o=[])).push(i),t[s]=null);return o}function Zw(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Pl(t,e,n,r){let o=[],s=!1;e.forEach((a,l)=>{let c=jw(t,a,l+n);if(c){s=!0;let u=Pl(c,a,n+l+1,r);u!=Rt&&o.push(l,l+a.nodeSize,u)}});let i=Hw(s?Zw(t):t,-n).sort(Ko);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||(r.onRemove&&r.onRemove(i[a].spec),i.splice(a--,1));return i.length||o.length?new Ue(i,o):Rt}function Ko(t,e){return t.from-e.from||t.to-e.to}function Yd(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let o=n+1;o<e.length;o++){let s=e[o];if(s.from==r.from){s.to!=r.to&&(e==t&&(e=t.slice()),e[o]=s.copy(s.from,r.to),Kw(e,o+1,s.copy(r.to,s.to)));continue}else{s.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,s.from),Kw(e,o,r.copy(s.from,r.to)));break}}}return e}function Kw(t,e,n){for(;e<t.length&&Ko(n,t[e])>0;)e++;t.splice(e,0,n)}function qd(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Rt&&e.push(r)}),t.cursorWrapper&&e.push(Ue.create(t.state.doc,[t.cursorWrapper.deco])),co.from(e)}const yO={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},wO=Qt&&ro<=11;class kO{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 vO{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new kO,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let o=0;o<r.length;o++)this.queue.push(r[o]);Qt&&ro<=11&&r.some(o=>o.type=="childList"&&o.removedNodes.length||o.type=="characterData"&&o.oldValue.length>o.target.nodeValue.length)?this.flushSoon():At&&e.composing&&r.some(o=>o.type=="childList"&&o.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),wO&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.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,yO)),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 n=0;n<e.length;n++)this.queue.push(e[n]);window.setTimeout(()=>this.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(bw(this.view)){if(this.suppressingSelectionUpdates)return Ar(this.view);if(Qt&&ro<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Vo(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 n=new Set,r;for(let s=e.focusNode;s;s=Ls(s))n.add(s);for(let s=e.anchorNode;s;s=Ls(s))if(n.has(s)){r=s;break}let o=r&&this.view.docView.nearestDesc(r);if(o&&o.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))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 n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),o=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&bw(e)&&!this.ignoreSelectionChange(r),s=-1,i=-1,a=!1,l=[];if(e.editable)for(let u=0;u<n.length;u++){let d=this.registerMutation(n[u],l);d&&(s=s<0?d.from:Math.min(d.from,s),i=i<0?d.to:Math.max(d.to,i),d.typeOver&&(a=!0))}if(En&&l.length){let u=l.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,h]=u;d.parentNode&&d.parentNode.parentNode==h.parentNode?h.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let h of u){let p=h.parentNode;p&&p.nodeName=="LI"&&(!d||EO(e,d)!=p)&&h.remove()}}}else if((yt||At)&&l.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let d=u.nextSibling;d&&d.nodeType==1&&d.contentEditable=="false"&&u.parentNode.removeChild(u)}}let c=null;s<0&&o&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&xl(r)&&(c=Od(e))&&c.eq(fe.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Ar(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||o)&&(s>-1&&(e.docView.markDirty(s,i),bO(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,CO(e,l)),this.handleDOMChange(s,i,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Ar(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let d=e.addedNodes[u];n.push(d),d.nodeType==3&&(this.lastChangedTextNode=d)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let o=e.previousSibling,s=e.nextSibling;if(Qt&&ro<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:d,nextSibling:h}=e.addedNodes[u];(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(o=d),(!h||Array.prototype.indexOf.call(e.addedNodes,h)<0)&&(s=h)}let i=o&&o.parentNode==e.target?_t(o)+1:0,a=r.localPosFromDOM(e.target,i,-1),l=s&&s.parentNode==e.target?_t(s):e.target.childNodes.length,c=r.localPosFromDOM(e.target,l,1);return{from:a,to:c}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let Yw=new WeakMap,qw=!1;function bO(t){if(!Yw.has(t)&&(Yw.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=En,qw)return;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."),qw=!0}}function Jw(t,e){let n=e.startContainer,r=e.startOffset,o=e.endContainer,s=e.endOffset,i=t.domAtPos(t.state.selection.anchor);return Vo(i.node,i.offset,o,s)&&([n,r,o,s]=[o,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:o,focusOffset:s}}function SO(t,e){if(e.getComposedRanges){let o=e.getComposedRanges(t.root)[0];if(o)return Jw(t,o)}let n;function r(o){o.preventDefault(),o.stopImmediatePropagation(),n=o.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?Jw(t,n):null}function EO(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function CO(t,e){var n;let{focusNode:r,focusOffset:o}=t.domSelectionRange();for(let s of e)if(((n=s.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let i=s.nextSibling;for(;i&&i.nodeName!="TD"&&i.nodeName!="TH";)i=i.nextSibling;if(i){let a=i;for(;;){let l=a.firstChild;if(!l||l.nodeType!=1||l.contentEditable=="false"||/^(BR|IMG)$/.test(l.nodeName))break;a=l}a.insertBefore(s,a.firstChild),r==s&&t.domSelection().collapse(s,o)}else s.parentNode.removeChild(s)}}function xO(t,e,n){let{node:r,fromOffset:o,toOffset:s,from:i,to:a}=t.docView.parseRange(e,n),l=t.domSelectionRange(),c,u=l.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(c=[{node:u,offset:l.anchorOffset}],xl(l)||c.push({node:l.focusNode,offset:l.focusOffset})),yt&&t.input.lastKeyCode===8)for(let y=s;y>o;y--){let w=r.childNodes[y-1],k=w.pmViewDesc;if(w.nodeName=="BR"&&!k){s=y;break}if(!k||k.size)break}let d=t.state.doc,h=t.someProp("domParser")||Cr.fromSchema(t.state.schema),p=d.resolve(i),m=null,g=h.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:o,to:s,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:TO,context:p});if(c&&c[0].pos!=null){let y=c[0].pos,w=c[1]&&c[1].pos;w==null&&(w=y),m={anchor:y+i,head:w+i}}return{doc:g,sel:m,from:i,to:a}}function TO(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(At&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||At&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const MO=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function _O(t,e,n,r,o){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let T=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,A=Od(t,T);if(A&&!t.state.selection.eq(A)){if(yt&&Mr&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",$=>$(t,Wo(13,"Enter"))))return;let P=t.state.tr.setSelection(A);T=="pointer"?P.setMeta("pointer",!0):T=="key"&&P.scrollIntoView(),s&&P.setMeta("composition",s),t.dispatch(P)}return}let i=t.state.doc.resolve(e),a=i.sharedDepth(n);e=i.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l=t.state.selection,c=xO(t,e,n),u=t.state.doc,d=u.slice(c.from,c.to),h,p;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(h=t.state.selection.to,p="end"):(h=t.state.selection.from,p="start"),t.input.lastKeyCode=null;let m=BO(d.content,c.doc.content,c.from,h,p);if(m&&t.input.domChangeCount++,(Fs&&t.input.lastIOSEnter>Date.now()-225||Mr)&&o.some(T=>T.nodeType==1&&!MO.test(T.nodeName))&&(!m||m.endA>=m.endB)&&t.someProp("handleKeyDown",T=>T(t,Wo(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!m)if(r&&l instanceof ue&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))m={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let T=Xw(t,t.state.doc,c.sel);if(T&&!T.eq(t.state.selection)){let A=t.state.tr.setSelection(T);s&&A.setMeta("composition",s),t.dispatch(A)}}return}t.state.selection.from<t.state.selection.to&&m.start==m.endB&&t.state.selection instanceof ue&&(m.start>t.state.selection.from&&m.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?m.start=t.state.selection.from:m.endA<t.state.selection.to&&m.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(m.endB+=t.state.selection.to-m.endA,m.endA=t.state.selection.to)),Qt&&ro<=11&&m.endB==m.start+1&&m.endA==m.start&&m.start>c.from&&c.doc.textBetween(m.start-c.from-1,m.start-c.from+1)=="  "&&(m.start--,m.endA--,m.endB--);let g=c.doc.resolveNoCache(m.start-c.from),y=c.doc.resolveNoCache(m.endB-c.from),w=u.resolve(m.start),k=g.sameParent(y)&&g.parent.inlineContent&&w.end()>=m.endA;if((Fs&&t.input.lastIOSEnter>Date.now()-225&&(!k||o.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!k&&g.pos<c.doc.content.size&&(!g.sameParent(y)||!g.parent.inlineContent)&&g.pos<y.pos&&!/\S/.test(c.doc.textBetween(g.pos,y.pos,"","")))&&t.someProp("handleKeyDown",T=>T(t,Wo(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>m.start&&IO(u,m.start,m.endA,g,y)&&t.someProp("handleKeyDown",T=>T(t,Wo(8,"Backspace")))){Mr&&yt&&t.domObserver.suppressSelectionUpdates();return}yt&&m.endB==m.start&&(t.input.lastChromeDelete=Date.now()),Mr&&!k&&g.start()!=y.start()&&y.parentOffset==0&&g.depth==y.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==m.endA&&(m.endB-=2,y=c.doc.resolveNoCache(m.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(T){return T(t,Wo(13,"Enter"))})},20));let b=m.start,S=m.endA,v=T=>{let A=T||t.state.tr.replace(b,S,c.doc.slice(m.start-c.from,m.endB-c.from));if(c.sel){let P=Xw(t,A.doc,c.sel);P&&!(yt&&t.composing&&P.empty&&(m.start!=m.endB||t.input.lastChromeDelete<Date.now()-100)&&(P.head==b||P.head==A.mapping.map(S)-1)||Qt&&P.empty&&P.head==b)&&A.setSelection(P)}return s&&A.setMeta("composition",s),A.scrollIntoView()},x;if(k)if(g.pos==y.pos){Qt&&ro<=11&&g.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>Ar(t),20));let T=v(t.state.tr.delete(b,S)),A=u.resolve(m.start).marksAcross(u.resolve(m.endA));A&&T.ensureMarks(A),t.dispatch(T)}else if(m.endA==m.endB&&(x=AO(g.parent.content.cut(g.parentOffset,y.parentOffset),w.parent.content.cut(w.parentOffset,m.endA-w.start())))){let T=v(t.state.tr);x.type=="add"?T.addMark(b,S,x.mark):T.removeMark(b,S,x.mark),t.dispatch(T)}else if(g.parent.child(g.index()).isText&&g.index()==y.index()-(y.textOffset?0:1)){let T=g.parent.textBetween(g.parentOffset,y.parentOffset),A=()=>v(t.state.tr.insertText(T,b,S));t.someProp("handleTextInput",P=>P(t,b,S,T,A))||t.dispatch(A())}else t.dispatch(v());else t.dispatch(v())}function Xw(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:zd(t,e.resolve(n.anchor),e.resolve(n.head))}function AO(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,o=n,s=r,i,a,l;for(let u=0;u<r.length;u++)o=r[u].removeFromSet(o);for(let u=0;u<n.length;u++)s=n[u].removeFromSet(s);if(o.length==1&&s.length==0)a=o[0],i="add",l=u=>u.mark(a.addToSet(u.marks));else if(o.length==0&&s.length==1)a=s[0],i="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;u<e.childCount;u++)c.push(l(e.child(u)));if(D.from(c).eq(t))return{mark:a,type:i}}function IO(t,e,n,r,o){if(n-e<=o.pos-r.pos||Jd(r,!0,!1)<o.pos)return!1;let s=t.resolve(e);if(!r.parent.isTextblock){let a=s.nodeAfter;return a!=null&&n==e+a.nodeSize}if(s.parentOffset<s.parent.content.size||!s.parent.isTextblock)return!1;let i=t.resolve(Jd(s,!0,!0));return!i.parent.isTextblock||i.pos>n||Jd(i,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(i.parent.content)}function Jd(t,e,n){let r=t.depth,o=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,o++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,o++}return o}function BO(t,e,n,r,o){let s=t.findDiffStart(e,n);if(s==null)return null;let{a:i,b:a}=t.findDiffEnd(e,n+t.size,n+e.size);if(o=="end"){let l=Math.max(0,s-Math.min(i,a));r-=i+l-s}if(i<s&&t.size<e.size){let l=r<=s&&r>=i?s-r:0;s-=l,s&&s<e.size&&Gw(e.textBetween(s-1,s+1))&&(s+=l?1:-1),a=s+(a-i),i=s}else if(a<s){let l=r<=s&&r>=a?s-r:0;s-=l,s&&s<t.size&&Gw(t.textBetween(s-1,s+1))&&(s+=l?1:-1),i=s+(i-a),a=s}return{start:s,endA:i,endB:a}}function Gw(t){if(t.length!=2)return!1;let e=t.charCodeAt(0),n=t.charCodeAt(1);return e>=56320&&e<=57343&&n>=55296&&n<=56319}class Qw{constructor(e,n){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 KD,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(o1),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=n1(this),t1(this),this.nodeViews=r1(this),this.docView=cw(this.state.doc,e1(this),qd(this),this.dom,this),this.domObserver=new vO(this,(r,o,s,i)=>_O(this,r,o,s,i)),this.domObserver.start(),YD(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 n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&Ud(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(o1),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let o=this.state,s=!1,i=!1;e.storedMarks&&this.composing&&(Fw(this),i=!0),this.state=e;let a=o.plugins!=e.plugins||this._props.plugins!=n.plugins;if(a||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=r1(this);NO(p,this.nodeViews)&&(this.nodeViews=p,s=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&Ud(this),this.editable=n1(this),t1(this);let l=qd(this),c=e1(this),u=o.plugins!=e.plugins&&!o.doc.eq(e.doc)?"reset":e.scrollToSelection>o.scrollToSelection?"to selection":"preserve",d=s||!this.docView.matchesNode(e.doc,c,l);(d||!e.selection.eq(o.selection))&&(i=!0);let h=u=="preserve"&&i&&this.dom.style.overflowAnchor==null&&lD(this);if(i){this.domObserver.stop();let p=d&&(Qt||yt)&&!this.composing&&!o.selection.empty&&!e.selection.empty&&PO(o.selection,e.selection);if(d){let m=yt?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=lO(this)),(s||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=cw(e.doc,c,l,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&PD(this))?Ar(this,p):(kw(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(o),!((r=this.dragging)===null||r===void 0)&&r.node&&!o.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,o),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():h&&cD(h)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof re){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&J0(this,n.getBoundingClientRect(),e)}else J0(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 n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,o=-1;if(this.state.doc.nodeAt(r.from)==r.node)o=r.from;else{let s=r.from+(this.state.doc.content.size-n.doc.content.size);(s>0&&this.state.doc.nodeAt(s))==r.node&&(o=s)}this.dragging=new Ww(e.slice,e.move,o<0?void 0:re.create(this.state.doc,o))}someProp(e,n){let r=this._props&&this._props[e],o;if(r!=null&&(o=n?n(r):r))return o;for(let i=0;i<this.directPlugins.length;i++){let a=this.directPlugins[i].props[e];if(a!=null&&(o=n?n(a):a))return o}let s=this.state.plugins;if(s)for(let i=0;i<s.length;i++){let a=s[i].props[e];if(a!=null&&(o=n?n(a):a))return o}}hasFocus(){if(Qt){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&uD(this.dom),Ar(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return mD(this,e)}coordsAtPos(e,n=1){return nw(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let o=this.docView.posFromDOM(e,n,r);if(o==null)throw new RangeError("DOM position not inside the editor");return o}endOfTextblock(e,n){return vD(this,n||this.state,e)}pasteHTML(e,n){return Ui(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Ui(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return Fd(this,e)}destroy(){this.docView&&(qD(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],qd(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,GN())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return XD(this,e)}domSelectionRange(){let e=this.domSelection();return e?At&&this.root.nodeType===11&&rD(this.dom.ownerDocument)==this.dom&&SO(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Qw.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function e1(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[jt.node(0,t.state.doc.content.size,e)]}function t1(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:jt.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function n1(t){return!t.someProp("editable",e=>e(t.state)===!1)}function PO(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function r1(t){let e=Object.create(null);function n(r){for(let o in r)Object.prototype.hasOwnProperty.call(e,o)||(e[o]=r[o])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function NO(t,e){let n=0,r=0;for(let o in t){if(t[o]!=e[o])return!0;n++}for(let o in e)r++;return n!=r}function o1(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var uo={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:"'"},Nl={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},DO=typeof navigator<"u"&&/Mac/.test(navigator.platform),OO=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),It=0;It<10;It++)uo[48+It]=uo[96+It]=String(It);for(var It=1;It<=24;It++)uo[It+111]="F"+It;for(var It=65;It<=90;It++)uo[It]=String.fromCharCode(It+32),Nl[It]=String.fromCharCode(It);for(var Xd in uo)Nl.hasOwnProperty(Xd)||(Nl[Xd]=uo[Xd]);function RO(t){var e=DO&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||OO&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Nl:uo)[t.keyCode]||t.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const zO=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),$O=typeof navigator<"u"&&/Win/.test(navigator.platform);function LO(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,o,s,i;for(let a=0;a<e.length-1;a++){let l=e[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))o=!0;else if(/^s(hift)?$/i.test(l))s=!0;else if(/^mod$/i.test(l))zO?i=!0:o=!0;else throw new Error("Unrecognized modifier name: "+l)}return r&&(n="Alt-"+n),o&&(n="Ctrl-"+n),i&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function FO(t){let e=Object.create(null);for(let n in t)e[LO(n)]=t[n];return e}function Gd(t,e,n=!0){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),n&&e.shiftKey&&(t="Shift-"+t),t}function VO(t){return new at({props:{handleKeyDown:s1(t)}})}function s1(t){let e=FO(t);return function(n,r){let o=RO(r),s,i=e[Gd(o,r)];if(i&&i(n.state,n.dispatch,n))return!0;if(o.length==1&&o!=" "){if(r.shiftKey){let a=e[Gd(o,r,!1)];if(a&&a(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!($O&&r.ctrlKey&&r.altKey)&&(s=uo[r.keyCode])&&s!=o){let a=e[Gd(s,r)];if(a&&a(n.state,n.dispatch,n))return!0}}return!1}}var WO=Object.defineProperty,Qd=(t,e)=>{for(var n in e)WO(t,n,{get:e[n],enumerable:!0})};function Dl(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:o}=n,{storedMarks:s}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return o},get tr(){return r=n.selection,o=n.doc,s=n.storedMarks,n}}}var Ol=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:o}=n,s=this.buildProps(o);return Object.fromEntries(Object.entries(t).map(([i,a])=>[i,(...c)=>{const u=a(...c)(s);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(o),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:o}=this,{view:s}=r,i=[],a=!!t,l=t||o.tr,c=()=>(!a&&e&&!l.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(l),i.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(n).map(([d,h])=>[d,(...m)=>{const g=this.buildProps(l,e),y=h(...m)(g);return i.push(y),u}])),run:c};return u}createCan(t){const{rawCommands:e,state:n}=this,r=!1,o=t||n.tr,s=this.buildProps(o,r);return{...Object.fromEntries(Object.entries(e).map(([a,l])=>[a,(...c)=>l(...c)({...s,dispatch:void 0})])),chain:()=>this.createChain(o,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:o}=this,{view:s}=r,i={tr:t,editor:r,view:s,state:Dl({state:o,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([a,l])=>[a,(...c)=>l(...c)(i)]))}};return i}},i1={};Qd(i1,{blur:()=>UO,clearContent:()=>HO,clearNodes:()=>jO,command:()=>ZO,createParagraphNear:()=>KO,cut:()=>YO,deleteCurrentNode:()=>qO,deleteNode:()=>JO,deleteRange:()=>XO,deleteSelection:()=>GO,enter:()=>QO,exitCode:()=>e3,extendMarkRange:()=>t3,first:()=>n3,focus:()=>o3,forEach:()=>s3,insertContent:()=>i3,insertContentAt:()=>c3,joinBackward:()=>f3,joinDown:()=>d3,joinForward:()=>h3,joinItemBackward:()=>p3,joinItemForward:()=>m3,joinTextblockBackward:()=>g3,joinTextblockForward:()=>y3,joinUp:()=>u3,keyboardShortcut:()=>k3,lift:()=>v3,liftEmptyBlock:()=>b3,liftListItem:()=>S3,newlineInCode:()=>E3,resetAttributes:()=>C3,scrollIntoView:()=>x3,selectAll:()=>T3,selectNodeBackward:()=>M3,selectNodeForward:()=>_3,selectParentNode:()=>A3,selectTextblockEnd:()=>I3,selectTextblockStart:()=>B3,setContent:()=>P3,setMark:()=>X3,setMeta:()=>G3,setNode:()=>Q3,setNodeSelection:()=>eR,setTextDirection:()=>tR,setTextSelection:()=>nR,sinkListItem:()=>rR,splitBlock:()=>oR,splitListItem:()=>sR,toggleList:()=>iR,toggleMark:()=>aR,toggleNode:()=>lR,toggleWrap:()=>cR,undoInputRule:()=>uR,unsetAllMarks:()=>dR,unsetMark:()=>fR,unsetTextDirection:()=>hR,updateAttributes:()=>pR,wrapIn:()=>mR,wrapInList:()=>gR});var UO=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window==null?void 0:window.getSelection())==null||n.removeAllRanges())}),!0),HO=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),jO=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:o}=r;return n&&o.forEach(({$from:s,$to:i})=>{t.doc.nodesBetween(s.pos,i.pos,(a,l)=>{if(a.type.isText)return;const{doc:c,mapping:u}=e,d=c.resolve(u.map(l)),h=c.resolve(u.map(l+a.nodeSize)),p=d.blockRange(h);if(!p)return;const m=Ns(p);if(a.type.isTextblock){const{defaultType:g}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(p.start,g)}(m||m===0)&&e.lift(p,m)})}),!0},ZO=t=>e=>t(e),KO=()=>({state:t,dispatch:e})=>F0(t,e),YO=(t,e)=>({editor:n,tr:r})=>{const{state:o}=n,s=o.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const i=r.mapping.map(e);return r.insert(i,s.content),r.setSelection(new ue(r.doc.resolve(Math.max(i-1,0)))),!0},qO=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const o=t.selection.$anchor;for(let s=o.depth;s>0;s-=1)if(o.node(s).type===r.type){if(e){const a=o.before(s),l=o.after(s);t.delete(a,l).scrollIntoView()}return!0}return!1};function wt(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var JO=t=>({tr:e,state:n,dispatch:r})=>{const o=wt(t,n.schema),s=e.selection.$anchor;for(let i=s.depth;i>0;i-=1)if(s.node(i).type===o){if(r){const l=s.before(i),c=s.after(i);e.delete(l,c).scrollIntoView()}return!0}return!1},XO=t=>({tr:e,dispatch:n})=>{const{from:r,to:o}=t;return n&&e.delete(r,o),!0},GO=()=>({state:t,dispatch:e})=>Sd(t,e),QO=()=>({commands:t})=>t.keyboardShortcut("Enter"),e3=()=>({state:t,dispatch:e})=>zN(t,e);function ef(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function Rl(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(o=>n.strict?e[o]===t[o]:ef(e[o])?e[o].test(t[o]):e[o]===t[o]):!0}function a1(t,e,n={}){return t.find(r=>r.type===e&&Rl(Object.fromEntries(Object.keys(n).map(o=>[o,r.attrs[o]])),n))}function l1(t,e,n={}){return!!a1(t,e,n)}function tf(t,e,n){var r;if(!t||!e)return;let o=t.parent.childAfter(t.parentOffset);if((!o.node||!o.node.marks.some(u=>u.type===e))&&(o=t.parent.childBefore(t.parentOffset)),!o.node||!o.node.marks.some(u=>u.type===e)||(n=n||((r=o.node.marks[0])==null?void 0:r.attrs),!a1([...o.node.marks],e,n)))return;let i=o.index,a=t.start()+o.offset,l=i+1,c=a+o.node.nodeSize;for(;i>0&&l1([...t.parent.child(i-1).marks],e,n);)i-=1,a-=t.parent.child(i).nodeSize;for(;l<t.parent.childCount&&l1([...t.parent.child(l).marks],e,n);)c+=t.parent.child(l).nodeSize,l+=1;return{from:a,to:c}}function Ir(t,e){if(typeof t=="string"){if(!e.marks[t])throw Error(`There is no mark type named '${t}'. Maybe you forgot to add the extension?`);return e.marks[t]}return t}var t3=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const s=Ir(t,r.schema),{doc:i,selection:a}=n,{$from:l,from:c,to:u}=a;if(o){const d=tf(l,s,e);if(d&&d.from<=c&&d.to>=u){const h=ue.create(i,d.from,d.to);n.setSelection(h)}}return!0},n3=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r<n.length;r+=1)if(n[r](e))return!0;return!1};function c1(t){return t instanceof ue}function Yo(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function u1(t,e=null){if(!e)return null;const n=fe.atStart(t),r=fe.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const o=n.from,s=r.to;return e==="all"?ue.create(t,Yo(0,o,s),Yo(t.content.size,o,s)):ue.create(t,Yo(e,o,s),Yo(e,o,s))}function d1(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function zl(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function r3(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var o3=(t=null,e={})=>({editor:n,view:r,tr:o,dispatch:s})=>{e={scrollIntoView:!0,...e};const i=()=>{(zl()||d1())&&r.dom.focus(),r3()&&!zl()&&!d1()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e!=null&&e.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&t===null||t===!1)return!0;if(s&&t===null&&!c1(n.state.selection))return i(),!0;const a=u1(o.doc,t)||n.state.selection,l=n.state.selection.eq(a);return s&&(l||o.setSelection(a),l&&o.storedMarks&&o.setStoredMarks(o.storedMarks),i()),!0},s3=(t,e)=>n=>t.every((r,o)=>e(r,{...n,index:o})),i3=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),f1=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):r.nodeType===1&&f1(r)}return t};function ji(t){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`<body>${t}</body>`,n=new window.DOMParser().parseFromString(e,"text/html").body;return f1(n)}function Zi(t,e,n){if(t instanceof Er||t instanceof D)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,o=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return D.fromArray(t.map(a=>e.nodeFromJSON(a)));const i=e.nodeFromJSON(t);return n.errorOnInvalidContent&&i.check(),i}catch(s){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",s),Zi("",e,n)}if(o){if(n.errorOnInvalidContent){let i=!1,a="";const l=new Xy({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(i=!0,a=typeof c=="string"?c:c.outerHTML,null)}]}})});if(n.slice?Cr.fromSchema(l).parseSlice(ji(t),n.parseOptions):Cr.fromSchema(l).parse(ji(t),n.parseOptions),n.errorOnInvalidContent&&i)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const s=Cr.fromSchema(e);return n.slice?s.parseSlice(ji(t),n.parseOptions).content:s.parse(ji(t),n.parseOptions)}return Zi("",e,n)}function a3(t,e,n){const r=t.steps.length-1;if(r<e)return;const o=t.steps[r];if(!(o instanceof mt||o instanceof gt))return;const s=t.mapping.maps[r];let i=0;s.forEach((a,l,c,u)=>{i===0&&(i=u)}),t.setSelection(fe.near(t.doc.resolve(i),n))}var l3=t=>!("type"in t),c3=(t,e,n)=>({tr:r,dispatch:o,editor:s})=>{var i;if(o){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let a;const l=y=>{s.emit("contentError",{editor:s,error:y,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{Zi(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(y){l(y)}try{a=Zi(e,s.schema,{parseOptions:c,errorOnInvalidContent:(i=n.errorOnInvalidContent)!=null?i:s.options.enableContentCheck})}catch(y){return l(y),!1}let{from:u,to:d}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},h=!0,p=!0;if((l3(a)?a:[a]).forEach(y=>{y.check(),h=h?y.isText&&y.marks.length===0:!1,p=p?y.isBlock:!1}),u===d&&p){const{parent:y}=r.doc.resolve(u);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(u-=1,d+=1)}let g;if(h){if(Array.isArray(e))g=e.map(y=>y.text||"").join("");else if(e instanceof D){let y="";e.forEach(w=>{w.text&&(y+=w.text)}),g=y}else typeof e=="object"&&e&&e.text?g=e.text:g=e;r.insertText(g,u,d)}else{g=a;const y=r.doc.resolve(u),w=y.node(),k=y.parentOffset===0,b=w.isText||w.isTextblock,S=w.content.size>0;k&&b&&S&&(u=Math.max(0,u-1)),r.replaceWith(u,d,g)}n.updateSelection&&a3(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:g}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:g})}return!0},u3=()=>({state:t,dispatch:e})=>DN(t,e),d3=()=>({state:t,dispatch:e})=>ON(t,e),f3=()=>({state:t,dispatch:e})=>N0(t,e),h3=()=>({state:t,dispatch:e})=>z0(t,e),p3=()=>({state:t,dispatch:e,tr:n})=>{try{const r=bl(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},m3=()=>({state:t,dispatch:e,tr:n})=>{try{const r=bl(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},g3=()=>({state:t,dispatch:e})=>PN(t,e),y3=()=>({state:t,dispatch:e})=>NN(t,e);function h1(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function w3(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,o,s,i;for(let a=0;a<e.length-1;a+=1){const l=e[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))o=!0;else if(/^s(hift)?$/i.test(l))s=!0;else if(/^mod$/i.test(l))zl()||h1()?i=!0:o=!0;else throw new Error(`Unrecognized modifier name: ${l}`)}return r&&(n=`Alt-${n}`),o&&(n=`Ctrl-${n}`),i&&(n=`Meta-${n}`),s&&(n=`Shift-${n}`),n}var k3=t=>({editor:e,view:n,tr:r,dispatch:o})=>{const s=w3(t).split(/-(?!$)/),i=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),a=new KeyboardEvent("keydown",{key:i==="Space"?" ":i,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),l=e.captureTransaction(()=>{n.someProp("handleKeyDown",c=>c(n,a))});return l==null||l.steps.forEach(c=>{const u=c.map(r.mapping);u&&o&&r.maybeStep(u)}),!0};function Ki(t,e,n={}){const{from:r,to:o,empty:s}=t.selection,i=e?wt(e,t.schema):null,a=[];t.doc.nodesBetween(r,o,(d,h)=>{if(d.isText)return;const p=Math.max(r,h),m=Math.min(o,h+d.nodeSize);a.push({node:d,from:p,to:m})});const l=o-r,c=a.filter(d=>i?i.name===d.node.type.name:!0).filter(d=>Rl(d.node.attrs,n,{strict:!1}));return s?!!c.length:c.reduce((d,h)=>d+h.to-h.from,0)>=l}var v3=(t,e={})=>({state:n,dispatch:r})=>{const o=wt(t,n.schema);return Ki(n,o,e)?RN(n,r):!1},b3=()=>({state:t,dispatch:e})=>V0(t,e),S3=t=>({state:e,dispatch:n})=>{const r=wt(t,e.schema);return YN(r)(e,n)},E3=()=>({state:t,dispatch:e})=>L0(t,e);function $l(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function p1(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,o)=>(n.includes(o)||(r[o]=t[o]),r),{})}var C3=(t,e)=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=$l(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=wt(t,r.schema)),a==="mark"&&(i=Ir(t,r.schema));let l=!1;return n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,d)=>{s&&s===u.type&&(l=!0,o&&n.setNodeMarkup(d,void 0,p1(u.attrs,e))),i&&u.marks.length&&u.marks.forEach(h=>{i===h.type&&(l=!0,o&&n.addMark(d,d+u.nodeSize,i.create(p1(h.attrs,e))))})})}),l},x3=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),T3=()=>({tr:t,dispatch:e})=>{if(e){const n=new dn(t.doc);t.setSelection(n)}return!0},M3=()=>({state:t,dispatch:e})=>O0(t,e),_3=()=>({state:t,dispatch:e})=>$0(t,e),A3=()=>({state:t,dispatch:e})=>FN(t,e),I3=()=>({state:t,dispatch:e})=>UN(t,e),B3=()=>({state:t,dispatch:e})=>WN(t,e);function nf(t,e,n={},r={}){return Zi(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var P3=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:o,tr:s,dispatch:i,commands:a})=>{const{doc:l}=s;if(r.preserveWhitespace!=="full"){const c=nf(t,o.schema,r,{errorOnInvalidContent:e??o.options.enableContentCheck});return i&&s.replaceWith(0,l.content.size,c).setMeta("preventUpdate",!n),!0}return i&&s.setMeta("preventUpdate",!n),a.insertContentAt({from:0,to:l.content.size},t,{parseOptions:r,errorOnInvalidContent:e??o.options.enableContentCheck})};function m1(t,e){const n=Ir(e,t.schema),{from:r,to:o,empty:s}=t.selection,i=[];s?(t.storedMarks&&i.push(...t.storedMarks),i.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,o,l=>{i.push(...l.marks)});const a=i.find(l=>l.type.name===n.name);return a?{...a.attrs}:{}}function N3(t,e){const n=new E0(t);return e.forEach(r=>{r.steps.forEach(o=>{n.step(o)})}),n}function D3(t){for(let e=0;e<t.edgeCount;e+=1){const{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function O3(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}function rf(t){return e=>O3(e.$from,t)}function te(t,e,n){return t.config[e]===void 0&&t.parent?te(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?te(t.parent,e,n):null}):t.config[e]}function of(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=te(e,"addExtensions",n);return r?[e,...of(r())]:e}).flat(10)}function Ll(t,e){const n=$o.fromSchema(e).serializeFragment(t),o=document.implementation.createHTMLDocument().createElement("div");return o.appendChild(n),o.innerHTML}function g1(t){return typeof t=="function"}function Pe(t,e=void 0,...n){return g1(t)?e?t.bind(e)(...n):t(...n):t}function R3(t={}){return Object.keys(t).length===0&&t.constructor===Object}function js(t){const e=t.filter(o=>o.type==="extension"),n=t.filter(o=>o.type==="node"),r=t.filter(o=>o.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function y1(t){const e=[],{nodeExtensions:n,markExtensions:r}=js(t),o=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(i=>{const a={name:i.name,options:i.options,storage:i.storage,extensions:o},l=te(i,"addGlobalAttributes",a);if(!l)return;l().forEach(u=>{u.types.forEach(d=>{Object.entries(u.attributes).forEach(([h,p])=>{e.push({type:d,name:h,attribute:{...s,...p}})})})})}),o.forEach(i=>{const a={name:i.name,options:i.options,storage:i.storage},l=te(i,"addAttributes",a);if(!l)return;const c=l();Object.entries(c).forEach(([u,d])=>{const h={...s,...d};typeof(h==null?void 0:h.default)=="function"&&(h.default=h.default()),h!=null&&h.isRequired&&(h==null?void 0:h.default)===void 0&&delete h.default,e.push({type:i.name,name:u,attribute:h})})}),e}function Zs(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([o,s])=>{if(!r[o]){r[o]=s;return}if(o==="class"){const a=s?String(s).split(" "):[],l=r[o]?r[o].split(" "):[],c=a.filter(u=>!l.includes(u));r[o]=[...l,...c].join(" ")}else if(o==="style"){const a=s?s.split(";").map(u=>u.trim()).filter(Boolean):[],l=r[o]?r[o].split(";").map(u=>u.trim()).filter(Boolean):[],c=new Map;l.forEach(u=>{const[d,h]=u.split(":").map(p=>p.trim());c.set(d,h)}),a.forEach(u=>{const[d,h]=u.split(":").map(p=>p.trim());c.set(d,h)}),r[o]=Array.from(c.entries()).map(([u,d])=>`${u}: ${d}`).join("; ")}else r[o]=s}),r},{})}function Fl(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,r)=>Zs(n,r),{})}function z3(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function w1(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(r===!1)return!1;const o=e.reduce((s,i)=>{const a=i.attribute.parseHTML?i.attribute.parseHTML(n):z3(n.getAttribute(i.name));return a==null?s:{...s,[i.name]:a}},{});return{...r,...o}}}}function k1(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&R3(n)?!1:n!=null))}function v1(t){var e,n;const r={};return!((e=t==null?void 0:t.attribute)!=null&&e.isRequired)&&"default"in((t==null?void 0:t.attribute)||{})&&(r.default=t.attribute.default),((n=t==null?void 0:t.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=t.attribute.validate),[t.name,r]}function b1(t,e){var n;const r=y1(t),{nodeExtensions:o,markExtensions:s}=js(t),i=(n=o.find(c=>te(c,"topNode")))==null?void 0:n.name,a=Object.fromEntries(o.map(c=>{const u=r.filter(w=>w.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=t.reduce((w,k)=>{const b=te(k,"extendNodeSchema",d);return{...w,...b?b(c):{}}},{}),p=k1({...h,content:Pe(te(c,"content",d)),marks:Pe(te(c,"marks",d)),group:Pe(te(c,"group",d)),inline:Pe(te(c,"inline",d)),atom:Pe(te(c,"atom",d)),selectable:Pe(te(c,"selectable",d)),draggable:Pe(te(c,"draggable",d)),code:Pe(te(c,"code",d)),whitespace:Pe(te(c,"whitespace",d)),linebreakReplacement:Pe(te(c,"linebreakReplacement",d)),defining:Pe(te(c,"defining",d)),isolating:Pe(te(c,"isolating",d)),attrs:Object.fromEntries(u.map(v1))}),m=Pe(te(c,"parseHTML",d));m&&(p.parseDOM=m.map(w=>w1(w,u)));const g=te(c,"renderHTML",d);g&&(p.toDOM=w=>g({node:w,HTMLAttributes:Fl(w,u)}));const y=te(c,"renderText",d);return y&&(p.toText=y),[c.name,p]})),l=Object.fromEntries(s.map(c=>{const u=r.filter(y=>y.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=t.reduce((y,w)=>{const k=te(w,"extendMarkSchema",d);return{...y,...k?k(c):{}}},{}),p=k1({...h,inclusive:Pe(te(c,"inclusive",d)),excludes:Pe(te(c,"excludes",d)),group:Pe(te(c,"group",d)),spanning:Pe(te(c,"spanning",d)),code:Pe(te(c,"code",d)),attrs:Object.fromEntries(u.map(v1))}),m=Pe(te(c,"parseHTML",d));m&&(p.parseDOM=m.map(y=>w1(y,u)));const g=te(c,"renderHTML",d);return g&&(p.toDOM=y=>g({mark:y,HTMLAttributes:Fl(y,u)})),[c.name,p]}));return new Xy({topNode:i,nodes:a,marks:l})}function $3(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function Vl(t){return t.sort((n,r)=>{const o=te(n,"priority")||100,s=te(r,"priority")||100;return o>s?-1:o<s?1:0})}function sf(t){const e=Vl(of(t)),n=$3(e.map(r=>r.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function S1(t,e){const n=sf(t);return b1(n,e)}function Wl(t,e){const n=S1(e),r=Er.fromJSON(n,t);return Ll(r.content,n)}function fo(t,e){const n=S1(e),r=ji(t);return Cr.fromSchema(n).parse(r).toJSON()}function E1(t,e,n){const{from:r,to:o}=e,{blockSeparator:s=`
79
-
80
- `,textSerializers:i={}}=n||{};let a="";return t.nodesBetween(r,o,(l,c,u,d)=>{var h;l.isBlock&&c>r&&(a+=s);const p=i==null?void 0:i[l.type.name];if(p)return u&&(a+=p({node:l,pos:c,parent:u,index:d,range:e})),!1;l.isText&&(a+=(h=l==null?void 0:l.text)==null?void 0:h.slice(Math.max(r,c)-c,o-c))}),a}function L3(t,e){const n={from:0,to:t.content.size};return E1(t,n,e)}function C1(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function F3(t,e){const n=wt(e,t.schema),{from:r,to:o}=t.selection,s=[];t.doc.nodesBetween(r,o,a=>{s.push(a)});const i=s.reverse().find(a=>a.type.name===n.name);return i?{...i.attrs}:{}}function V3(t,e){const n=$l(typeof e=="string"?e:e.name,t.schema);return n==="node"?F3(t,e):n==="mark"?m1(t,e):{}}function W3(t,e=JSON.stringify){const n={};return t.filter(r=>{const o=e(r);return Object.prototype.hasOwnProperty.call(n,o)?!1:n[o]=!0})}function U3(t){const e=W3(t);return e.length===1?e:e.filter((n,r)=>!e.filter((s,i)=>i!==r).some(s=>n.oldRange.from>=s.oldRange.from&&n.oldRange.to<=s.oldRange.to&&n.newRange.from>=s.newRange.from&&n.newRange.to<=s.newRange.to))}function H3(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((o,s)=>{const i=[];if(o.ranges.length)o.forEach((a,l)=>{i.push({from:a,to:l})});else{const{from:a,to:l}=n[s];if(a===void 0||l===void 0)return;i.push({from:a,to:l})}i.forEach(({from:a,to:l})=>{const c=e.slice(s).map(a,-1),u=e.slice(s).map(l),d=e.invert().map(c,-1),h=e.invert().map(u);r.push({oldRange:{from:d,to:h},newRange:{from:c,to:u}})})}),U3(r)}function x1(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(o=>{const s=n.resolve(t),i=tf(s,o.type);i&&r.push({mark:o,...i})}):n.nodesBetween(t,e,(o,s)=>{!o||(o==null?void 0:o.nodeSize)===void 0||r.push(...o.marks.map(i=>({from:s,to:s+o.nodeSize,mark:i})))}),r}function Ul(t,e){return e.nodes[t]||e.marks[t]||null}function Hl(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const o=t.find(s=>s.type===e&&s.name===r);return o?o.attribute.keepOnSplit:!1}))}var j3=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(o,s,i,a)=>{var l,c;const u=((c=(l=o.type.spec).toText)==null?void 0:c.call(l,{node:o,pos:s,parent:i,index:a}))||o.textContent||"%leaf%";n+=o.isAtom&&!o.isText?u:u.slice(0,Math.max(0,r-s))}),n};function af(t,e,n={}){const{empty:r,ranges:o}=t.selection,s=e?Ir(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(d=>s?s.name===d.type.name:!0).find(d=>Rl(d.attrs,n,{strict:!1}));let i=0;const a=[];if(o.forEach(({$from:d,$to:h})=>{const p=d.pos,m=h.pos;t.doc.nodesBetween(p,m,(g,y)=>{if(!g.isText&&!g.marks.length)return;const w=Math.max(p,y),k=Math.min(m,y+g.nodeSize),b=k-w;i+=b,a.push(...g.marks.map(S=>({mark:S,from:w,to:k})))})}),i===0)return!1;const l=a.filter(d=>s?s.name===d.mark.type.name:!0).filter(d=>Rl(d.mark.attrs,n,{strict:!1})).reduce((d,h)=>d+h.to-h.from,0),c=a.filter(d=>s?d.mark.type!==s&&d.mark.type.excludes(s):!0).reduce((d,h)=>d+h.to-h.from,0);return(l>0?l+c:l)>=i}function Z3(t,e,n={}){if(!e)return Ki(t,null,n)||af(t,null,n);const r=$l(e,t.schema);return r==="node"?Ki(t,e,n):r==="mark"?af(t,e,n):!1}function T1(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function M1(t,e){const{nodeExtensions:n}=js(e),r=n.find(i=>i.name===t);if(!r)return!1;const o={name:r.name,options:r.options,storage:r.storage},s=Pe(te(r,"group",o));return typeof s!="string"?!1:s.split(" ").includes("list")}function jl(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((r=t.text)!=null?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let o=!0;return t.content.forEach(s=>{o!==!1&&(jl(s,{ignoreWhitespace:n,checkChildren:e})||(o=!1))}),o}return!1}function K3(t){return t instanceof re}var _1=class _v{constructor(e){this.position=e}static fromJSON(e){return new _v(e.position)}toJSON(){return{position:this.position}}};function Y3(t,e){const n=e.mapping.mapResult(t.position);return{position:new _1(n.pos),mapResult:n}}function q3(t){return new _1(t)}function J3(t,e,n){var r;const{selection:o}=e;let s=null;if(c1(o)&&(s=o.$cursor),s){const a=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(a)||!a.some(c=>c.type.excludes(n)))}const{ranges:i}=o;return i.some(({$from:a,$to:l})=>{let c=a.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(a.pos,l.pos,(u,d,h)=>{if(c)return!1;if(u.isInline){const p=!h||h.type.allowsMarkType(n),m=!!n.isInSet(u.marks)||!u.marks.some(g=>g.type.excludes(n));c=p&&m}return!c}),c})}var X3=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const{selection:s}=n,{empty:i,ranges:a}=s,l=Ir(t,r.schema);if(o)if(i){const c=m1(r,l);n.addStoredMark(l.create({...c,...e}))}else a.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;r.doc.nodesBetween(u,d,(h,p)=>{const m=Math.max(p,u),g=Math.min(p+h.nodeSize,d);h.marks.find(w=>w.type===l)?h.marks.forEach(w=>{l===w.type&&n.addMark(m,g,l.create({...w.attrs,...e}))}):n.addMark(m,g,l.create(e))})});return J3(r,n,l)},G3=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),Q3=(t,e={})=>({state:n,dispatch:r,chain:o})=>{const s=wt(t,n.schema);let i;return n.selection.$anchor.sameParent(n.selection.$head)&&(i=n.selection.$anchor.parent.attrs),s.isTextblock?o().command(({commands:a})=>H0(s,{...i,...e})(n)?!0:a.clearNodes()).command(({state:a})=>H0(s,{...i,...e})(a,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},eR=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,o=Yo(t,0,r.content.size),s=re.create(r,o);e.setSelection(s)}return!0},tR=(t,e)=>({tr:n,state:r,dispatch:o})=>{const{selection:s}=r;let i,a;return typeof e=="number"?(i=e,a=e):e&&"from"in e&&"to"in e?(i=e.from,a=e.to):(i=s.from,a=s.to),o&&n.doc.nodesBetween(i,a,(l,c)=>{l.isText||n.setNodeMarkup(c,void 0,{...l.attrs,dir:t})}),!0},nR=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:o,to:s}=typeof t=="number"?{from:t,to:t}:t,i=ue.atStart(r).from,a=ue.atEnd(r).to,l=Yo(o,i,a),c=Yo(s,i,a),u=ue.create(r,l,c);e.setSelection(u)}return!0},rR=t=>({state:e,dispatch:n})=>{const r=wt(t,e.schema);return XN(r)(e,n)};function A1(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(o=>e==null?void 0:e.includes(o.type.name));t.tr.ensureMarks(r)}}var oR=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:o})=>{const{selection:s,doc:i}=e,{$from:a,$to:l}=s,c=o.extensionManager.attributes,u=Hl(c,a.node().type.name,a.node().attrs);if(s instanceof re&&s.node.isBlock)return!a.parentOffset||!xr(i,a.pos)?!1:(r&&(t&&A1(n,o.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const d=l.parentOffset===l.parent.content.size,h=a.depth===0?void 0:D3(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=d&&h?[{type:h,attrs:u}]:void 0,m=xr(e.doc,e.mapping.map(a.pos),1,p);if(!p&&!m&&xr(e.doc,e.mapping.map(a.pos),1,h?[{type:h}]:void 0)&&(m=!0,p=h?[{type:h,attrs:u}]:void 0),r){if(m&&(s instanceof ue&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,p),h&&!d&&!a.parentOffset&&a.parent.type!==h)){const g=e.mapping.map(a.before()),y=e.doc.resolve(g);a.node(-1).canReplaceWith(y.index(),y.index()+1,h)&&e.setNodeMarkup(e.mapping.map(a.before()),h)}t&&A1(n,o.extensionManager.splittableMarks),e.scrollIntoView()}return m},sR=(t,e={})=>({tr:n,state:r,dispatch:o,editor:s})=>{var i;const a=wt(t,r.schema),{$from:l,$to:c}=r.selection,u=r.selection.node;if(u&&u.isBlock||l.depth<2||!l.sameParent(c))return!1;const d=l.node(-1);if(d.type!==a)return!1;const h=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==a||l.index(-2)!==l.node(-2).childCount-1)return!1;if(o){let w=D.empty;const k=l.index(-1)?1:l.index(-2)?2:3;for(let A=l.depth-k;A>=l.depth-3;A-=1)w=D.from(l.node(A).copy(w));const b=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,S={...Hl(h,l.node().type.name,l.node().attrs),...e},v=((i=a.contentMatch.defaultType)==null?void 0:i.createAndFill(S))||void 0;w=w.append(D.from(a.createAndFill(null,v)||void 0));const x=l.before(l.depth-(k-1));n.replace(x,l.after(-b),new j(w,4-k,0));let T=-1;n.doc.nodesBetween(x,n.doc.content.size,(A,P)=>{if(T>-1)return!1;A.isTextblock&&A.content.size===0&&(T=P+1)}),T>-1&&n.setSelection(ue.near(n.doc.resolve(T))),n.scrollIntoView()}return!0}const p=c.pos===l.end()?d.contentMatchAt(0).defaultType:null,m={...Hl(h,d.type.name,d.attrs),...e},g={...Hl(h,l.node().type.name,l.node().attrs),...e};n.delete(l.pos,c.pos);const y=p?[{type:a,attrs:m},{type:p,attrs:g}]:[{type:a,attrs:m}];if(!xr(n.doc,l.pos,2))return!1;if(o){const{selection:w,storedMarks:k}=r,{splittableMarks:b}=s.extensionManager,S=k||w.$to.parentOffset&&w.$from.marks();if(n.split(l.pos,2,y).scrollIntoView(),!S||!o)return!0;const v=S.filter(x=>b.includes(x.type.name));n.ensureMarks(v)}return!0},lf=(t,e)=>{const n=rf(i=>i.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const o=t.doc.nodeAt(r);return n.node.type===(o==null?void 0:o.type)&&Fo(t.doc,n.pos)&&t.join(n.pos),!0},cf=(t,e)=>{const n=rf(i=>i.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const o=t.doc.nodeAt(r);return n.node.type===(o==null?void 0:o.type)&&Fo(t.doc,r)&&t.join(r),!0},iR=(t,e,n,r={})=>({editor:o,tr:s,state:i,dispatch:a,chain:l,commands:c,can:u})=>{const{extensions:d,splittableMarks:h}=o.extensionManager,p=wt(t,i.schema),m=wt(e,i.schema),{selection:g,storedMarks:y}=i,{$from:w,$to:k}=g,b=w.blockRange(k),S=y||g.$to.parentOffset&&g.$from.marks();if(!b)return!1;const v=rf(x=>M1(x.type.name,d))(g);if(b.depth>=1&&v&&b.depth-v.depth<=1){if(v.node.type===p)return c.liftListItem(m);if(M1(v.node.type.name,d)&&p.validContent(v.node.content)&&a)return l().command(()=>(s.setNodeMarkup(v.pos,p),!0)).command(()=>lf(s,p)).command(()=>cf(s,p)).run()}return!n||!S||!a?l().command(()=>u().wrapInList(p,r)?!0:c.clearNodes()).wrapInList(p,r).command(()=>lf(s,p)).command(()=>cf(s,p)).run():l().command(()=>{const x=u().wrapInList(p,r),T=S.filter(A=>h.includes(A.type.name));return s.ensureMarks(T),x?!0:c.clearNodes()}).wrapInList(p,r).command(()=>lf(s,p)).command(()=>cf(s,p)).run()},aR=(t,e={},n={})=>({state:r,commands:o})=>{const{extendEmptyMarkRange:s=!1}=n,i=Ir(t,r.schema);return af(r,i,e)?o.unsetMark(i,{extendEmptyMarkRange:s}):o.setMark(i,e)},lR=(t,e,n={})=>({state:r,commands:o})=>{const s=wt(t,r.schema),i=wt(e,r.schema),a=Ki(r,s,n);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),a?o.setNode(i,l):o.setNode(s,{...l,...n})},cR=(t,e={})=>({state:n,commands:r})=>{const o=wt(t,n.schema);return Ki(n,o,e)?r.lift(o):r.wrapIn(o,e)},uR=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r<n.length;r+=1){const o=n[r];let s;if(o.spec.isInputRules&&(s=o.getState(t))){if(e){const i=t.tr,a=s.transform;for(let l=a.steps.length-1;l>=0;l-=1)i.step(a.steps[l].invert(a.docs[l]));if(s.text){const l=i.doc.resolve(s.from).marks();i.replaceWith(s.from,s.to,t.schema.text(s.text,l))}else i.delete(s.from,s.to)}return!0}}return!1},dR=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:o}=n;return r||e&&o.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},fR=(t,e={})=>({tr:n,state:r,dispatch:o})=>{var s;const{extendEmptyMarkRange:i=!1}=e,{selection:a}=n,l=Ir(t,r.schema),{$from:c,empty:u,ranges:d}=a;if(!o)return!0;if(u&&i){let{from:h,to:p}=a;const m=(s=c.marks().find(y=>y.type===l))==null?void 0:s.attrs,g=tf(c,l,m);g&&(h=g.from,p=g.to),n.removeMark(h,p,l)}else d.forEach(h=>{n.removeMark(h.$from.pos,h.$to.pos,l)});return n.removeStoredMark(l),!0},hR=t=>({tr:e,state:n,dispatch:r})=>{const{selection:o}=n;let s,i;return typeof t=="number"?(s=t,i=t):t&&"from"in t&&"to"in t?(s=t.from,i=t.to):(s=o.from,i=o.to),r&&e.doc.nodesBetween(s,i,(a,l)=>{if(a.isText)return;const c={...a.attrs};delete c.dir,e.setNodeMarkup(l,void 0,c)}),!0},pR=(t,e={})=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=$l(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=wt(t,r.schema)),a==="mark"&&(i=Ir(t,r.schema));let l=!1;return n.selection.ranges.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;let h,p,m,g;n.selection.empty?r.doc.nodesBetween(u,d,(y,w)=>{s&&s===y.type&&(l=!0,m=Math.max(w,u),g=Math.min(w+y.nodeSize,d),h=w,p=y)}):r.doc.nodesBetween(u,d,(y,w)=>{w<u&&s&&s===y.type&&(l=!0,m=Math.max(w,u),g=Math.min(w+y.nodeSize,d),h=w,p=y),w>=u&&w<=d&&(s&&s===y.type&&(l=!0,o&&n.setNodeMarkup(w,void 0,{...y.attrs,...e})),i&&y.marks.length&&y.marks.forEach(k=>{if(i===k.type&&(l=!0,o)){const b=Math.max(w,u),S=Math.min(w+y.nodeSize,d);n.addMark(b,S,i.create({...k.attrs,...e}))}}))}),p&&(h!==void 0&&o&&n.setNodeMarkup(h,void 0,{...p.attrs,...e}),i&&p.marks.length&&p.marks.forEach(y=>{i===y.type&&o&&n.addMark(m,g,i.create({...y.attrs,...e}))}))}),l},mR=(t,e={})=>({state:n,dispatch:r})=>{const o=wt(t,n.schema);return HN(o,e)(n,r)},gR=(t,e={})=>({state:n,dispatch:r})=>{const o=wt(t,n.schema);return jN(o,e)(n,r)},yR=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(r=>r.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(r=>r!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},wR=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},kR=(t,e)=>{if(ef(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function Zl(t){var e;const{editor:n,from:r,to:o,text:s,rules:i,plugin:a}=t,{view:l}=n;if(l.composing)return!1;const c=l.state.doc.resolve(r);if(c.parent.type.spec.code||(e=c.nodeBefore||c.nodeAfter)!=null&&e.marks.find(h=>h.type.spec.code))return!1;let u=!1;const d=j3(c)+s;return i.forEach(h=>{if(u)return;const p=kR(d,h.find);if(!p)return;const m=l.state.tr,g=Dl({state:l.state,transaction:m}),y={from:r-(p[0].length-s.length),to:o},{commands:w,chain:k,can:b}=new Ol({editor:n,state:g});h.handler({state:g,range:y,match:p,commands:w,chain:k,can:b})===null||!m.steps.length||(h.undoable&&m.setMeta(a,{transform:m,from:r,to:o,text:s}),l.dispatch(m),u=!0)}),u}function vR(t){const{editor:e,rules:n}=t,r=new at({state:{init(){return null},apply(o,s,i){const a=o.getMeta(r);if(a)return a;const l=o.getMeta("applyInputRules");return!!l&&setTimeout(()=>{let{text:u}=l;typeof u=="string"?u=u:u=Ll(D.from(u),i.schema);const{from:d}=l,h=d+u.length;Zl({editor:e,from:d,to:h,text:u,rules:n,plugin:r})}),o.selectionSet||o.docChanged?null:s}},props:{handleTextInput(o,s,i,a){return Zl({editor:e,from:s,to:i,text:a,rules:n,plugin:r})},handleDOMEvents:{compositionend:o=>(setTimeout(()=>{const{$cursor:s}=o.state.selection;s&&Zl({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(o,s){if(s.key!=="Enter")return!1;const{$cursor:i}=o.state.selection;return i?Zl({editor:e,from:i.pos,to:i.pos,text:`
81
- `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function bR(t){return Object.prototype.toString.call(t).slice(8,-1)}function Kl(t){return bR(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function I1(t,e){const n={...t};return Kl(t)&&Kl(e)&&Object.keys(e).forEach(r=>{Kl(e[r])&&Kl(t[r])?n[r]=I1(t[r],e[r]):n[r]=e[r]}),n}var uf=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...Pe(te(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Pe(te(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>I1(this.options,t)});return e.name=this.name,e.parent=this.parent,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},Yi=class Av extends uf{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new Av(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,o=e.state.selection.$from;if(o.pos===o.end()){const i=o.marks();if(!!!i.find(c=>(c==null?void 0:c.type.name)===n.name))return!1;const l=i.find(c=>(c==null?void 0:c.type.name)===n.name);return l&&r.removeStoredMark(l),r.insertText(" ",o.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function SR(t){return typeof t=="number"}var ER=class{constructor(t){this.find=t.find,this.handler=t.handler}},CR=(t,e,n)=>{if(ef(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(o=>{const s=[o.text];return s.index=o.index,s.input=t,s.data=o.data,o.replaceWith&&(o.text.includes(o.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(o.replaceWith)),s}):[]};function xR(t){const{editor:e,state:n,from:r,to:o,rule:s,pasteEvent:i,dropEvent:a}=t,{commands:l,chain:c,can:u}=new Ol({editor:e,state:n}),d=[];return n.doc.nodesBetween(r,o,(p,m)=>{var g,y,w,k,b;if((y=(g=p.type)==null?void 0:g.spec)!=null&&y.code||!(p.isText||p.isTextblock||p.isInline))return;const S=(b=(k=(w=p.content)==null?void 0:w.size)!=null?k:p.nodeSize)!=null?b:0,v=Math.max(r,m),x=Math.min(o,m+S);if(v>=x)return;const T=p.isText?p.text||"":p.textBetween(v-m,x-m,void 0,"");CR(T,s.find,i).forEach(P=>{if(P.index===void 0)return;const $=v+P.index+1,V=$+P[0].length,U={from:n.tr.mapping.map($),to:n.tr.mapping.map(V)},M=s.handler({state:n,range:U,match:P,commands:l,chain:c,can:u,pasteEvent:i,dropEvent:a});d.push(M)})}),d.every(p=>p!==null)}var Yl=null,TR=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function MR(t){const{editor:e,rules:n}=t;let r=null,o=!1,s=!1,i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,a;try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}const l=({state:u,from:d,to:h,rule:p,pasteEvt:m})=>{const g=u.tr,y=Dl({state:u,transaction:g});if(!(!xR({editor:e,state:y,from:Math.max(d-1,0),to:h.b-1,rule:p,pasteEvent:m,dropEvent:a})||!g.steps.length)){try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}return i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,g}};return n.map(u=>new at({view(d){const h=m=>{var g;r=(g=d.dom.parentElement)!=null&&g.contains(m.target)?d.dom.parentElement:null,r&&(Yl=e)},p=()=>{Yl&&(Yl=null)};return window.addEventListener("dragstart",h),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",h),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(d,h)=>{if(s=r===d.dom.parentElement,a=h,!s){const p=Yl;p!=null&&p.isEditable&&setTimeout(()=>{const m=p.state.selection;m&&p.commands.deleteRange({from:m.from,to:m.to})},10)}return!1},paste:(d,h)=>{var p;const m=(p=h.clipboardData)==null?void 0:p.getData("text/html");return i=h,o=!!(m!=null&&m.includes("data-pm-slice")),!1}}},appendTransaction:(d,h,p)=>{const m=d[0],g=m.getMeta("uiEvent")==="paste"&&!o,y=m.getMeta("uiEvent")==="drop"&&!s,w=m.getMeta("applyPasteRules"),k=!!w;if(!g&&!y&&!k)return;if(k){let{text:v}=w;typeof v=="string"?v=v:v=Ll(D.from(v),p.schema);const{from:x}=w,T=x+v.length,A=TR(v);return l({rule:u,state:p,from:x,to:{b:T},pasteEvt:A})}const b=h.doc.content.findDiffStart(p.doc.content),S=h.doc.content.findDiffEnd(p.doc.content);if(!(!SR(b)||!S||b===S.b))return l({rule:u,state:p,from:b,to:S,pasteEvt:i})}}))}var ql=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=sf(t),this.schema=b1(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Ul(e.name,this.schema)},r=te(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return Vl([...this.extensions].reverse()).flatMap(r=>{const o={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:Ul(r.name,this.schema)},s=[],i=te(r,"addKeyboardShortcuts",o);let a={};if(r.type==="mark"&&te(r,"exitable",o)&&(a.ArrowRight=()=>Yi.handleExit({editor:t,mark:r})),i){const h=Object.fromEntries(Object.entries(i()).map(([p,m])=>[p,()=>m({editor:t})]));a={...a,...h}}const l=VO(a);s.push(l);const c=te(r,"addInputRules",o);if(T1(r,t.options.enableInputRules)&&c){const h=c();if(h&&h.length){const p=vR({editor:t,rules:h}),m=Array.isArray(p)?p:[p];s.push(...m)}}const u=te(r,"addPasteRules",o);if(T1(r,t.options.enablePasteRules)&&u){const h=u();if(h&&h.length){const p=MR({editor:t,rules:h});s.push(...p)}}const d=te(r,"addProseMirrorPlugins",o);if(d){const h=d();s.push(...h)}return s})}get attributes(){return y1(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=js(this.extensions);return Object.fromEntries(e.filter(n=>!!te(n,"addNodeView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),o={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:wt(n.name,this.schema)},s=te(n,"addNodeView",o);if(!s)return[];const i=s();if(!i)return[];const a=(l,c,u,d,h)=>{const p=Fl(l,r);return i({node:l,view:c,getPos:u,decorations:d,innerDecorations:h,editor:t,extension:n,HTMLAttributes:p})};return[n.name,a]}))}dispatchTransaction(t){const{editor:e}=this;return Vl([...this.extensions].reverse()).reduceRight((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:Ul(o.name,this.schema)},i=te(o,"dispatchTransaction",s);return i?a=>{i.call(s,{transaction:a,next:r})}:r},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=js(this.extensions);return Object.fromEntries(e.filter(n=>!!te(n,"addMarkView")).map(n=>{const r=this.attributes.filter(a=>a.type===n.name),o={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:Ir(n.name,this.schema)},s=te(n,"addMarkView",o);if(!s)return[];const i=(a,l,c)=>{const u=Fl(a,r);return s()({mark:a,view:l,inline:c,editor:t,extension:n,HTMLAttributes:u,updateAttributes:d=>{VR(a,t,d)}})};return[n.name,i]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Ul(e.name,this.schema)};e.type==="mark"&&((n=Pe(te(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const o=te(e,"onBeforeCreate",r),s=te(e,"onCreate",r),i=te(e,"onUpdate",r),a=te(e,"onSelectionUpdate",r),l=te(e,"onTransaction",r),c=te(e,"onFocus",r),u=te(e,"onBlur",r),d=te(e,"onDestroy",r);o&&this.editor.on("beforeCreate",o),s&&this.editor.on("create",s),i&&this.editor.on("update",i),a&&this.editor.on("selectionUpdate",a),l&&this.editor.on("transaction",l),c&&this.editor.on("focus",c),u&&this.editor.on("blur",u),d&&this.editor.on("destroy",d)})}};ql.resolve=sf,ql.sort=Vl,ql.flatten=of;var _R={};Qd(_R,{ClipboardTextSerializer:()=>B1,Commands:()=>P1,Delete:()=>N1,Drop:()=>D1,Editable:()=>O1,FocusEvents:()=>z1,Keymap:()=>$1,Paste:()=>L1,Tabindex:()=>F1,TextDirection:()=>V1,focusEventsPluginKey:()=>R1});var $e=class Iv extends uf{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Iv(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},B1=$e.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new at({key:new Wt("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:o}=e,{ranges:s}=o,i=Math.min(...s.map(u=>u.$from.pos)),a=Math.max(...s.map(u=>u.$to.pos)),l=C1(n);return E1(r,{from:i,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:l})}}})]}}),P1=$e.create({name:"commands",addCommands(){return{...i1}}}),N1=$e.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,o;const s=()=>{var i,a,l,c;if((c=(l=(a=(i=this.editor.options.coreExtensionOptions)==null?void 0:i.delete)==null?void 0:a.filterTransaction)==null?void 0:l.call(a,t))!=null?c:t.getMeta("y-sync$"))return;const u=N3(t.before,[t,...e]);H3(u).forEach(p=>{u.mapping.mapResult(p.oldRange.from).deletedAfter&&u.mapping.mapResult(p.oldRange.to).deletedBefore&&u.before.nodesBetween(p.oldRange.from,p.oldRange.to,(m,g)=>{const y=g+m.nodeSize-2,w=p.oldRange.from<=g&&y<=p.oldRange.to;this.editor.emit("delete",{type:"node",node:m,from:g,to:y,newFrom:u.mapping.map(g),newTo:u.mapping.map(y),deletedRange:p.oldRange,newRange:p.newRange,partial:!w,editor:this.editor,transaction:t,combinedTransform:u})})});const h=u.mapping;u.steps.forEach((p,m)=>{var g,y;if(p instanceof Fn){const w=h.slice(m).map(p.from,-1),k=h.slice(m).map(p.to),b=h.invert().map(w,-1),S=h.invert().map(k),v=(g=u.doc.nodeAt(w-1))==null?void 0:g.marks.some(T=>T.eq(p.mark)),x=(y=u.doc.nodeAt(k))==null?void 0:y.marks.some(T=>T.eq(p.mark));this.editor.emit("delete",{type:"mark",mark:p.mark,from:p.from,to:p.to,deletedRange:{from:b,to:S},newRange:{from:w,to:k},partial:!!(x||v),editor:this.editor,transaction:t,combinedTransform:u})}})};(o=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||o?setTimeout(s,0):s()}}),D1=$e.create({name:"drop",addProseMirrorPlugins(){return[new at({key:new Wt("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),O1=$e.create({name:"editable",addProseMirrorPlugins(){return[new at({key:new Wt("editable"),props:{editable:()=>this.editor.options.editable}})]}}),R1=new Wt("focusEvents"),z1=$e.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new at({key:R1,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),$1=$e.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:i})=>[()=>i.undoInputRule(),()=>i.command(({tr:a})=>{const{selection:l,doc:c}=a,{empty:u,$anchor:d}=l,{pos:h,parent:p}=d,m=d.parent.isTextblock&&h>0?a.doc.resolve(h-1):d,g=m.parent.type.spec.isolating,y=d.pos-d.parentOffset,w=g&&m.parent.childCount===1?y===d.pos:fe.atStart(c).from===h;return!u||!p.type.isTextblock||p.textContent.length||!w||w&&d.parent.type.name==="paragraph"?!1:i.clearNodes()}),()=>i.deleteSelection(),()=>i.joinBackward(),()=>i.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:i})=>[()=>i.deleteSelection(),()=>i.deleteCurrentNode(),()=>i.joinForward(),()=>i.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:i})=>[()=>i.newlineInCode(),()=>i.createParagraphNear(),()=>i.liftEmptyBlock(),()=>i.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},o={...r},s={...r,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return zl()||h1()?s:o},addProseMirrorPlugins(){return[new at({key:new Wt("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(g=>g.getMeta("composition")))return;const r=t.some(g=>g.docChanged)&&!e.doc.eq(n.doc),o=t.some(g=>g.getMeta("preventClearDocument"));if(!r||o)return;const{empty:s,from:i,to:a}=e.selection,l=fe.atStart(e.doc).from,c=fe.atEnd(e.doc).to;if(s||!(i===l&&a===c)||!jl(n.doc))return;const h=n.tr,p=Dl({state:n,transaction:h}),{commands:m}=new Ol({editor:this.editor,state:p});if(m.clearNodes(),!!h.steps.length)return h}})]}}),L1=$e.create({name:"paste",addProseMirrorPlugins(){return[new at({key:new Wt("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),F1=$e.create({name:"tabindex",addProseMirrorPlugins(){return[new at({key:new Wt("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),V1=$e.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=js(this.extensions);return[{types:t.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const n=e.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new at({key:new Wt("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),AR=class Js{constructor(e,n,r=!1,o=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=o}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new Js(n,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new Js(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new Js(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const o=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,i=this.pos+r+(s?0:1);if(i<0||i>this.resolvedPos.doc.nodeSize-2)return;const a=this.resolvedPos.doc.resolve(i);if(!o&&a.depth<=this.depth)return;const l=new Js(a,this.editor,o,o?n:null);o&&(l.actualDepth=this.depth+1),e.push(new Js(a,this.editor,o,o?n:null))}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let r=null,o=this.parent;for(;o&&!r;){if(o.node.type.name===e)if(Object.keys(n).length>0){const s=o.node.attrs,i=Object.keys(n);for(let a=0;a<i.length;a+=1){const l=i[a];if(s[l]!==n[l])break}}else r=o;o=o.parent}return r}querySelector(e,n={}){return this.querySelectorAll(e,n,!0)[0]||null}querySelectorAll(e,n={},r=!1){let o=[];if(!this.children||this.children.length===0)return o;const s=Object.keys(n);return this.children.forEach(i=>{r&&o.length>0||(i.node.type.name===e&&s.every(l=>n[l]===i.node.attrs[l])&&o.push(i),!(r&&o.length>0)&&(o=o.concat(i.querySelectorAll(e,n,r))))}),o}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},IR=`.ProseMirror {
69
+ </svg>`}var I2={drag:{makeSvg:()=>_2,hotspot:[12,12],rotationOffset:0},ns:{makeSvg:el,hotspot:[12,12],rotationOffset:0},ew:{makeSvg:el,hotspot:[12,12],rotationOffset:Math.PI/2},nwse:{makeSvg:el,hotspot:[12,12],rotationOffset:-Math.PI/4},nesw:{makeSvg:el,hotspot:[12,12],rotationOffset:Math.PI/4},rotateNW:{makeSvg:tl,hotspot:[16,16],rotationOffset:0},rotateNE:{makeSvg:tl,hotspot:[16,16],rotationOffset:Math.PI/2},rotateSW:{makeSvg:tl,hotspot:[16,16],rotationOffset:-Math.PI/2},rotateSE:{makeSvg:tl,hotspot:[16,16],rotationOffset:-Math.PI}},ye={Idle:"idle",Pointing:"pointing",Dragging:"dragging",SelectionBoxPointing:"selectionBoxPointing",SelectionBoxDragging:"selectionBoxDragging"},On={None:"none",Idle:"idle",Editing:"editing"},Rn={Scale:"scale",Stretch:"stretch",Rotate:"rotate"},Sn={Idle:"idle",Waiting:"waiting",Scrolling:"scrolling"},Mg=qt({enabled:Lt().default(!0),edgeSizePx:Je().default(10),edgeScrollSpeedPxPerFrame:Je().default(15),edgeScrollDelayMs:Je().default(250)}),B2=qt({edgeScrolling:Mg.default(Mg.parse({}))}),$e=Ze({name:"transformHandle"},{kind:C.string().max(16).default(Rn.Scale),vectorX:C.int8().default(0),vectorY:C.int8().default(0),transformBox:C.ref(),cursorKind:C.string().max(16).default("drag")}),Ag="selection";function N2(t,e,n){var o;const r={...n};for(const[s,i]of Object.entries(e))if(((o=i==null?void 0:i.def)==null?void 0:o.type)==="ref"){const a=n[s];r[s]=P2(t,a)}return r}function P2(t,e){return e==null||!O(t,e,de)?null:de.read(t,e).id}function D2(t){var n;const e=[];for(const[r,o]of Object.entries(t))((n=o==null?void 0:o.def)==null?void 0:n.type)==="ref"&&e.push(r);return e}function O2(t,e,n,r,o){var i;const s=n.write(t,e);for(const[a,l]of Object.entries(n.schema))if(((i=l==null?void 0:l.def)==null?void 0:i.type)==="ref"){const c=r[a];c!=null&&(s[a]=o.get(c)??null)}}var R2=re(t=>t.with(pt));re(t=>t.with(A));function Ds(t,e){if(O(t,e,pt)||Ru(t,e))return;const{sessionId:n}=Ve(t);J(t,e,pt,{}),O(t,e,Tt)||J(t,e,Tt,{sessionId:n})}function xi(t,e){O(t,e,pt)&&(nn(t,e,pt),nn(t,e,Tt))}function _g(t){for(const e of R2.current(t))xi(t,e)}function z2(t){let e=0;for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);e=(e<<5)-e+r,e=e&e}return Math.abs(e)}var $2=class{constructor(t){this.seed=typeof t=="string"?z2(t):t}next(){return this.seed=(this.seed*9301+49297)%233280,this.seed/233280}nextInt(t,e){return Math.floor(this.next()*(e-t+1))+t}nextHex(){return this.nextInt(0,15).toString(16)}};function ju(t,e){const n=t+e,r=new $2(n);let o="";for(let s=0;s<32;s++)(s===8||s===12||s===16||s===20)&&(o+="-"),s===12?o+="4":s===16?o+=["8","9","a","b"][r.nextInt(0,3)]:o+=r.nextHex();return o}var Ig={};Ns(Ig,{Clipboard:()=>Ti,ScrollEdgesStateSingleton:()=>Zu,SelectionStateSingleton:()=>zn,TransformBoxStateSingleton:()=>Ku});var L2={count:C.uint32().default(0),center:C.tuple(C.float64(),2).default([0,0])},nl=new WeakMap,V2=class extends St{constructor(){super({name:"clipboard"},L2)}setEntities(t,e){const{editor:n}=Ve(t);nl.set(n,e)}getEntities(t){const{editor:e}=Ve(t);return nl.get(e)??[]}clearEntities(t){const{editor:e}=Ve(t);nl.delete(e)}hasContent(t){const{editor:e}=Ve(t),n=nl.get(e);return n!==void 0&&n.length>0}},Ti=new V2,Zu=to("scrollEdgesState",{state:C.enum(Sn).default(Sn.Idle),edgeEnterStartTime:C.float64().default(0)}),zn=to("selectionState",{state:C.enum(ye).default(ye.Idle),dragStart:C.tuple(C.float64(),2).default([0,0]),pointingStartClient:C.tuple(C.float64(),2).default([0,0]),pointingStartWorld:C.tuple(C.float64(),2).default([0,0]),draggedEntityStart:C.tuple(C.float64(),2).default([0,0]),draggedEntity:C.ref(),cloneGeneratorSeed:C.string().max(36).default(""),isCloning:C.boolean()}),Ku=to("transformBoxState",{state:C.string().max(32).default(On.None),transformBoxId:C.ref()}),Bg={};Ns(Bg,{hoverCursorSystem:()=>W2,scrollEdgesSystem:()=>H2,transformBoxSystem:()=>K2});var Yu=re(t=>t.with(Gr,$e).tracking(Gr)),F2=re(t=>t.with(A,Ft).tracking(A)),W2=ge({phase:"capture"},t=>{const e=Yu.added(t),n=Yu.removed(t),r=Yu.current(t),o=F2.changed(t);if(r.length===0&&n.length>0){vn.clearContextCursor(t);return}if((e.length>0||o.length>0)&&r.length>0){const i=r[0],a=$e.read(t,i);if(a.transformBox===null)return;const l=A.read(t,a.transformBox),c=vn.read(t);(a.cursorKind!==c.contextCursorKind||l.rotateZ!==c.contextRotation)&&vn.setContextCursor(t,a.cursorKind,l.rotateZ)}});function rl(t){return As(t,Ag).edgeScrolling}var U2=br({guards:{isPointerNearEdge:({event:t})=>{const{edgeSizePx:e}=rl(t.ctx),n=Mt.read(t.ctx),r=n.width,o=n.height,s=t.screenPosition[0],i=t.screenPosition[1];return s<e||s>r-e||i<e||i>o-e},isEdgeScrollDelayPassed:({context:t,event:e})=>{const{edgeScrollDelayMs:n}=rl(e.ctx);return performance.now()-t.edgeEnterStartTime>=n}},actions:{setEdgeEnterStartTime:Re({edgeEnterStartTime:()=>performance.now()}),moveCamera:({event:t})=>{const{edgeSizePx:e,edgeScrollSpeedPxPerFrame:n}=rl(t.ctx),r=Mt.read(t.ctx),o=he.read(t.ctx),s=r.width,i=r.height,a=t.screenPosition[0],l=t.screenPosition[1];let c=0,u=0;const f=n/o.zoom;if(a<e?c=-f:a>s-e&&(c=f),l<e?u=-f:l>i-e&&(u=f),c===0&&u===0)return;const h=he.write(t.ctx);h.left+=c,h.top+=u},resetContext:Re({edgeEnterStartTime:0})}}).createMachine({id:"scrollEdges",initial:Sn.Idle,context:{edgeEnterStartTime:0},states:{[Sn.Idle]:{entry:"resetContext",on:{pointerMove:{guard:"isPointerNearEdge",target:Sn.Waiting}}},[Sn.Waiting]:{entry:"setEdgeEnterStartTime",on:{pointerMove:{guard:Mo("isPointerNearEdge"),target:Sn.Idle},frame:{guard:"isEdgeScrollDelayPassed",target:Sn.Scrolling}}},[Sn.Scrolling]:{on:{frame:[{guard:Mo("isPointerNearEdge"),target:Sn.Idle},{actions:"moveCamera"}]}}}}),H2=ge({phase:"capture"},t=>{if(!rl(t).enabled)return;const e=zn.read(t).state;if(e!==ye.Dragging&&e!==ye.SelectionBoxDragging)return;const n=Zu.read(t).state,r=n===Sn.Waiting||n===Sn.Scrolling,o=et.getButtons(t,"select"),s=xr(t,o,{includeFrameEvent:r});s.length!==0&&Zu.run(t,U2,s)}),ol=re(t=>t.with(A).tracking(pt)),j2=br({guards:{isSelectionEditable:({event:t})=>Z2(t.ctx),isOverTransformBox:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:O(t.ctx,t.intersects[0],Ft),isOverTransformHandle:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:O(t.ctx,t.intersects[0],$e),selectionIsTransformable:({event:t})=>{if(t.type!=="selectionChanged")return!1;if(t.selectedEntityIds.length>1)return!0;if(t.selectedEntityIds.length===0)return!1;const e=t.selectedEntityIds[0],n=A.read(t.ctx,e);return Vt(t.ctx,n.tag).resizeMode!=="groupOnly"},hasEditAfterPlacing:({event:t})=>t.type!=="selectionChanged"||t.selectedEntityIds.length!==1?!1:O(t.ctx,t.selectedEntityIds[0],Ci)},actions:{addTransformBox:Re(({context:t,event:e},n)=>{t.transformBoxId!==null&&Hu.spawn(e.ctx,{transformBoxId:t.transformBoxId});const r=bt(e.ctx);return Sg.spawn(e.ctx,{transformBoxId:r,skipHandles:n==null?void 0:n.skipHandles}),{transformBoxId:r}}),updateTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Uu.spawn(e.ctx,{transformBoxId:t.transformBoxId})},hideTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Eg.spawn(e.ctx,{transformBoxId:t.transformBoxId})},showTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Cg.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Hu.spawn(e.ctx,{transformBoxId:t.transformBoxId})},clearTransformBoxId:Re({transformBoxId:()=>null}),startTransformBoxEdit:({context:t,event:e})=>{t.transformBoxId!==null&&xg.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeEditAfterPlacing:({event:t})=>{if(t.type==="selectionChanged")for(const e of t.selectedEntityIds)O(t.ctx,e,Ci)&&nn(t.ctx,e,Ci)}}}).createMachine({id:"transformBox",initial:On.None,context:{transformBoxId:null},states:{[On.None]:{entry:["removeTransformBox","clearTransformBoxId"],on:{selectionChanged:[{guard:di(["hasEditAfterPlacing","selectionIsTransformable","isSelectionEditable"]),actions:[{type:"addTransformBox",params:{skipHandles:!0}},"removeEditAfterPlacing"],target:On.Editing},{guard:"selectionIsTransformable",target:On.Idle}]}},[On.Idle]:{entry:["addTransformBox"],on:{selectionChanged:[{guard:Mo("selectionIsTransformable"),target:On.None},{guard:"selectionIsTransformable",actions:"showTransformBox"},{actions:"updateTransformBox"}],pointerDown:{actions:"hideTransformBox"},pointerUp:{actions:"showTransformBox"},click:{guard:di(["isOverTransformBox","isSelectionEditable"]),target:On.Editing}}},[On.Editing]:{entry:["hideTransformBox","startTransformBoxEdit"],on:{pointerDown:{guard:di([Mo("isOverTransformBox"),Mo("isOverTransformHandle")]),target:On.None},selectionChanged:{target:On.None,actions:Wa(({event:t})=>t)}}}}});function Z2(t){const e=ol.current(t);if(e.length!==1)return!1;const n=e[0],r=A.read(t,n);return Wm(t,r.tag)}var K2=ge({phase:"capture"},t=>{const e=[],n=ol.added(t),r=ol.removed(t);if(n.length>0||r.length>0){const i=[...ol.current(t)],a={type:"selectionChanged",ctx:t,selectedEntityIds:i};e.push(a)}const o=et.getButtons(t,"select"),s=xr(t,o);e.push(...s),e.length!==0&&Ku.run(t,j2,e)}),Ng={};Ns(Ng,{transformBoxSystem:()=>J2});var sl=re(t=>t.with(A,pt)),Y2=re(t=>t.with(A,Sr)),q2="a",X2="b",Pg="c",G2="d",J2=ge({phase:"update",priority:-100},t=>{ae(t,Hu,(e,{transformBoxId:n})=>{Q2(e,n)}),ae(t,Sg,(e,{transformBoxId:n,skipHandles:r})=>{eI(e,n,r)}),ae(t,Uu,(e,{transformBoxId:n})=>{qu(e,n)}),ae(t,Eg,(e,{transformBoxId:n})=>{nI(e,n)}),ae(t,Cg,(e,{transformBoxId:n})=>{rI(e,n)}),ae(t,xg,(e,{transformBoxId:n})=>{oI(e,n)}),ae(t,A2,Xu)});function Q2(t,e){if(!O(t,e,Ft)){Xu(t);return}const n=Jn(t,e,$e,"transformBox");for(const r of n)qe(t,r);qe(t,e),Xu(t)}function eI(t,e,n){J(t,e,A,{tag:"transform-box",position:[0,0],size:[0,0],rotateZ:0,rank:q2}),J(t,e,Ft,{}),J(t,e,lt,{position:[0,0],size:[0,0],rotateZ:0,fontSize:16}),n||qu(t,e)}function qu(t,e){if(!jb(t,e))return;const n=sl.current(t);if(n.length===0)return;let r=0;r=A.read(t,n[0]).rotateZ;for(let c=1;c<n.length;c++){const u=A.read(t,n[c]);if(Math.abs(r-u.rotateZ)>.01){r=0;break}}if(n.length===0)return;const s=[];for(const c of n){const u=A.getCorners(t,c);s.push(...u)}if(s.length===0)return;const i=A.write(t,e);if(i.rotateZ=r,st.boundPoints(i.position,i.size,r,s),!(zn.read(t).state===ye.Dragging)){if(O(t,e,lt)){const c=lt.write(t,e);c.position=i.position,c.size=i.size,c.rotateZ=r}for(const c of n){const u=A.read(t,c),f=O(t,c,at)?at.read(t,c).fontSizePx:16;if(!O(t,c,lt))J(t,c,lt,{position:u.position,size:u.size,rotateZ:u.rotateZ,flip:u.flip,fontSize:f});else{const h=lt.write(t,c);h.position=u.position,h.size=u.size,h.rotateZ=u.rotateZ,h.flip=u.flip,h.fontSize=f}}}tI(t,e)}function tI(t,e){const n=A.read(t,e),{position:r,size:o,rotateZ:s}=n,i=r[0],a=r[1],l=o[0],c=o[1],u=[i+l/2,a+c/2],f=12,h=2*f,p=1.25*f,m=[],g=["rotateNW","rotateNE","rotateSW","rotateSE"],y=sl.current(t);let w="scale";if(y.length===1){const M=A.read(t,y[0]);w=Vt(t,M.tag).resizeMode}else y.length>1&&y.every(V=>{const K=A.read(t,V);return Vt(t,K.tag).resizeMode==="free"})&&(w="free");const k=y.every(M=>{const V=A.read(t,M);return Vt(t,V.tag).canRotate}),b=y.every(M=>{const V=A.read(t,M);return Vt(t,V.tag).canScale});let S;switch(w){case"scale":case"text":S=Rn.Scale;break;case"free":S=Rn.Stretch;break;default:S=Rn.Scale;break}const v=he.read(t),E=l*v.zoom,T=c*v.zoom,_=Math.min(E,T),I=15;for(let M=0;M<2;M++)for(let V=0;V<2;V++)M+V!==1&&_<I/2||M+V===1&&T<I||(b&&m.push({tag:"transform-handle",kind:S,vectorX:M*2-1,vectorY:V*2-1,left:i+l*M-f/2,top:a+c*V-f/2,width:f,height:f,rotateZ:s,rank:G2,cursorKind:M+V===1?"nesw":"nwse",scaleMultiplier:[1,1],anchor:[.5,.5]}),k&&m.push({tag:"transform-rotate",kind:Rn.Rotate,vectorX:M*2-1,vectorY:V*2-1,left:i+M*l-(1-M)*h,top:a+V*c-(1-V)*h,width:h,height:h,rotateZ:s,rank:X2,cursorKind:g[M+V*2],scaleMultiplier:[.5,.5],anchor:[1-M,1-V]}));if(b)for(let M=0;M<2;M++)m.push({tag:"transform-edge",kind:S,vectorX:0,vectorY:M*2-1,left:i,top:a+c*M-p/2,width:l,height:p,rotateZ:s,rank:Pg,cursorKind:"ns",scaleMultiplier:[0,1],anchor:[.5,.5]});if(b||w==="text")for(let M=0;M<2;M++)m.push({tag:"transform-edge",kind:w==="text"?Rn.Stretch:S,vectorX:M*2-1,vectorY:0,left:i+l*M-p/2,top:a,width:p,height:c,rotateZ:s,rank:Pg,cursorKind:"ew",scaleMultiplier:[1,0],anchor:[.5,.5]});const z=Jn(t,e,$e,"transformBox"),F=new Map;for(const M of z){const V=$e.read(t,M),K=`${V.kind}-${V.vectorX}-${V.vectorY}`;F.set(K,M)}const j=new Set;for(const M of m){const V=`${M.kind}-${M.vectorX}-${M.vectorY}`;let K=F.get(V);const se=[M.left+M.width/2,M.top+M.height/2],Y=L.clone(se);L.rotateAround(Y,u,s);const R=Y[0]-M.width/2,W=Y[1]-M.height/2;K||(K=bt(t),J(t,K,A),J(t,K,$e),J(t,K,lt),J(t,K,Qr));const Q=A.write(t,K);Q.tag=M.tag,Q.position=[R,W],Q.size=[M.width,M.height],Q.rotateZ=M.rotateZ,Q.rank=M.rank;const pe=$e.write(t,K);pe.transformBox=e,pe.kind=M.kind,pe.vectorX=M.vectorX,pe.vectorY=M.vectorY,pe.cursorKind=M.cursorKind;const me=lt.write(t,K);me.position=[R,W],me.size=[M.width,M.height],me.rotateZ=M.rotateZ;const Ue=Qr.write(t,K);Ue.startPosition=[R,W],Ue.startSize=[M.width,M.height],L.copy(Ue.scaleMultiplier,M.scaleMultiplier),L.copy(Ue.anchor,M.anchor),j.add(K)}for(const M of z)j.has(M)||qe(t,M)}function nI(t,e){if(!O(t,e,Ft))return;if(!O(t,e,Qe))J(t,e,Qe,{value:0});else{const r=Qe.write(t,e);r.value=0}const n=Jn(t,e,$e,"transformBox");for(const r of n)if(!O(t,r,Qe))J(t,r,Qe,{value:0});else{const o=Qe.write(t,r);o.value=0}}function rI(t,e){if(!O(t,e,Ft))return;const n=sl.current(t);if(n.length===0)return;if(n.length===1){const o=A.read(t,n[0]);if(Vt(t,o.tag).resizeMode==="groupOnly")return}O(t,e,Qe)&&nn(t,e,Qe);const r=Jn(t,e,$e,"transformBox");for(const o of r)O(t,o,Qe)&&nn(t,o,Qe);qu(t,e)}function oI(t,e){if(O(t,e,Ft)){const n=Jn(t,e,$e,"transformBox");for(const r of n)qe(t,r)}for(const n of sl.current(t))O(t,n,Sr)||J(t,n,Sr,{})}function Xu(t){for(const e of Y2.current(t))O(t,e,Sr)&&nn(t,e,Sr)}var Dg={};Ns(Dg,{selectSystem:()=>lI});var sI=4,Og=re(t=>t.with(A,pt,de)),iI=re(t=>t.with(A,Sr)),aI=br({guards:{isThresholdReached:({context:t,event:e})=>L.distance(t.pointingStartClient,e.screenPosition)>=sI,isOverBlock:({event:t})=>t.intersects.length>0,isOverSyncedBlock:({event:t})=>{const e=t.ctx;for(const n of t.intersects)if(O(e,n,de))return!0;return!1},isNotHeldByRemote:({event:t})=>{const e=t.ctx,n=t.intersects[0];return n?!Ru(e,n):!0},hasEditedBlocks:({event:t})=>iI.current(t.ctx).length>0},actions:{setPointingStart:Re({pointingStartClient:({event:t})=>t.screenPosition,pointingStartWorld:({event:t})=>t.worldPosition}),setDragStart:Re({dragStart:({event:t})=>t.worldPosition}),addHeldToDragged:({context:t,event:e})=>{t.draggedEntity!==null&&vg.spawn(e.ctx,{entityId:t.draggedEntity})},removeHeldFromDragged:({context:t,event:e})=>{t.draggedEntity!==null&&bg.spawn(e.ctx,{entityId:t.draggedEntity})},setDragCursor:({event:t,context:e})=>{if(e.draggedEntity)if(O(t.ctx,e.draggedEntity,$e)){const n=$e.read(t.ctx,e.draggedEntity),r=n.transformBox!==null?A.read(t.ctx,n.transformBox):void 0;Ja.spawn(t.ctx,{contextCursorKind:n.cursorKind,contextRotation:(r==null?void 0:r.rotateZ)??0})}else Ja.spawn(t.ctx,{contextCursorKind:"drag",contextRotation:0})},unsetDragCursor:({event:t})=>{Ja.spawn(t.ctx,{contextCursorKind:""})},setDraggedEntity:Re({draggedEntity:({event:t})=>t.intersects[0]??null,draggedEntityStart:({event:t})=>{if(!t.intersects.length)return[0,0];const e=t.intersects[0],n=A.read(t.ctx,e);return[n.position[0],n.position[1]]}}),resetDragged:({context:t,event:e})=>{t.draggedEntity!==null&&(Ei.spawn(e.ctx,{entityId:t.draggedEntity,position:t.draggedEntityStart}),t.isCloning&&Fu.spawn(e.ctx,{entityIds:[t.draggedEntity],seed:t.cloneGeneratorSeed}))},resetContext:Re({dragStart:()=>[0,0],pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],draggedEntityStart:()=>[0,0],draggedEntity:()=>null,cloneGeneratorSeed:()=>crypto.randomUUID(),isCloning:()=>!1}),createSelectionBox:({event:t})=>{yg.spawn(t.ctx,void 0)},removeSelectionBox:({event:t})=>{kg.spawn(t.ctx,void 0)},updateDragged:Re({isCloning:({context:t,event:e})=>{const n=e.ctx;if(t.draggedEntity===null)return!1;let r=t.draggedEntityStart[0]+e.worldPosition[0]-t.dragStart[0],o=t.draggedEntityStart[1]+e.worldPosition[1]-t.dragStart[1];const s=O(n,t.draggedEntity,de)||O(n,t.draggedEntity,Ft);if(e.shiftDown&&s){const a=Math.abs(e.worldPosition[0]-t.dragStart[0]),l=Math.abs(e.worldPosition[1]-t.dragStart[1]);a>l?o=t.draggedEntityStart[1]:r=t.draggedEntityStart[0]}s&&(r=Ot.snapX(n,r),o=Ot.snapY(n,o)),Ei.spawn(n,{entityId:t.draggedEntity,position:[r,o]});let i=t.isCloning;if(e.altDown&&s&&!t.isCloning){const a=t.draggedEntityStart[0]-r,l=t.draggedEntityStart[1]-o;i=!0;const u=O(n,t.draggedEntity,Ft)?Array.from(Og.current(n)):[t.draggedEntity];dg.spawn(n,{entityIds:u,offset:[a,l],seed:t.cloneGeneratorSeed})}else if(!e.altDown&&t.isCloning){const l=O(n,t.draggedEntity,Ft)?Array.from(Og.current(n)):[t.draggedEntity];Fu.spawn(n,{entityIds:l,seed:t.cloneGeneratorSeed}),i=!1}return i}}),resizeSelectionBox:({context:t,event:e})=>{const n=Math.min(t.pointingStartWorld[0],e.worldPosition[0]),r=Math.min(t.pointingStartWorld[1],e.worldPosition[1]),o=Math.max(t.pointingStartWorld[0],e.worldPosition[0]),s=Math.max(t.pointingStartWorld[1],e.worldPosition[1]);wg.spawn(e.ctx,{bounds:[n,r,o,s],deselectOthers:!e.shiftDown})},selectIntersect:({event:t})=>{const e=t.ctx;let n;for(const r of t.intersects)if(O(e,r,de)){n=r;break}n!==void 0&&(t.shiftDown?mg.spawn(e,{entityId:n}):Wu.spawn(e,{entityId:n,deselectOthers:!0}))},selectDragged:({context:t,event:e})=>{t.draggedEntity!==null&&O(e.ctx,t.draggedEntity,de)&&Wu.spawn(e.ctx,{entityId:t.draggedEntity,deselectOthers:!0})},deselectAllIfShiftNotDown:({event:t})=>{t.shiftDown||Ps.spawn(t.ctx,void 0)},deselectAllIfDraggedNotSelected:({context:t,event:e})=>{t.draggedEntity!==null&&(O(e.ctx,t.draggedEntity,pt)||O(e.ctx,t.draggedEntity,Ft)||O(e.ctx,t.draggedEntity,$e)||Ps.spawn(e.ctx,void 0))}}}).createMachine({id:"selection",initial:ye.Idle,context:{dragStart:[0,0],pointingStartClient:[0,0],pointingStartWorld:[0,0],draggedEntityStart:[0,0],draggedEntity:null,cloneGeneratorSeed:crypto.randomUUID(),isCloning:!1},states:{[ye.Idle]:{entry:["resetContext"],on:{pointerDown:[{guard:di(["isOverBlock","isNotHeldByRemote"]),target:ye.Pointing},{actions:"deselectAllIfShiftNotDown",target:ye.SelectionBoxPointing}]}},[ye.Pointing]:{entry:["setPointingStart","setDraggedEntity"],on:{pointerMove:{guard:di(["isThresholdReached",Mo("hasEditedBlocks")]),target:ye.Dragging},pointerUp:[{guard:"isOverSyncedBlock",actions:"selectIntersect",target:ye.Idle},{actions:"deselectAllIfShiftNotDown",target:ye.Idle}],cancel:{target:ye.Idle}}},[ye.Dragging]:{entry:["setDragStart","addHeldToDragged","setDragCursor","deselectAllIfDraggedNotSelected"],exit:["unsetDragCursor"],on:{pointerMove:{actions:"updateDragged"},pointerUp:{actions:"selectDragged",target:ye.Idle},cancel:{actions:["resetDragged","removeHeldFromDragged"],target:ye.Idle}}},[ye.SelectionBoxPointing]:{entry:["setPointingStart"],on:{pointerMove:{guard:"isThresholdReached",target:ye.SelectionBoxDragging},pointerUp:{target:ye.Idle},cancel:{target:ye.Idle}}},[ye.SelectionBoxDragging]:{entry:["setDragStart","createSelectionBox"],exit:"removeSelectionBox",on:{pointerMove:{actions:"resizeSelectionBox"},pointerUp:{target:ye.Idle},cancel:{target:ye.Idle}}}}}),lI=ge({phase:"capture",priority:100},t=>{let e=et.getButtons(t,"select");zn.read(t).state===ye.Dragging&&e.length===0&&(e=["left"]);const r=xr(t,e);r.length!==0&&zn.run(t,aI,r)}),Rg={};Ns(Rg,{blockSystem:()=>cI,dragHandlerSystem:()=>mI,selectSystem:()=>SI});var Os=re(t=>t.with(A,pt)),zg=re(t=>t.with(A,de)),cI=ge({phase:"update"},t=>{ae(t,Ei,(e,{entityId:n,position:r})=>{if(!O(e,n,A))return;const o=A.write(e,n);o.position=r}),ae(t,Wu,(e,{entityId:n,deselectOthers:r})=>{r&&Gu(e),Ds(e,n)}),ae(t,M2,(e,{entityId:n})=>{xi(e,n)}),ae(t,mg,(e,{entityId:n})=>{O(e,n,pt)?xi(e,n):Ds(e,n)}),ae(t,Ps,Gu),ae(t,vg,(e,{entityId:n})=>{if(!O(e,n,de)||O(e,n,Tt))return;const{sessionId:r}=Ve(e);J(e,n,Tt,{sessionId:r})}),ae(t,bg,(e,{entityId:n})=>{O(e,n,pt)||O(e,n,Tt)&&nn(e,n,Tt)}),ae(t,gg,e=>{for(const n of zg.current(e))Ds(e,n)}),ae(t,T2,(e,{entityId:n})=>{qe(e,n)}),ae(t,Vu,e=>{for(const n of Os.current(e))qe(e,n)}),ae(t,cg,uI),ae(t,ug,dI),ae(t,Ja,(e,n)=>{n.cursorKind!==void 0&&vn.setCursor(e,n.cursorKind,n.rotation??0),n.contextCursorKind!==void 0&&vn.setContextCursor(e,n.contextCursorKind,n.contextRotation??0),n.contextCursorKind===""&&vn.clearContextCursor(e)}),ae(t,hg,e=>{$g(e)}),ae(t,fg,e=>{$g(e);for(const n of Os.current(e))qe(e,n)}),ae(t,pg,(e,n)=>{fI(e,n==null?void 0:n.position)}),ae(t,dg,(e,{entityIds:n,offset:r,seed:o})=>{hI(e,n,r,o)}),ae(t,Fu,(e,{entityIds:n,seed:r})=>{pI(e,n,r)})});function Gu(t){for(const e of Os.current(t))xi(t,e)}function uI(t){const e=[...Os.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=A.read(t,n),s=A.read(t,r);return!o.rank&&!s.rank?0:o.rank?s.rank?o.rank<s.rank?-1:o.rank>s.rank?1:0:1:-1});for(const n of e){const r=A.write(t,n);r.rank=Dn.genNext(t)}}}function dI(t){const e=[...Os.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=A.read(t,n),s=A.read(t,r);return!o.rank&&!s.rank?0:o.rank?!s.rank||s.rank<o.rank?-1:s.rank>o.rank?1:0:1});for(const n of e){const r=A.write(t,n);r.rank=Dn.genPrev(t)}}}function $g(t){const e=[...Os.current(t)];if(e.length===0)return;const{componentsById:n}=Ve(t),r=new Map([...n].filter(([,c])=>c.sync==="document")),o=[],s=ee.zero();let i=!1;const a=de._getComponentId(t);for(const c of e){const u=new Map;O(t,c,de)&&u.set(a,de.snapshot(t,c));for(const f of t.entityBuffer.getComponentIds(c)){if(f===a)continue;const h=r.get(f);if(h){const p=h.snapshot(t,c),m=N2(t,h.schema,p);u.set(f,m)}}if(o.push(u),O(t,c,Be)){const{value:f}=Be.read(t,c);i?ee.union(s,f):(ee.copy(s,f),i=!0)}}Ti.setEntities(t,o);const l=Ti.write(t);l.count=o.length,l.center=ee.center(s)}function fI(t,e){const n=Ti.getEntities(t);if(n.length===0)return;const{componentsById:r}=Ve(t),o=new Map([...r].filter(([,h])=>h.sync==="document")),s=Ti.read(t),i=de._getComponentId(t),a=A._getComponentId(t);let l;if(e)l=L.clone(e),L.sub(l,s.center);else{const h=he.getWorldCenter(t);l=L.clone(h),L.sub(l,s.center),Ot.snapPosition(t,l)}const c=[...n].sort((h,p)=>{const m=h.get(a),g=p.get(a),y=(m==null?void 0:m.rank)??"",w=(g==null?void 0:g.rank)??"";return y<w?-1:y>w?1:0});Gu(t);const u=new Map,f=[];for(const h of c){const p=bt(t),m=h.get(i);m!=null&&m.id&&u.set(m.id,p),J(t,p,de,{id:crypto.randomUUID()});for(const[g,y]of h){if(g===i)continue;const w=o.get(g);if(!w)continue;const k={...y};if(g===a){const S=L.clone(k.position);L.add(S,l),k.position=S,k.rank=Dn.genNext(t)}const b=D2(w.schema);if(b.length>0){for(const S of b)delete k[S];f.push({entityId:p,componentDef:w,componentData:y})}J(t,p,w,k)}Ds(t,p)}for(const{entityId:h,componentDef:p,componentData:m}of f)O2(t,h,p,m,u)}function hI(t,e,n,r){const{componentsById:o}=Ve(t),s=new Map([...o].filter(([,c])=>c.sync==="document")),i=de._getComponentId(t),a=A._getComponentId(t),l=new Map;for(const c of e){if(!O(t,c,de))continue;const u=de.read(t,c),f=ju(u.id,r),h=bt(t);l.set(c,h),J(t,h,de,{id:f});for(const p of t.entityBuffer.getComponentIds(c)){if(p===i)continue;const m=s.get(p);if(!m)continue;const g={...m.snapshot(t,c)};if(p===a){const y=L.clone(g.position);L.add(y,n),g.position=y,g.rank=Dn.genPrev(t)}J(t,h,m,g)}}Lg(t,l)}function pI(t,e,n){const r=new Set;for(const i of e){if(!O(t,i,de))continue;const a=de.read(t,i);r.add(ju(a.id,n))}const o=[];for(const i of zg.current(t)){const a=de.read(t,i);r.has(a.id)&&o.push(i)}const s=new Map;for(const i of o){const a=de.read(t,i).id;for(const l of e){if(!O(t,l,de))continue;const c=de.read(t,l).id;if(ju(c,n)===a){s.set(i,l);break}}}Lg(t,s);for(const i of o)qe(t,i)}function Lg(t,e){for(const[n,r]of e){for(const o of Jn(t,n,ze,"startBlock"))ze.write(t,o).startBlock=r;for(const o of Jn(t,n,ze,"endBlock"))ze.write(t,o).endBlock=r}}var Ju=re(t=>t.with(A,pt)),Vg=re(t=>t.with(A,Ft,lt)),mI=ge({phase:"update"},t=>{ae(t,Ei,(e,{entityId:n,position:r})=>{if(O(e,n,Ft)){gI(e,n,r);return}if(O(e,n,$e)){yI(e,n,r);return}})});function gI(t,e,n){const r=lt.read(t,e),o=n[0]-r.position[0],s=n[1]-r.position[1];for(const i of Ju.current(t)){if(!O(t,i,lt))continue;const a=lt.read(t,i),l=A.write(t,i);l.position=[a.position[0]+o,a.position[1]+s],Ot.snapPosition(t,l.position)}}function yI(t,e,n){const r=$e.read(t,e);r.kind===Rn.Rotate?wI(t,e,n):r.kind===Rn.Scale?Fg(t,e,n,!0):r.kind===Rn.Stretch&&Fg(t,e,n,!1)}function wI(t,e,n){const r=Vg.current(t);if(r.length===0){console.warn("No transform box found for rotation");return}const o=r[0],s=A.write(t,o),i=A.getCenter(t,o),a=A.read(t,e),l=[n[0]+a.size[0]/2,n[1]+a.size[1]/2],c=L.angleTo(i,l),u=lt.read(t,o),f=$e.read(t,e),h=L.angle([s.size[0]*f.vectorX,s.size[1]*f.vectorY])+u.rotateZ;let p=c-h;const m=Ot.read(t),g=cn.read(t);let y=0;if(g.shiftDown?y=m.shiftSnapAngleRad:m.enabled&&(y=m.snapAngleRad),y>0){const w=u.rotateZ%y;p=Math.round(p/y)*y-w}s.rotateZ=xt.normalizeAngle(u.rotateZ+p);for(const w of Ju.current(t)){if(!O(t,w,lt))continue;const k=lt.read(t,w),b=A.write(t,w);b.rotateZ=xt.normalizeAngle(k.rotateZ+p);const S=[k.position[0]+k.size[0]/2,k.position[1]+k.size[1]/2],v=L.distance(i,S),E=L.angleTo(i,S)+p,T=L.fromPolar(v,E,i);b.position=[T[0]-b.size[0]/2,T[1]-b.size[1]/2],m.strict&&Ot.snapPosition(t,b.position)}}function Fg(t,e,n,r){const o=Vg.current(t);if(o.length===0){console.warn("No transform box found for scaling");return}const s=o[0],i=lt.read(t,s),a=$e.read(t,e),l=A.read(t,e),c=[n[0]+l.size[0]/2,n[1]+l.size[1]/2];Ot.snapPosition(t,c);const u=i.rotateZ,f=[i.position[0]+i.size[0]/2,i.position[1]+i.size[1]/2],h=[-a.vectorX*i.size[0]/2,-a.vectorY*i.size[1]/2];L.rotate(h,u);const p=[f[0]+h[0],f[1]+h[1]],m=[c[0]-p[0],c[1]-p[1]],g=L.clone(m);L.rotate(g,-u);let y=a.vectorX,w=a.vectorY,k=!1,b=!1;Math.sign(g[0])!==y&&y!==0&&(y=-y,k=!0),Math.sign(g[1])!==w&&w!==0&&(w=-w,b=!0);let S=Math.max(Math.abs(g[0]),1),v=Math.max(Math.abs(g[1]),1);if(r){const j=i.size[0]/i.size[1];S/v>j?v=S/j:S=v*j}else a.vectorX===0?S=i.size[0]:a.vectorY===0&&(v=i.size[1]);const E=i.size[0]>0?S/i.size[0]:1,T=i.size[1]>0?v/i.size[1]:1,_=Ot.read(t),I=L.create(y*S,w*v);L.rotate(I,u),L.scale(I,.5);const z=L.clone(p);L.add(z,I);const F=[E,T];for(const j of Ju.current(t)){if(!O(t,j,lt))continue;const M=lt.read(t,j),V=A.write(t,j),K=L.clone(M.position);L.add(K,[M.size[0]/2,M.size[1]/2]);const se=L.clone(K);L.sub(se,f),L.rotate(se,-u),L.multiply(se,F),k&&(se[0]=-se[0]),b&&(se[1]=-se[1]),L.rotate(se,u);const Y=L.clone(z);L.add(Y,se);const R=L.clone(M.size);L.multiply(R,F);const W=Vt(t,V.tag),Q=(W==null?void 0:W.resizeMode)==="text";if(_.strict)if(Q&&r){R[1]=Math.max(_.rowHeight,Ot.snapY(t,R[1]));const pe=M.size[0]/M.size[1];R[0]=R[1]*pe}else Ot.snapSize(t,R);if(L.copy(V.position,Y),L.sub(V.position,[R[0]/2,R[1]/2]),_.strict&&Ot.snapPosition(t,V.position),!r&&a.vectorY===0?V.size[0]=R[0]:!r&&a.vectorX===0?V.size[1]=R[1]:L.copy(V.size,R),O(t,j,at)){const pe=a.kind===Rn.Stretch,me=at.write(t,j);if(pe)me.constrainWidth=!0;else{const Ue=M.size[1]>0?R[1]/M.size[1]:1;me.fontSizePx=M.fontSize*Ue}}V.flip=[k!==M.flip[0],b!==M.flip[1]]}}var kI=re(t=>t.with(A,pt)),Wg=re(t=>t.with(A,Qa)),vI=re(t=>t.with(A,de,Be)),bI="z",SI=ge({phase:"update"},t=>{ae(t,yg,e=>{const n=bt(e);J(e,n,A,{tag:"selection-box",position:[0,0],size:[0,0],rotateZ:0,rank:bI}),J(e,n,Qa,{})}),ae(t,wg,(e,{bounds:n,deselectOthers:r})=>{const o=Wg.current(e);if(o.length===0){console.warn("Can't update selection box: not found");return}const s=o[0],i=A.write(e,s),a=n[0],l=n[1],c=n[2]-n[0],u=n[3]-n[1];i.position=[a,l],i.size=[c,u];const f=N_(e,n,vI.current(e));if(r)for(const h of kI.current(e))!f.includes(h)&&xi(e,h);for(const h of f)Ds(e,h)}),ae(t,kg,e=>{const n=Wg.current(e);if(n.length===0){console.warn("Can't remove selection box: not found");return}const r=n[0];qe(e,r)})}),il=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function EI(t={}){return{name:Ag,resources:B2.parse(t),components:Object.values(Tg).filter(e=>e instanceof Kt),singletons:Object.values(Ig).filter(e=>e instanceof St),blockDefs:[{tag:"selection-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[Qa]},{tag:"transform-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ft]},{tag:"transform-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[$e]},{tag:"transform-edge",stratum:"overlay",canRotate:!1,canScale:!1,components:[$e]},{tag:"transform-rotate",stratum:"overlay",canRotate:!1,canScale:!1,components:[$e]}],systems:[...il(Dg),...il(Bg),...il(Rg),...il(Ng)],keybinds:[{command:fg.name,key:Gt.X,mod:!0},{command:hg.name,key:Gt.C,mod:!0},{command:pg.name,key:Gt.V,mod:!0},{command:Vu.name,key:Gt.Delete},{command:gg.name,key:Gt.A,mod:!0},{command:cg.name,key:Gt.BracketRight},{command:ug.name,key:Gt.BracketLeft}],cursors:I2}}var CI=Object.defineProperty,Ug=(t,e)=>{for(var n in e)CI(t,n,{get:e[n],enumerable:!0})},Hg={};Ug(Hg,{ArcArrow:()=>we,ArrowHandle:()=>Ln,ArrowTerminal:()=>Mi,ElbowArrow:()=>Ce});var xI="arrows",jg="zzzzz",TI=24,Zg=50,Qu=4,MI=4,ed=24,no=24,Kg=40,$n={Idle:"idle",Pointing:"pointing",Dragging:"dragging"},Rs={None:"none",Idle:"idle"},_e={Start:"start",Middle:"middle",End:"end"},Te={None:"none",V:"v",Delta:"delta",Circle:"circle",Diamond:"diamond"},Do={Arc:"arc",Elbow:"elbow"},al=0,ll=1,cl=2,ul=3,dl=4,fl=5,td=6,AI={value:C.tuple(C.float64(),7).default([0,0,.5,.5,1,1,Qu]),startArrowHead:C.enum(Te).default(Te.None),endArrowHead:C.enum(Te).default(Te.V),trimStart:C.float64().default(0),trimEnd:C.float64().default(1)},_I=class extends Kt{constructor(){super({name:"arcArrow",sync:"document"},AI)}getA(t,e){const{value:n}=this.read(t,e);return[n[al],n[ll]]}getB(t,e){const{value:n}=this.read(t,e);return[n[cl],n[ul]]}getC(t,e){const{value:n}=this.read(t,e);return[n[dl],n[fl]]}getThickness(t,e){const{value:n}=this.read(t,e);return n[td]}setA(t,e,n){const{value:r}=this.write(t,e);r[al]=n[0],r[ll]=n[1]}setB(t,e,n){const{value:r}=this.write(t,e);r[cl]=n[0],r[ul]=n[1]}setC(t,e,n){const{value:r}=this.write(t,e);r[dl]=n[0],r[fl]=n[1]}setThickness(t,e,n){const{value:r}=this.write(t,e);r[td]=n}getWorldArc(t,e){const{value:n}=this.read(t,e),r=A.uvToWorld(t,e,[n[al],n[ll]]),o=A.uvToWorld(t,e,[n[cl],n[ul]]),s=A.uvToWorld(t,e,[n[dl],n[fl]]);return[r[0],r[1],o[0],o[1],s[0],s[1],n[td]]}getWorldPoints(t,e){const{value:n}=this.read(t,e);return{a:A.uvToWorld(t,e,[n[al],n[ll]]),b:A.uvToWorld(t,e,[n[cl],n[ul]]),c:A.uvToWorld(t,e,[n[dl],n[fl]])}}isCurved(t,e){const{value:n}=this.read(t,e);return!Me.isCollinear(n)}directionAt(t,e,n){const r=this.getWorldArc(t,e);return Me.directionAt(r,n)}pointAt(t,e,n){const r=this.getWorldArc(t,e);return Me.parametricToPoint(r,n)}length(t,e){const n=this.getWorldArc(t,e);return Me.length(n)}containsPoint(t,e,n){const r=this.getWorldArc(t,e);return Me.containsPoint(r,n)}},we=new _I,Ln=Ze({name:"arrowHandle"},{kind:C.enum(_e).default(_e.Start),arrowEntity:C.ref()}),Mi=Ze({name:"arrowTerminal"},{blockEntity:C.ref(),terminalIndex:C.uint8().default(0)}),II={points:C.buffer(C.float64()).size(ed*2),pointCount:C.uint8().default(0),thickness:C.float32().default(Qu),startArrowHead:C.enum(Te).default(Te.None),endArrowHead:C.enum(Te).default(Te.V),trimStart:C.float64().default(0),trimEnd:C.float64().default(1)},BI=class extends Kt{constructor(){super({name:"elbowArrow",sync:"document"},II)}snapshot(t,e){const n=super.snapshot(t,e);return n.points=n.points.slice(0,n.pointCount*2),n}getPoint(t,e,n){const{points:r}=this.read(t,e);return[r[n*2],r[n*2+1]]}setPoint(t,e,n,r){const{points:o}=this.write(t,e);o[n*2]=r[0],o[n*2+1]=r[1]}getPoints(t,e){const{points:n,pointCount:r}=this.read(t,e),o=[];for(let s=0;s<r;s++)o.push([n[s*2],n[s*2+1]]);return o}setPoints(t,e,n){if(n.length>ed)throw new Error(`ElbowArrow points exceed capacity of ${ed}`);const r=this.write(t,e);for(let o=0;o<n.length;o++)r.points[o*2]=n[o][0],r.points[o*2+1]=n[o][1];r.pointCount=n.length}getStartWorld(t,e){const n=this.getPoint(t,e,0);return A.uvToWorld(t,e,n)}getEndWorld(t,e){const{pointCount:n}=this.read(t,e),r=this.getPoint(t,e,n-1);return A.uvToWorld(t,e,r)}getWorldPoints(t,e){return this.getPoints(t,e).map(r=>A.uvToWorld(t,e,r))}getThickness(t,e){const{thickness:n}=this.read(t,e);return n}},Ce=new BI,Yg={};Ug(Yg,{ArrowDrawState:()=>nd,ArrowTransformState:()=>qg});var nd=to("arrowDrawState",{state:C.string().max(16).default($n.Idle),activeArrow:C.ref(),kind:C.enum(Do).default(Do.Elbow),pointingStartClient:C.tuple(C.int32(),2).default([0,0]),pointingStartWorld:C.tuple(C.float64(),2).default([0,0])}),qg=to("arrowTransformState",{state:C.string().max(16).default(Rs.None),activeArrow:C.ref()}),Xg=le("arrows-add-arrow"),Gg=le("arrows-remove-arrow"),Jg=le("arrows-add-or-update-transform-handles"),Qg=le("arrows-remove-transform-handles"),ey=le("arrows-hide-transform-handles"),ty=le("arrows-show-transform-handles"),NI=br({guards:{isThresholdReached:({context:t,event:e})=>L.distance(t.pointingStartClient,e.screenPosition)>=MI},actions:{setPointingStart:Re({pointingStartClient:({event:t})=>[t.screenPosition[0],t.screenPosition[1]],pointingStartWorld:({event:t})=>[t.worldPosition[0],t.worldPosition[1]]}),resetContext:Re({pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],activeArrow:()=>null}),addArrow:Re({activeArrow:({context:t,event:e})=>{const n=t.kind,r=t.pointingStartWorld,o=bt(e.ctx);return Xg.spawn(e.ctx,{entityId:o,position:r,kind:n}),o}}),removeArrow:Re({activeArrow:({context:t,event:e})=>(t.activeArrow&&Gg.spawn(e.ctx,{entityId:t.activeArrow}),null)}),exitArrowControl:({event:t})=>{const e=et.write(t.ctx);e.leftMouseTool="select";const n=vn.write(t.ctx);n.cursorKind="select"},deselectAll:({event:t})=>{Ps.spawn(t.ctx)}}}).createMachine({id:"arrowDraw",initial:$n.Idle,context:{activeArrow:null,kind:Do.Elbow,pointingStartClient:[0,0],pointingStartWorld:[0,0]},states:{[$n.Idle]:{entry:"resetContext",on:{pointerDown:[{actions:"deselectAll",target:$n.Pointing}]}},[$n.Pointing]:{entry:"setPointingStart",on:{pointerMove:{guard:"isThresholdReached",target:$n.Dragging},pointerUp:{target:$n.Idle},cancel:{target:$n.Idle}}},[$n.Dragging]:{entry:"addArrow",exit:"exitArrowControl",on:{pointerUp:{target:$n.Idle},cancel:{actions:"removeArrow",target:$n.Idle}}}}}),PI=ge({phase:"capture",priority:100},t=>{const e=et.getButtons(t,"arc-arrow","elbow-arrow");if(e.length===0)return;const n=xr(t,e);if(n.length===0)return;const r=et.read(t).leftMouseTool,o=nd.write(t);o.kind=r==="elbow-arrow"?Do.Elbow:Do.Arc,nd.run(t,NI,n)}),rd=re(t=>t.with(A).tracking(pt)),DI=br({guards:{selectingSingleArrow:({event:t})=>{if(!("selectedEntities"in t)||t.selectedEntities.length!==1)return!1;const e=t.selectedEntities[0];return O(t.ctx,e,we)||O(t.ctx,e,Ce)}},actions:{setActiveArrow:Re({activeArrow:({event:t})=>!("selectedEntities"in t)||t.selectedEntities.length===0?null:t.selectedEntities[0]}),addOrUpdateTransformHandles:({context:t,event:e})=>{t.activeArrow&&Jg.spawn(e.ctx,{arrowEntityId:t.activeArrow})},removeTransformHandles:({event:t})=>{Qg.spawn(t.ctx,{})},hideTransformHandles:({event:t})=>{ey.spawn(t.ctx,{})},showTransformHandles:({event:t})=>{ty.spawn(t.ctx,{})}}}).createMachine({id:"arrowTransform",initial:Rs.None,context:{activeArrow:null},states:{[Rs.None]:{entry:"removeTransformHandles",on:{selectionChanged:[{guard:"selectingSingleArrow",actions:"setActiveArrow",target:Rs.Idle}]}},[Rs.Idle]:{entry:"addOrUpdateTransformHandles",on:{selectionChanged:[{guard:Mo("selectingSingleArrow"),target:Rs.None},{actions:["setActiveArrow","addOrUpdateTransformHandles"]}],pointerDown:{actions:"hideTransformHandles"},pointerUp:{actions:"showTransformHandles"}}}}}),OI=ge({phase:"capture",priority:99},t=>{const e=RI(t);e.length!==0&&qg.run(t,DI,e)});function RI(t){const e=[],n=rd.added(t),r=rd.removed(t);if(n.length>0||r.length>0){const i=[...rd.current(t)];e.push({type:"selectionChanged",ctx:t,selectedEntities:i})}const o=et.getButtons(t,"select"),s=xr(t,o);return e.push(...s),e}var zI=class{constructor(){this.heap=[],this.positions=new Map}parent(t){return Math.floor((t-1)/2)}leftChild(t){return 2*t+1}rightChild(t){return 2*t+2}swap(t,e){this.positions.set(this.heap[t].id,e),this.positions.set(this.heap[e].id,t),[this.heap[t],this.heap[e]]=[this.heap[e],this.heap[t]]}bubbleUp(t){for(;t>0&&this.heap[this.parent(t)].distance>this.heap[t].distance;)this.swap(t,this.parent(t)),t=this.parent(t)}bubbleDown(t){let e=t;const n=this.leftChild(t);n<this.heap.length&&this.heap[n].distance<this.heap[e].distance&&(e=n);const r=this.rightChild(t);r<this.heap.length&&this.heap[r].distance<this.heap[e].distance&&(e=r),t!==e&&(this.swap(t,e),this.bubbleDown(e))}insert(t,e){this.heap.push({id:t,distance:e});const n=this.heap.length-1;this.positions.set(t,n),this.bubbleUp(n)}extractMin(){if(this.heap.length===0)return null;const t=this.heap[0],e=this.heap.pop();return this.positions.delete(t.id),this.heap.length>0&&(this.heap[0]=e,this.positions.set(e.id,0),this.bubbleDown(0)),t}decreaseKey(t,e){const n=this.positions.get(t);n!==void 0&&(this.heap[n].distance=e,this.bubbleUp(n))}isEmpty(){return this.heap.length===0}contains(t){return this.positions.has(t)}};function $I(t,e,n,r,o,s,i){return new LI(t,e,n,s,i).calculate(r,o)}var LI=class{constructor(t,e,n,r,o){this.ctx=t,this.padding=r,this.rotation=o;const s=L.midPoint(e,n);this.toLocal=Ae.fromTranslation(-s[0],-s[1]),Ae.rotate(this.toLocal,-o),this.toWorld=Ae.fromRotation(o),Ae.translate(this.toWorld,s[0],s[1]),this.localStart=this.transformToLocal(e),this.localEnd=this.transformToLocal(n)}transformToLocal(t){const e=L.clone(t);return Ae.transformPoint(this.toLocal,e),e}transformToWorld(t){const e=L.clone(t);return Ae.transformPoint(this.toWorld,e),e}calculate(t,e){const n=this.calculateRay(this.localStart,this.localEnd,t),r=this.calculateRay(this.localEnd,this.localStart,e);let o;if(t&&e){const s=this.isPointInsideBlockMargin(this.localStart,e),i=this.isPointInsideBlockMargin(this.localEnd,t);s||i?o=Ai(ut.origin(n),ut.origin(r)):o=this.routeBlockToBlock(t,e,n,r)}else t&&!e?this.isPointInsideBlockMargin(this.localEnd,t)?o=Ai(ut.origin(n),this.localEnd):o=this.routeBlockToPoint(t,n,this.localEnd):!t&&e?this.isPointInsideBlockMargin(this.localStart,e)?o=Ai(this.localStart,ut.origin(r)):o=this.routeBlockToPoint(e,r,this.localStart).reverse():o=Ai(ut.origin(n),this.localEnd);for(let s=0;s<o.length;s++)o[s]=this.transformToWorld(o[s]);return o}getBlockAabb(t){const e=A.read(this.ctx,t),n=[e.position[0]+e.size[0]/2,e.position[1]+e.size[1]/2],r=this.transformToLocal(n),o=(e.rotateZ||0)-this.rotation,s=[r[0]-e.size[0]/2,r[1]-e.size[1]/2],i=[0,0,0,0];return st.getAabb(s,e.size,o,i),i}isPointInsideBlockMargin(t,e){const n=this.getBlockAabb(e);return ee.pad(n,this.padding),ee.containsPoint(n,t)}routeBlockToBlock(t,e,n,r){const o=this.getBlockAabb(t),s=this.getBlockAabb(e);ee.pad(o,this.padding),ee.pad(s,this.padding),UI(o,s);const i=HI(o,s),a=hl(n,i),l=hl(r,i),c=ut.origin(n),u=ut.origin(r);if(a===null||l===null)return console.warn("[routeBlockToBlock] Failed to add start or end node to graph"),[c,u];const f=sy(i,a,l);if(f===null)return[c,u];const h=[c];for(const p of f){const m=i.find(g=>g.id===p);m&&h.push(m.coords)}return h.push(u),VI(h),ny(h),FI(h),h}routeBlockToPoint(t,e,n){const r=ut.origin(e),o=ut.direction(e),s=pl(r,n);if(o[0]===s[0]&&o[1]===s[1])return Ai(r,n);const i=this.getBlockAabb(t);ee.pad(i,this.padding);const a=ut.fromPoints(n,[-s[0],-s[1]]),l=ut.intersectAabb(a,i);l.length===0&&ee.expand(i,n);const c=ee.corners(i),u=ry(c),f=hl(a,u),h=hl(e,u);if(h===null||f===null)return[r,n];const p=sy(u,h,f);if(p===null)return[r,n];const m=[r];for(const g of p){const y=u.find(w=>w.id===g);y&&m.push(y.coords)}return l.length>0&&m.push(n),ny(m),m}calculateRay(t,e,n){let r;return n?r=this.exitClosestSide(t,n).direction:r=pl(t,e),ut.fromPoints(t,r)}exitClosestSide(t,e){const n=A.read(this.ctx,e),r=A.getCenter(this.ctx,e),o=this.transformToWorld(t),s=L.clone(o),i=L.clone(r);L.sub(i,o),L.scale(i,.01),L.add(s,i);const a=[[0,-1],[1,0],[0,1],[-1,0]],l=a.map(m=>{const g=L.clone(m);return L.rotate(g,this.rotation),g}),c=[];for(let m=0;m<l.length;m++){const g=l[m],y=ut.fromPoints(s,g),w=ut.intersectRect(y,n.position,n.size,n.rotateZ);w.length!==0&&c.push({direction:a[m],distance:w[0].distance})}if(c.length===0)return console.error("[exitClosestSide] No valid exit direction found!",{point:t,nudgedPoint:s,blockPosition:n.position,blockSize:n.size,blockRotateZ:n.rotateZ,center:r}),{direction:[0,-1],distance:0};c.sort((m,g)=>m.distance-g.distance);const u=c[0],f=(o[0]-n.position[0])/n.size[0],h=(o[1]-n.position[1])/n.size[1],p=.2;if(Math.abs(f-.5)<p&&Math.abs(h-.5)<p){const m=pl(t,this.localEnd),g=c.find(y=>y.direction[0]===m[0]&&y.direction[1]===m[1]);if(g)return g}return u}};function Ai(t,e){const n=[];n.push(t);const r=e[0]-t[0],o=e[1]-t[1];if(xt.approxEqual(o,0)||xt.approxEqual(r,0))return n.push(e),n;const s=pl(t,e);let i;s[0]===1?i=r:s[0]===-1?i=-r:s[1]===1?i=o:i=-o;const a=[t[0]+s[0]*i/2,t[1]+s[1]*i/2];return n.push(a),s[0]===0?n.push([e[0],a[1]]):n.push([a[0],e[1]]),n.push(e),n}function VI(t){if(t.length<2)return;const e=[t[0]];for(let n=1;n<t.length;n++){const r=e[e.length-1],o=t[n],s=xt.approxEqual(r[0],o[0]),i=xt.approxEqual(r[1],o[1]);(!s||!i)&&e.push(o)}t.length=0,t.push(...e)}function ny(t){if(t.length<3)return;const e=[];for(let n=1;n<t.length-1;n++){const r=t[n-1],o=t[n],s=t[n+1],i=xt.approxEqual(r[0],o[0])&&xt.approxEqual(o[0],s[0]),a=xt.approxEqual(r[1],o[1])&&xt.approxEqual(o[1],s[1]);(i||a)&&e.push(n)}for(let n=e.length-1;n>=0;n--)t.splice(e[n],1)}function FI(t){if(t.length<3)return;const e=[];for(let r=1;r<t.length-1;r++){const o=t[r-1],s=t[r],i=t[r+1],a=WI(o,s,i);e.push(a)}const n=[];for(let r=1;r<e.length-1;r++){const o=e[r-1],s=e[r],i=e[r+1];if(o==="left"&&s==="right"&&i==="left"||o==="right"&&s==="left"&&i==="right"){const l=Math.abs(t[r+1][0]-t[r][0])<1e-6,c=Math.abs(t[r+1][1]-t[r][1])<1e-6;if(l)t[r+1][0]=t[r+2][0],t[r+1][1]=t[r][1];else if(c)t[r+1][0]=t[r][0],t[r+1][1]=t[r+2][1];else continue;n.push(r),n.push(r+2)}}for(let r=n.length-1;r>=0;r--)t.splice(n[r],1)}function WI(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])>0?"left":"right"}function UI(t,e){if(!ee.intersects(t,e)){if(t[2]<e[0]){const n=(t[2]+e[0])/2;t[2]=n,e[0]=n}else if(e[2]<t[0]){const n=(e[2]+t[0])/2;e[2]=n,t[0]=n}if(t[3]<e[1]){const n=(t[3]+e[1])/2;t[3]=n,e[1]=n}else if(e[3]<t[1]){const n=(e[3]+t[1])/2;e[3]=n,t[1]=n}}}function ry(t){const e=t.map((n,r)=>({id:r,connections:[],distances:{},coords:n}));return oy(e,0),oy(e,1),e}function oy(t,e){const n={},r=1-e;for(const o of t){const s=Math.round(o.coords[e]);n[s]||(n[s]=[]),n[s].push(o)}for(const o of Object.values(n)){o.sort((s,i)=>s.coords[r]-i.coords[r]);for(let s=0;s<o.length-1;s++){const i=o[s],a=o[s+1];i.connections.push(a.id),a.connections.push(i.id);const l=Math.abs(a.coords[r]-i.coords[r]);i.distances[a.id]=l,a.distances[i.id]=l}}}function HI(t,e){if(!ee.intersects(t,e))return[];const n=[],r=ee.corners(t),o=ee.corners(e);for(const c of r)ee.containsPoint(e,c,!1)||n.push(c);for(const c of o)ee.containsPoint(t,c,!1)||n.push(c);const s=ee.clone(t);ee.intersection(s,e);const i=ee.corners(s);for(const c of i)ee.containsPoint(t,c,!1)||ee.containsPoint(e,c,!1)||n.push(c);const a=[],l=new Set;for(const c of n){const u=c.map(Math.round).join(",");l.has(u)||(a.push(c),l.add(u))}return ry(a)}function hl(t,e){const n=ut.origin(t),r=e.find(p=>p.coords[0]===n[0]&&p.coords[1]===n[1]);if(r)return r.id;let o=null,s=-1,i=-1;for(const p of e)for(const m of p.connections){if(p.id>=m)continue;const g=e.find(w=>w.id===m);if(!g)continue;const y=ut.intersectSegment(t,p.coords,g.coords);y&&(o===null||y.distance<o.distance)&&(o=y,s=p.id,i=m)}if(!o||s===-1||i===-1)return console.warn("[intersectRayAndAddNode] No intersection found for ray",t,o,s,i),null;const a=e.length,l={id:a,connections:[],distances:{},coords:o.point},c=e[s],u=e[i],f=Math.hypot(o.point[0]-c.coords[0],o.point[1]-c.coords[1]),h=Math.hypot(o.point[0]-u.coords[0],o.point[1]-u.coords[1]);return l.connections.push(s,i),l.distances[s]=f,l.distances[i]=h,c.connections.push(a),c.distances[a]=f,u.connections.push(a),u.distances[a]=h,c.connections=c.connections.filter(p=>p!==i),delete c.distances[i],u.connections=u.connections.filter(p=>p!==s),delete u.distances[s],e.push(l),a}function sy(t,e,n){const r={},o={},s=new zI;for(const i of t)r[i.id]=Number.POSITIVE_INFINITY,o[i.id]=null;for(r[e]=0,s.insert(e,0);!s.isEmpty();){const i=s.extractMin();if(!i)break;const a=i.id;if(a===n){const c=[];let u=n;for(;u!==null;)c.unshift(u),u=o[u];return c}const l=t.find(c=>c.id===a);if(l)for(const c of l.connections){const u=r[a]+(l.distances[c]||1);u<r[c]&&(r[c]=u,o[c]=a,s.contains(c)?s.decreaseKey(c,u):s.insert(c,u))}}return null}function pl(t,e){const n=e[0]-t[0],r=e[1]-t[1];return Math.abs(n)>Math.abs(r)?[Math.sign(n),0]:[0,Math.sign(r)]}function iy(t,e){if(t.length===0)return null;let n=t[0],r=L.distanceSq(t[0],e);for(let o=1;o<t.length;o++){const s=L.distanceSq(t[o],e);s<r&&(r=s,n=t[o])}return n}function jI(t,e,n){const r=[t[0]-n[0],t[1]-n[1]],o=[e[0]-n[0],e[1]-n[1]],s=Math.atan2(r[1],r[0]);let a=Math.atan2(o[1],o[0])-s;a>Math.PI&&(a-=2*Math.PI),a<-Math.PI&&(a+=2*Math.PI);const l=Math.hypot(r[0],r[1]),u=Math.hypot(o[0],o[1])-l;return{angle:a,distance:u}}function ZI(t,e,n,r){const o=Math.atan2(t[1]-r[1],t[0]-r[0])+e,s=Math.hypot(t[0]-r[0],t[1]-r[1])+n;return[r[0]+Math.cos(o)*s,r[1]+Math.sin(o)*s]}var ay=20,KI=re(t=>t.tracking(we,ze)),YI=re(t=>t.tracking(Ce,ze)),qI=ge({phase:"update",priority:-10},t=>{for(const e of KI.addedOrChanged(t))XI(t,e);for(const e of YI.addedOrChanged(t))GI(t,e)});function XI(t,e){O(t,e,ke)||J(t,e,ke,{});const n=we.read(t,e),r=Me.clone(n.value);r[6]=Math.max(r[6],ay),ke.clear(t,e),ke.addArc(t,e,r),JI(t,e)}function GI(t,e){O(t,e,ke)||J(t,e,ke,{});const n=Ce.read(t,e),r=Math.max(n.thickness,ay),o=Ce.getPoints(t,e),s=ke.write(t,e),i=Math.min(o.length-1,Ms);s.capsuleCount=i,s.arcCount=0;for(let a=0;a<i;a++){const l=o[a],c=o[a+1],u=ot.create(l[0],l[1],c[0],c[1],r/2);ke.setCapsuleAt(t,e,a,u)}QI(t,e)}function JI(t,e){const n=ze.read(t,e),r=we.getWorldArc(t,e),{a:o,c:s}=we.getWorldPoints(t,e);let i=ly(t,n.startBlock,r,o),a=ly(t,n.endBlock,r,s);1-a-i<.1&&(i=0,a=0);const l=we.read(t,e);if(!xt.approxEqual(l.trimStart,i)||!xt.approxEqual(l.trimEnd,a)){const u=we.write(t,e);u.trimStart=i,u.trimEnd=a}const c=ke.read(t,e);for(let u=0;u<c.arcCount;u++){const f=ke.getArcAt(t,e,u);Me.trim(f,i,1-a),ke.setArcAt(t,e,u,f)}}function ly(t,e,n,r){if(!e)return 0;const o=A.getCorners(t,e),s=Me.intersectRect(n,o);if(s.length===0)return 0;const i=iy(s,r);return i?Me.pointToParametric(n,i)??0:0}function QI(t,e){const n=ze.read(t,e),r=Ce.getWorldPoints(t,e),o=r.length-1;if(o<1)return;const s=r[0],i=r[r.length-1],a=r[1],l=r[r.length-2],c=cy(t,n.startBlock,s,a),u=cy(t,n.endBlock,i,l),f=Ce.read(t,e);if(!xt.approxEqual(f.trimStart,c)||!xt.approxEqual(f.trimEnd,u)){const g=Ce.write(t,e);g.trimStart=c,g.trimEnd=u}const h=ke.getCapsuleAt(t,e,0);ot.trim(h,c,1),ke.setCapsuleAt(t,e,0,h);const p=o-1,m=ke.getCapsuleAt(t,e,p);ot.trim(m,0,1-u),ke.setCapsuleAt(t,e,p,m)}function cy(t,e,n,r){if(!e)return 0;const o=A.getCorners(t,e),s=[];for(let f=0;f<4;f++){const h=o[f],p=o[(f+1)%4],m=eB(n,r,h,p);m&&s.push(m)}if(s.length===0)return 0;const i=iy(s,n);if(!i)return 0;const a=r[0]-n[0],l=r[1]-n[1],c=Math.hypot(a,l);if(c<.001)return 0;const u=((i[0]-n[0])*a+(i[1]-n[1])*l)/(c*c);return Math.max(0,Math.min(1,u))}function eB(t,e,n,r){const o=e[0]-t[0],s=e[1]-t[1],i=r[0]-n[0],a=r[1]-n[1],l=o*a-s*i;if(Math.abs(l)<1e-10)return null;const c=n[0]-t[0],u=n[1]-t[1],f=(c*a-u*i)/l,h=(c*s-u*o)/l;return f>=0&&f<=1&&h>=0&&h<=1?[t[0]+f*o,t[1]+f*s]:null}var ml=re(t=>t.with(Ln,A)),tB=re(t=>t.with(de,Be).tracking(A)),uy=re(t=>t.with(Mi,A)),nB=ge({phase:"update"},t=>{ae(t,Xg,(e,{entityId:n,position:r,kind:o})=>{oB(e,n,r,o)}),ae(t,Gg,(e,{entityId:n})=>{sB(e,n)}),ae(t,Jg,(e,{arrowEntityId:n})=>{od(e,n)}),ae(t,Qg,e=>{uB(e)}),ae(t,ey,e=>{sd(e)}),ae(t,ty,e=>{dB(e)}),ae(t,Ei,(e,{entityId:n,position:r})=>{iB(e,n,r)}),rB(t)});function rB(t){const e=tB.addedOrChangedOrRemoved(t);if(e.length===0)return;const n=new Set;for(const r of e){const o=Jn(t,r,ze,"startBlock",!1);for(const i of o)n.has(i)||(n.add(i),dy(t,i));const s=Jn(t,r,ze,"endBlock",!1);for(const i of s)n.has(i)||(n.add(i),dy(t,i))}}function dy(t,e){const n=ze.read(t,e);if(O(t,e,we)){const{a:r,c:o}=we.getWorldPoints(t,e);let s=r,i=o;n.startBlock!==null&&(s=A.uvToWorld(t,n.startBlock,n.startBlockUv),id(t,e,_e.Start,s)),n.endBlock!==null&&(i=A.uvToWorld(t,n.endBlock,n.endBlockUv),id(t,e,_e.End,i))}else if(O(t,e,Ce)){if(n.startBlock!==null){const r=A.uvToWorld(t,n.startBlock,n.startBlockUv);ad(t,e,_e.Start,r)}if(n.endBlock!==null){const r=A.uvToWorld(t,n.endBlock,n.endBlockUv);ad(t,e,_e.End,r)}}}function oB(t,e,n,r){const o=Qu,s=r===Do.Elbow?"elbow-arrow":"arc-arrow",a=eo.getAll(t).find(h=>O(t,h,de)&&ld(t,h))??null;let l=n,c=[0,0];if(a!==null){const h=cd(t,a,n);h!==null?(l=h.position,c=h.uv):(l=A.uvToWorld(t,a,[.5,.5]),c=[.5,.5])}J(t,e,A,{tag:s,rank:Dn.genNext(t),position:l,size:[o,o]}),J(t,e,de,{id:crypto.randomUUID()}),r===Do.Arc?J(t,e,we,{value:[0,0,.5,.5,1,1,o],startArrowHead:Te.None,endArrowHead:Te.V}):J(t,e,Ce,{points:[0,0,.5,0,.5,1,1,1],pointCount:4,thickness:o,startArrowHead:Te.None,endArrowHead:Te.V}),J(t,e,ze,{startBlock:a,startBlockUv:c}),Ds(t,e);const f=od(t,e).find(h=>Ln.read(t,h).kind===_e.End);if(f){const h=A.read(t,f),p=zn.write(t);p.state=ye.Dragging,p.draggedEntity=f,p.dragStart=l,p.draggedEntityStart=[h.position[0],h.position[1]],sd(t)}}function sB(t,e){qe(t,e)}function iB(t,e,n){O(t,e,we)?aB(t,e):O(t,e,Ce)?lB(t,e):O(t,e,Ln)&&cB(t,e,n)}function aB(t,e){const n=ze.read(t,e);if(n.startBlock!==null){const{a:r}=we.getWorldPoints(t,e);_i(t,e,_e.Start,r)}if(n.endBlock!==null){const{c:r}=we.getWorldPoints(t,e);_i(t,e,_e.End,r)}}function lB(t,e){const n=ze.read(t,e);if(n.startBlock!==null){const r=Ce.getStartWorld(t,e);_i(t,e,_e.Start,r)}if(n.endBlock!==null){const r=Ce.getEndWorld(t,e);_i(t,e,_e.End,r)}}function cB(t,e,n){const r=Ln.read(t,e),o=r.arrowEntity;if(!o)return;const s=A.read(t,e);let i=[n[0]+s.size[0]/2,n[1]+s.size[1]/2];if(r.kind!==_e.Middle){const a=gB(t,o,r.kind,i);a!==null&&(i=a)}O(t,o,we)?id(t,o,r.kind,i):O(t,o,Ce)&&ad(t,o,r.kind,i),r.kind!==_e.Middle&&_i(t,o,r.kind,i)}function od(t,e){const n=TI,r=[_e.Start,_e.End];O(t,e,we)&&r.push(_e.Middle);const o=Array.from(ml.current(t)),s=new Map;for(const l of o){const c=Ln.read(t,l);s.set(c.kind,l)}const i=new Set;for(const l of r){const c=fB(t,e,l),u=c[0]-n/2,f=c[1]-n/2;let h=s.get(l);h||(h=bt(t),J(t,h,Ln),J(t,h,A),J(t,h,Qr),J(t,h,$e,{kind:"arrow"}));const p=Ln.write(t,h);p.kind=l,p.arrowEntity=e;const m=A.write(t,h);m.tag="arrow-handle",m.rank=jg,m.position=[u,f],m.size=[n,n];const g=Qr.write(t,h);g.startPosition=[u,f],g.startSize=[n,n],i.add(h)}for(const l of o)i.has(l)||qe(t,l);const a=zn.read(t);return a.state===ye.Dragging&&a.draggedEntity!==null&&O(t,a.draggedEntity,Ln)&&sd(t),Array.from(i)}function uB(t){for(const e of ml.current(t))qe(t,e);gl(t)}function sd(t){for(const e of ml.current(t))if(!O(t,e,Qe))J(t,e,Qe,{value:0});else{const n=Qe.write(t,e);n.value=0}}function dB(t){const e=ml.current(t);for(const n of e)O(t,n,Qe)&&nn(t,n,Qe);if(e.length>0){const n=Ln.read(t,e[0]);n.arrowEntity&&od(t,n.arrowEntity)}gl(t)}function fB(t,e,n){if(O(t,e,we)){const{a:r,b:o,c:s}=we.getWorldPoints(t,e);switch(n){case _e.Start:return r;case _e.Middle:return o;case _e.End:return s}}if(O(t,e,Ce))switch(n){case _e.Start:return Ce.getStartWorld(t,e);case _e.End:return Ce.getEndWorld(t,e)}return console.warn("Arrow entity has no recognized arrow component"),[0,0]}function id(t,e,n,r){const{a:o,b:s,c:i}=we.getWorldPoints(t,e);let a=o,l=s,c=i,u=[0,0],f=[0,0];if(n===_e.Start?(u=o,f=i,a=r):n===_e.Middle?l=r:(u=i,f=o,c=r),n!==_e.Middle){const{angle:w,distance:k}=jI(u,r,f);l=ZI(s,w,.5*k,f)}const h=A.write(t,e),p=Math.min(a[0],l[0],c[0]),m=Math.min(a[1],l[1],c[1]),g=Math.max(a[0],l[0],c[0]),y=Math.max(a[1],l[1],c[1]);h.position=[p,m],h.size=[g-p||1,y-m||1],we.setA(t,e,A.worldToUv(t,e,a)),we.setB(t,e,A.worldToUv(t,e,l)),we.setC(t,e,A.worldToUv(t,e,c))}function ad(t,e,n,r){const o=ze.read(t,e);let s,i;n===_e.Start?(s=r,o.endBlock!==null?i=A.uvToWorld(t,o.endBlock,o.endBlockUv):i=Ce.getEndWorld(t,e)):(o.startBlock!==null?s=A.uvToWorld(t,o.startBlock,o.startBlockUv):s=Ce.getStartWorld(t,e),i=r);const l=A.read(t,e).rotateZ||0,c=$I(t,s,i,o.startBlock,o.endBlock,Zg,l),u=A.write(t,e),f=[0,0],h=[1,1];st.boundPoints(f,h,l,c),u.position=f,u.size=[Math.max(h[0],1),Math.max(h[1],1)];const p=c.map(m=>A.worldToUv(t,e,m));Ce.setPoints(t,e,p)}function _i(t,e,n,r){let s=eo.getAll(t).find(l=>l!==e&&O(t,l,de)&&!O(t,l,ze)&&ld(t,l))??null;const i=ze.write(t,e);if(s!==null){const l=n===_e.Start?i.endBlock:i.startBlock;s===l&&(s=null)}s!==null?mB(t,s):gl(t);let a=[0,0];if(s!==null){const l=cd(t,s,r,Kg);l!==null?a=l.uv:a=A.worldToUv(t,s,r)}n===_e.Start?(i.startBlock=s,i.startBlockUv=a):(i.endBlock=s,i.endBlockUv=a),hB(t,e)}function hB(t,e){const n=ze.read(t,e);let r=null;for(const s of[n.startBlock,n.endBlock]){if(s===null)continue;const i=A.read(t,s).rank;(r===null||i>r)&&(r=i)}const o=A.read(t,e).rank;if(r!==null&&o<r){const s=A.write(t,e);s.rank=Oa(r,null)}}function ld(t,e){const n=A.read(t,e).tag;return Vt(t,n).connectors.enabled}function pB(t){const e=uy.current(t);return e.length===0?null:Mi.read(t,e[0]).blockEntity}function mB(t,e){if(pB(t)===e)return;gl(t);const n=A.read(t,e).tag,r=Vt(t,n);if(!r.connectors.enabled)return;const o=r.connectors.terminals;for(let s=0;s<o.length;s++){const i=o[s],a=A.uvToWorld(t,e,i),l=bt(t);J(t,l,Mi,{blockEntity:e,terminalIndex:s}),J(t,l,A,{tag:"arrow-terminal",rank:jg,position:[a[0]-no/2,a[1]-no/2],size:[no,no]}),J(t,l,Qr,{startPosition:[a[0]-no/2,a[1]-no/2],startSize:[no,no]})}}function gl(t){for(const e of uy.current(t))qe(t,e)}function cd(t,e,n,r){const o=A.read(t,e).tag,s=Vt(t,o);if(!s.connectors.enabled)return null;const i=s.connectors.terminals;if(i.length===0)return null;let a=null,l=r??1/0;for(const c of i){const u=A.uvToWorld(t,e,c),f=u[0]-n[0],h=u[1]-n[1],p=Math.sqrt(f*f+h*h);p<l&&(l=p,a={position:u,uv:c})}return a}function gB(t,e,n,r){const s=eo.getAll(t).find(c=>c!==e&&O(t,c,de)&&!O(t,c,ze)&&ld(t,c))??null;if(s===null)return null;const i=ze.read(t,e),a=n===_e.Start?i.endBlock:i.startBlock;if(s===a)return null;const l=cd(t,s,r,Kg);return l===null?null:l.position}function yB(t={}){return{name:xI,components:Object.values(Hg).filter(e=>e instanceof Kt),singletons:Object.values(Yg).filter(e=>e instanceof St),blockDefs:[{tag:"arc-arrow",resizeMode:"groupOnly",components:[we,ze,yn],connectors:{enabled:!1}},{tag:"elbow-arrow",resizeMode:"groupOnly",components:[Ce,ze,yn],connectors:{enabled:!1}},{tag:"arrow-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ln],connectors:{enabled:!1}},{tag:"arrow-terminal",stratum:"overlay",canRotate:!1,canScale:!1,components:[Mi],connectors:{enabled:!1}}],systems:[PI,OI,nB,qI],resources:{elbowArrowPadding:t.elbowArrowPadding??Zg}}}const ud=[{kind:Te.None,label:"None",gap:0,svg:""},{kind:Te.V,label:"Arrow",gap:15,svg:'<polyline points="-10,-7 -1,0 -10,7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />'},{kind:Te.Delta,label:"Triangle",gap:20,svg:'<polygon points="-1,0 -12,-7 -12,7" fill="currentColor" />'},{kind:Te.Circle,label:"Circle",gap:0,svg:'<circle cx="-6" cy="0" r="6" fill="currentColor" />'},{kind:Te.Diamond,label:"Diamond",gap:0,svg:'<polygon points="0,0 -7,-6 -14,0 -7,6" fill="currentColor" />'}];function zs(t){return ud.find(e=>e.kind===t)}const fy=Symbol("dropdownActive"),hy=Symbol("dropdownLevel"),py=Symbol("floating-menu"),dd=Symbol("toolbar"),my=Symbol("WovenCanvasTooltip"),En=Symbol("woven-canvas");function mt(t,e){const n=d.inject(En);if(!n)throw new Error("useComponent must be used within a WovenCanvas component");const r=d.shallowRef(null),o=n.getEditor();if(o){const i=o._getContext();O(i,t,e)&&(r.value=e.snapshot(i,t))}const s=n.subscribeComponent(t,e.name,i=>{r.value=i});return d.onUnmounted(()=>{s()}),r}const wB={key:0},kB=["x1","y1","x2","y2","stroke","stroke-width"],vB=["x1","y1","x2","y2","stroke","stroke-width"],bB=["points","fill"],SB=["cx","cy","r","fill"],EB=["points","fill"],CB=15,xB=2,Tr=d.defineComponent({__name:"ArrowHead",props:{position:{},direction:{},thickness:{},color:{},arrowThickness:{},kind:{}},setup(t){const e=t,n=d.computed(()=>{const a=Math.hypot(e.direction[0],e.direction[1]);if(a===0)return null;const l=(e.arrowThickness/xB)**.33,c=CB*l,u=[e.direction[0]/a,e.direction[1]/a],f=[-u[1],u[0]];return{unitDir:u,perpDir:f,size:c}}),r=d.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=c,f=c,h=[e.position[0]-a[0]*u+l[0]*(f/2),e.position[1]-a[1]*u+l[1]*(f/2)],p=[e.position[0]-a[0]*u-l[0]*(f/2),e.position[1]-a[1]*u-l[1]*(f/2)];return{p1:h,p2:p}}),o=d.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=c,f=c,h=[a[0]*(c*.4),a[1]*(c*.4)],p=[e.position[0]-a[0]*u+h[0],e.position[1]-a[1]*u+h[1]],m=[p[0]+l[0]*(f/2),p[1]+l[1]*(f/2)],g=[p[0]-l[0]*(f/2),p[1]-l[1]*(f/2)],y=[e.position[0]+h[0],e.position[1]+h[1]];return`${y[0]},${y[1]} ${m[0]},${m[1]} ${g[0]},${g[1]}`}),s=d.computed(()=>{if(!n.value)return null;const{unitDir:a,size:l}=n.value,c=l*.8,u=[a[0]*c,a[1]*c];return{center:[e.position[0]-a[0]*c+u[0],e.position[1]-a[1]*c+u[1]],radius:c}}),i=d.computed(()=>{if(!n.value)return null;const{unitDir:a,perpDir:l,size:c}=n.value,u=1.6*c,f=1.6*c,h=[a[0]*(c*.8),a[1]*(c*.8)],p=[e.position[0]-a[0]*(u/2)+h[0],e.position[1]-a[1]*(u/2)+h[1]],m=[e.position[0]-a[0]*u+h[0],e.position[1]-a[1]*u+h[1]],g=[p[0]+l[0]*(f/2),p[1]+l[1]*(f/2)],y=[p[0]-l[0]*(f/2),p[1]-l[1]*(f/2)],w=[e.position[0]+h[0],e.position[1]+h[1]];return`${w[0]},${w[1]} ${g[0]},${g[1]} ${m[0]},${m[1]} ${y[0]},${y[1]}`});return(a,l)=>n.value?(d.openBlock(),d.createElementBlock("g",wB,[t.kind===d.unref(Te).V&&r.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:0},[d.createElementVNode("line",{x1:r.value.p1[0],y1:r.value.p1[1],x2:t.position[0],y2:t.position[1],stroke:t.color,"stroke-width":t.thickness,"stroke-linecap":"round"},null,8,kB),d.createElementVNode("line",{x1:r.value.p2[0],y1:r.value.p2[1],x2:t.position[0],y2:t.position[1],stroke:t.color,"stroke-width":t.thickness,"stroke-linecap":"round"},null,8,vB)],64)):t.kind===d.unref(Te).Delta&&o.value?(d.openBlock(),d.createElementBlock("polygon",{key:1,points:o.value,fill:t.color},null,8,bB)):t.kind===d.unref(Te).Circle&&s.value?(d.openBlock(),d.createElementBlock("circle",{key:2,cx:s.value.center[0],cy:s.value.center[1],r:s.value.radius,fill:t.color},null,8,SB)):t.kind===d.unref(Te).Diamond&&i.value?(d.openBlock(),d.createElementBlock("polygon",{key:3,points:i.value,fill:t.color},null,8,EB)):d.createCommentVNode("",!0)])):d.createCommentVNode("",!0)}}),TB={class:"arrow-svg",preserveAspectRatio:"none"},MB=["d","stroke","stroke-width"],AB=["x1","y1","x2","y2","stroke","stroke-width"],_B=["d"],IB=["x1","y1","x2","y2"],BB=d.defineComponent({__name:"ArcArrow",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=d.ref(null),r=d.ref(0),o=d.ref(0),s=mt(e.entityId,yn),i=mt(e.entityId,we);let a=null;d.onMounted(()=>{n.value&&(a=new ResizeObserver(()=>{n.value&&(r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),a.observe(n.value),r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),d.onUnmounted(()=>{a==null||a.disconnect()});const l=d.computed(()=>{if(!s.value)return"#000000";const b=s.value.red.toString(16).padStart(2,"0"),S=s.value.green.toString(16).padStart(2,"0"),v=s.value.blue.toString(16).padStart(2,"0");return`#${b}${S}${v}`}),c=d.computed(()=>{var b;return((b=i.value)==null?void 0:b.value[6])??2}),u=d.computed(()=>`${c.value}px`),f=d.computed(()=>e.hovered||e.selected),h=d.computed(()=>{if(!i.value)return!1;const b=i.value.value,S=Me.create(b[0],b[1],b[2],b[3],b[4],b[5],b[6]);return!Me.isCollinear(S)}),p=d.computed(()=>{if(!i.value)return null;const b=i.value.value,S=r.value,v=o.value;return Me.create(b[0]*S,b[1]*v,b[2]*S,b[3]*v,b[4]*S,b[5]*v,b[6])}),m=d.computed(()=>!p.value||!h.value?null:Me.compute(p.value)),g=d.computed(()=>{var V,K,se,Y;if(!i.value||!p.value)return null;const b=p.value,S=i.value.startArrowHead,v=i.value.endArrowHead,E=Me.length(b);let T=i.value.trimStart;if((V=e.connector)!=null&&V.startBlock&&S!=="none"){const R=((K=zs(S))==null?void 0:K.gap)??0,W=E>0?R/E:0;T+=W}let _=i.value.trimEnd;if((se=e.connector)!=null&&se.endBlock&&v!=="none"){const R=((Y=zs(v))==null?void 0:Y.gap)??0,W=E>0?R/E:0;_+=W}const I=1-_,z=Me.parametricToPoint(b,T),F=Me.parametricToPoint(b,I),j=k(Me.directionAt(b,T)),M=Me.directionAt(b,I);return{start:z,end:F,startDir:j,endDir:M,tStart:T,tEnd:I,startHead:S,endHead:v}}),y=d.computed(()=>{if(!g.value||!m.value||!h.value)return"";const{start:b,end:S,tStart:v,tEnd:E}=g.value,{radius:T,clockwise:_,arcAngle:I}=m.value,F=I*(E-v)>Math.PI?1:0,j=_?0:1;return`M ${b[0]} ${b[1]} A ${T} ${T} 0 ${F} ${j} ${S[0]} ${S[1]}`}),w=d.computed(()=>!g.value||h.value?null:{x1:g.value.start[0],y1:g.value.start[1],x2:g.value.end[0],y2:g.value.end[1]});function k(b){return[-b[0],-b[1]]}return(b,S)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-arc-arrow"},[(d.openBlock(),d.createElementBlock("svg",TB,[h.value&&y.value?(d.openBlock(),d.createElementBlock("path",{key:0,d:y.value,stroke:l.value,fill:"none","stroke-width":u.value,"stroke-linecap":"round"},null,8,MB)):w.value?(d.openBlock(),d.createElementBlock("line",{key:1,x1:w.value.x1,y1:w.value.y1,x2:w.value.x2,y2:w.value.y2,stroke:l.value,fill:"none","stroke-width":u.value,"stroke-linecap":"round"},null,8,AB)):d.createCommentVNode("",!0),g.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:2},[g.value.startHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:0,position:g.value.start,direction:g.value.startDir,thickness:u.value,"arrow-thickness":c.value,color:l.value,kind:g.value.startHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):d.createCommentVNode("",!0),g.value.endHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:1,position:g.value.end,direction:g.value.endDir,thickness:u.value,"arrow-thickness":c.value,color:l.value,kind:g.value.endHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):d.createCommentVNode("",!0),f.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:2},[h.value&&y.value?(d.openBlock(),d.createElementBlock("path",{key:0,d:y.value,class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,_B)):w.value?(d.openBlock(),d.createElementBlock("line",{key:1,x1:w.value.x1,y1:w.value.y1,x2:w.value.x2,y2:w.value.y2,class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,IB)):d.createCommentVNode("",!0),g.value.startHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:2,position:g.value.start,direction:g.value.startDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":c.value,color:"var(--wov-highlighted-block-outline-color)",kind:g.value.startHead},null,8,["position","direction","arrow-thickness","kind"])):d.createCommentVNode("",!0),g.value.endHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:3,position:g.value.end,direction:g.value.endDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":c.value,color:"var(--wov-highlighted-block-outline-color)",kind:g.value.endHead},null,8,["position","direction","arrow-thickness","kind"])):d.createCommentVNode("",!0)],64)):d.createCommentVNode("",!0)],64)):d.createCommentVNode("",!0)]))],512))}}),Oo=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},gy=Oo(BB,[["__scopeId","data-v-bcf5b4f3"]]),NB={},PB={class:"wov-arrow-handle"};function DB(t,e){return d.openBlock(),d.createElementBlock("div",PB,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-handle-inner"},null,-1)])])}const yy=Oo(NB,[["render",DB]]),OB={},RB={class:"wov-arrow-terminal"};function zB(t,e){return d.openBlock(),d.createElementBlock("div",RB,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-terminal-ring"},[d.createElementVNode("div",{class:"wov-arrow-terminal-fill"})],-1)])])}const wy=Oo(OB,[["render",zB]]),$B={class:"arrow-svg",preserveAspectRatio:"none"},LB=["x1","y1","x2","y2"],VB=["x1","y1","x2","y2","stroke","stroke-width"],FB=["x1","y1","x2","y2"],ky=Oo(d.defineComponent({__name:"ElbowArrow",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=d.ref(null),r=d.ref(0),o=d.ref(0),s=mt(e.entityId,yn),i=mt(e.entityId,Ce),a=d.computed(()=>e.hovered||e.selected);let l=null;d.onMounted(()=>{n.value&&(l=new ResizeObserver(()=>{n.value&&(r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),l.observe(n.value),r.value=n.value.clientWidth,o.value=n.value.clientHeight)}),d.onUnmounted(()=>{l==null||l.disconnect()});const c=d.computed(()=>{if(!s.value)return"#000000";const g=s.value.red.toString(16).padStart(2,"0"),y=s.value.green.toString(16).padStart(2,"0"),w=s.value.blue.toString(16).padStart(2,"0");return`#${g}${y}${w}`}),u=d.computed(()=>{var g;return((g=i.value)==null?void 0:g.thickness)??2}),f=d.computed(()=>`${u.value}px`),h=d.computed(()=>{if(!i.value)return[];const g=i.value,y=r.value,w=o.value,k=[];for(let b=0;b<g.pointCount;b++){const S=g.points[b*2]*y,v=g.points[b*2+1]*w;k.push([S,v])}return k}),p=d.computed(()=>{const g=h.value;if(g.length<2)return[];const y=[];for(let w=0;w<g.length-1;w++)y.push({start:g[w],end:g[w+1]});return y}),m=d.computed(()=>{var I,z,F,j;if(!i.value||h.value.length<2)return null;const g=i.value,y=[...h.value.map(M=>[...M])],w=g.startArrowHead,k=g.endArrowHead,b=[y[1][0]-y[0][0],y[1][1]-y[0][1]],S=[y[y.length-1][0]-y[y.length-2][0],y[y.length-1][1]-y[y.length-2][1]];let v=g.trimStart;if((I=e.connector)!=null&&I.startBlock&&w!=="none"){const M=Math.hypot(b[0],b[1]),V=((z=zs(w))==null?void 0:z.gap)??0,K=M>0?V/M:0;v+=K}let E=g.trimEnd;if((F=e.connector)!=null&&F.endBlock&&k!=="none"){const M=Math.hypot(S[0],S[1]),V=((j=zs(k))==null?void 0:j.gap)??0,K=M>0?V/M:0;E+=K}y[0]=[y[0][0]+(y[1][0]-y[0][0])*v,y[0][1]+(y[1][1]-y[0][1])*v];const T=y.length-1;y[T]=[y[T-1][0]+(y[T][0]-y[T-1][0])*(1-E),y[T-1][1]+(y[T][1]-y[T-1][1])*(1-E)];const _=[];for(let M=0;M<y.length-1;M++)_.push({start:y[M],end:y[M+1]});return L.scale(b,-1),{points:y,lines:_,startPos:y[0],endPos:y[y.length-1],startDir:b,endDir:S,startHead:w,endHead:k}});return(g,y)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-elbow-arrow"},[(d.openBlock(),d.createElementBlock("svg",$B,[a.value&&p.value.length>0?(d.openBlock(!0),d.createElementBlock(d.Fragment,{key:0},d.renderList(p.value,(w,k)=>(d.openBlock(),d.createElementBlock("line",{key:"bg-"+k,x1:w.start[0],y1:w.start[1],x2:w.end[0],y2:w.end[1],class:"highlight-bg",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))","stroke-dasharray":"calc(12px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,LB))),128)):d.createCommentVNode("",!0),m.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(m.value.lines,(w,k)=>(d.openBlock(),d.createElementBlock("line",{key:k,x1:w.start[0],y1:w.start[1],x2:w.end[0],y2:w.end[1],stroke:c.value,fill:"none","stroke-width":f.value,"stroke-linecap":"round"},null,8,VB))),128)),m.value.startHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:0,position:m.value.startPos,direction:m.value.startDir,thickness:f.value,"arrow-thickness":u.value,color:c.value,kind:m.value.startHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):d.createCommentVNode("",!0),m.value.endHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:1,position:m.value.endPos,direction:m.value.endDir,thickness:f.value,"arrow-thickness":u.value,color:c.value,kind:m.value.endHead},null,8,["position","direction","thickness","arrow-thickness","color","kind"])):d.createCommentVNode("",!0),a.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:2},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(m.value.lines,(w,k)=>(d.openBlock(),d.createElementBlock("line",{key:"hl-"+k,x1:w.start[0],y1:w.start[1],x2:w.end[0],y2:w.end[1],class:"highlight-overlay",fill:"none",style:{"stroke-width":"calc(2px / var(--wov-zoom))"},"stroke-linecap":"round"},null,8,FB))),128)),m.value.startHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:0,position:m.value.startPos,direction:m.value.startDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":u.value,color:"var(--wov-highlighted-block-outline-color)",kind:m.value.startHead},null,8,["position","direction","arrow-thickness","kind"])):d.createCommentVNode("",!0),m.value.endHead!=="none"?(d.openBlock(),d.createBlock(Tr,{key:1,position:m.value.endPos,direction:m.value.endDir,thickness:"calc(2px / var(--wov-zoom))","arrow-thickness":u.value,color:"var(--wov-highlighted-block-outline-color)",kind:m.value.endHead},null,8,["position","direction","arrow-thickness","kind"])):d.createCommentVNode("",!0)],64)):d.createCommentVNode("",!0)],64)):d.createCommentVNode("",!0)]))],512))}}),[["__scopeId","data-v-b2719db1"]]);var WB=Object.defineProperty,fd=(t,e)=>{for(var n in e)WB(t,n,{get:e[n],enumerable:!0})},vy=le("start-eraser-stroke"),by=le("add-eraser-stroke-point"),Sy=le("complete-eraser-stroke"),Ey=le("cancel-eraser-stroke"),Cy={};fd(Cy,{Erased:()=>Ro,EraserStroke:()=>Ii});var Ro=Ze({name:"erased"},{eraserStrokeId:C.ref()}),$s=8,UB="eraser",rr=20,Ii=Ze({name:"eraserStroke"},{points:C.buffer(C.float32()).size(rr*2),pointCount:C.uint32().default(0),firstPointIndex:C.uint32().default(0),radius:C.float32().default(8)}),xy={};fd(xy,{EraserStateSingleton:()=>hd});var zo={Idle:"idle",Erasing:"erasing"},hd=to("eraserState",{state:C.string().max(16).default(zo.Idle),activeStroke:C.ref(),lastWorldPosition:C.tuple(C.float64(),2).default([0,0])}),Ty={};fd(Ty,{captureEraserSystem:()=>jB,updateEraserSystem:()=>YB});var HB=br({guards:{},actions:{startStroke:({event:t})=>{vy.spawn(t.ctx,{worldPosition:t.worldPosition})},addPoint:Re({lastWorldPosition:({event:t,context:e})=>e.activeStroke?(by.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition}),[t.worldPosition[0],t.worldPosition[1]]):e.lastWorldPosition}),completeStroke:({event:t,context:e})=>{e.activeStroke&&Sy.spawn(t.ctx,{strokeId:e.activeStroke})},cancelStroke:({event:t,context:e})=>{e.activeStroke&&Ey.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:Re({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"eraser",initial:zo.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[zo.Idle]:{entry:["resetContext"],on:{pointerDown:{target:zo.Erasing,actions:["startStroke"]}}},[zo.Erasing]:{on:{pointerMove:{actions:["addPoint"]},frame:{actions:["addPoint"]},pointerUp:{target:zo.Idle,actions:["completeStroke"]},cancel:{target:zo.Idle,actions:["cancelStroke"]}}}}}),jB=ge({phase:"capture",priority:100},t=>{const e=et.getButtons(t,"eraser"),n=xr(t,e,{includeFrameEvent:!0});n.length!==0&&hd.run(t,HB,n)}),ZB=re(t=>t.with(A,de,Be)),KB=re(t=>t.with(Ro)),YB=ge({phase:"update"},t=>{ae(t,vy,(e,{worldPosition:n})=>{qB(e,n)}),ae(t,by,(e,{strokeId:n,worldPosition:r})=>{XB(e,n,r)}),ae(t,Sy,(e,{strokeId:n})=>{QB(e,n)}),ae(t,Ey,(e,{strokeId:n})=>{eN(e,n)})});function qB(t,e){const n=bt(t);J(t,n,A,{tag:"eraser",rank:Dn.genNext(t),position:[e[0]-$s,e[1]-$s],size:[$s*2,$s*2]}),J(t,n,Ii,{points:e,pointCount:1,firstPointIndex:0,radius:$s});const r=hd.write(t);r.activeStroke=n,r.lastWorldPosition=e}function XB(t,e,n){const r=Ii.write(t,e),o=r.pointCount,s=(o-1)%rr*2,i=r.points[s],a=r.points[s+1],l=o%rr*2;if(r.points[l]=n[0],r.points[l+1]=n[1],r.pointCount++,r.pointCount>rr&&(r.firstPointIndex=(r.pointCount-rr)%rr),!Be.containsPoint(t,e,n)){Be.expandByPoint(t,e,n);const{value:g}=Be.read(t,e),y=A.write(t,e);L.set(y.position,ee.left(g),ee.top(g)),L.set(y.size,ee.width(g),ee.height(g))}const c=n[0]-i,u=n[1]-a;if(c*c+u*u<1)return;const h=ot.create(i,a,n[0],n[1],$s),p=GB(t,ZB.current(t)),m=D_(t,h,p);for(const g of m)JB(t,g,e)}function*GB(t,e){for(const n of e)O(t,n,Ro)||(yield n)}function JB(t,e,n){J(t,e,Ro,{eraserStrokeId:n}),J(t,e,Qe,{value:80})}function QB(t,e){const n=Jn(t,e,Ro,"eraserStrokeId");for(const r of n)qe(t,r);qe(t,e)}function eN(t,e){const n=[];for(const r of KB.current(t))Ro.read(t,r).eraserStrokeId===e&&n.push(r);for(const r of n)nn(t,r,Ro),nn(t,r,Qe);qe(t,e)}var tN=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e),nN=qt({tailRadius:Je().positive().optional(),tailLength:Je().int().min(1).max(rr).optional()});function rN(t={}){const e=nN.parse(t);return{name:UB,components:Object.values(Cy).filter(n=>n instanceof Kt),singletons:Object.values(xy).filter(n=>n instanceof St),blockDefs:[{tag:"eraser-stroke",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ii]}],systems:tN(Ty),resources:{tailRadius:e.tailRadius??8,tailLength:e.tailLength??rr}}}function My(t,e,n,r=o=>o){return t*r(.5-e*(.5-n))}function oN(t){return[-t[0],-t[1]]}function Vn(t,e){return[t[0]+e[0],t[1]+e[1]]}function Cn(t,e){return[t[0]-e[0],t[1]-e[1]]}function Fn(t,e){return[t[0]*e,t[1]*e]}function sN(t,e){return[t[0]/e,t[1]/e]}function Bi(t){return[t[1],-t[0]]}function Ay(t,e){return t[0]*e[0]+t[1]*e[1]}function iN(t,e){return t[0]===e[0]&&t[1]===e[1]}function aN(t){return Math.hypot(t[0],t[1])}function lN(t){return t[0]*t[0]+t[1]*t[1]}function _y(t,e){return lN(Cn(t,e))}function Iy(t){return sN(t,aN(t))}function cN(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function Ni(t,e,n){let r=Math.sin(n),o=Math.cos(n),s=t[0]-e[0],i=t[1]-e[1],a=s*o-i*r,l=s*r+i*o;return[a+e[0],l+e[1]]}function pd(t,e,n){return Vn(t,Fn(Cn(e,t),n))}function By(t,e,n){return Vn(t,Fn(e,n))}var{min:Ls,PI:uN}=Math,Ny=.275,Pi=uN+1e-4;function dN(t,e={}){let{size:n=16,smoothing:r=.5,thinning:o=.5,simulatePressure:s=!0,easing:i=Y=>Y,start:a={},end:l={},last:c=!1}=e,{cap:u=!0,easing:f=Y=>Y*(2-Y)}=a,{cap:h=!0,easing:p=Y=>--Y*Y*Y+1}=l;if(t.length===0||n<=0)return[];let m=t[t.length-1].runningLength,g=a.taper===!1?0:a.taper===!0?Math.max(n,m):a.taper,y=l.taper===!1?0:l.taper===!0?Math.max(n,m):l.taper,w=Math.pow(n*r,2),k=[],b=[],S=t.slice(0,10).reduce((Y,R)=>{let W=R.pressure;if(s){let Q=Ls(1,R.distance/n),pe=Ls(1,1-Q);W=Ls(1,Y+(pe-Y)*(Q*Ny))}return(Y+W)/2},t[0].pressure),v=My(n,o,t[t.length-1].pressure,i),E,T=t[0].vector,_=t[0].point,I=_,z=_,F=I,j=!1;for(let Y=0;Y<t.length;Y++){let{pressure:R}=t[Y],{point:W,vector:Q,distance:pe,runningLength:me}=t[Y];if(Y<t.length-1&&m-me<3)continue;if(o){if(s){let Pn=Ls(1,pe/n),si=Ls(1,1-Pn);R=Ls(1,S+(si-S)*(Pn*Ny))}v=My(n,o,R,i)}else v=n/2;E===void 0&&(E=v);let Ue=me<g?f(me/g):1,Yn=m-me<y?p((m-me)/y):1;v=Math.max(.01,v*Math.min(Ue,Yn));let pr=(Y<t.length-1?t[Y+1]:t[Y]).vector,So=Y<t.length-1?Ay(Q,pr):1,ri=Ay(Q,T)<0&&!j,ca=So!==null&&So<0;if(ri||ca){let Pn=Fn(Bi(T),v);for(let si=1/13,N=0;N<=1;N+=si)z=Ni(Cn(W,Pn),W,Pi*N),k.push(z),F=Ni(Vn(W,Pn),W,Pi*-N),b.push(F);_=z,I=F,ca&&(j=!0);continue}if(j=!1,Y===t.length-1){let Pn=Fn(Bi(Q),v);k.push(Cn(W,Pn)),b.push(Vn(W,Pn));continue}let oi=Fn(Bi(pd(pr,Q,So)),v);z=Cn(W,oi),(Y<=1||_y(_,z)>w)&&(k.push(z),_=z),F=Vn(W,oi),(Y<=1||_y(I,F)>w)&&(b.push(F),I=F),S=R,T=Q}let M=t[0].point.slice(0,2),V=t.length>1?t[t.length-1].point.slice(0,2):Vn(t[0].point,[1,1]),K=[],se=[];if(t.length===1){if(!(g||y)||c){let Y=By(M,Iy(Bi(Cn(M,V))),-(E||v)),R=[];for(let W=1/13,Q=W;Q<=1;Q+=W)R.push(Ni(Y,M,Pi*2*Q));return R}}else{if(!(g||y&&t.length===1))if(u)for(let R=1/13,W=R;W<=1;W+=R){let Q=Ni(b[0],M,Pi*W);K.push(Q)}else{let R=Cn(k[0],b[0]),W=Fn(R,.5),Q=Fn(R,.51);K.push(Cn(M,W),Cn(M,Q),Vn(M,Q),Vn(M,W))}let Y=Bi(oN(t[t.length-1].vector));if(y||g&&t.length===1)se.push(V);else if(h){let R=By(V,Y,v);for(let W=1/29,Q=W;Q<1;Q+=W)se.push(Ni(R,V,Pi*3*Q))}else se.push(Vn(V,Fn(Y,v)),Vn(V,Fn(Y,v*.99)),Cn(V,Fn(Y,v*.99)),Cn(V,Fn(Y,v)))}return k.concat(se,b.reverse(),K)}function fN(t,e={}){var n;let{streamline:r=.5,size:o=16,last:s=!1}=e;if(t.length===0)return[];let i=.15+(1-r)*.85,a=Array.isArray(t[0])?t:t.map(({x:p,y:m,pressure:g=.5})=>[p,m,g]);if(a.length===2){let p=a[1];a=a.slice(0,-1);for(let m=1;m<5;m++)a.push(pd(a[0],p,m/4))}a.length===1&&(a=[...a,[...Vn(a[0],[1,1]),...a[0].slice(2)]]);let l=[{point:[a[0][0],a[0][1]],pressure:a[0][2]>=0?a[0][2]:.25,vector:[1,1],distance:0,runningLength:0}],c=!1,u=0,f=l[0],h=a.length-1;for(let p=1;p<a.length;p++){let m=s&&p===h?a[p].slice(0,2):pd(f.point,a[p],i);if(iN(f.point,m))continue;let g=cN(m,f.point);if(u+=g,p<h&&!c){if(u<o)continue;c=!0}f={point:m,pressure:a[p][2]>=0?a[p][2]:.5,vector:Iy(Cn(f.point,m)),distance:g,runningLength:u},l.push(f)}return l[0].vector=((n=l[1])==null?void 0:n.vector)||[0,0],l}function md(t,e={}){return dN(fN(t,e),e)}const hN={class:"wov-eraser-stroke"},pN={preserveAspectRatio:"none"},mN=["d"],gN="#88888833",Py=d.defineComponent({__name:"Eraser",props:{entityId:{}},setup(t){const e=t,n=mt(e.entityId,Ii),r=mt(e.entityId,A),o=d.shallowRef("");function s(a,l){return(a+l)/2}function i(a,l,c,u,f,h){if(a<=4)return"";const p=[],m=Math.min(a,rr);for(let S=0;S<m;S++){const v=(l+S)%rr*2;p.push([c[v]-f,c[v+1]-h])}const g=md(p,{size:u,start:{taper:66,cap:!0}});if(g.length<3)return"";let y=g[0],w=g[1];const k=g[2];let b=`M${y[0].toFixed(2)},${y[1].toFixed(2)} Q${w[0].toFixed(2)},${w[1].toFixed(2)} ${s(w[0],k[0]).toFixed(2)},${s(w[1],k[1]).toFixed(2)} T`;for(let S=2;S<g.length-1;S++)y=g[S],w=g[S+1],b+=`${s(y[0],w[0]).toFixed(2)},${s(y[1],w[1]).toFixed(2)} `;return b+=`${w[0].toFixed(2)},${w[1].toFixed(2)} `,b+="Z",b}return d.watch([n,r],([a,l])=>{if(!a||!l){o.value="";return}const c=a.radius??8,[u,f]=l.position;o.value=i(a.pointCount,a.firstPointIndex,a.points,2*c,u,f)},{immediate:!0}),(a,l)=>(d.openBlock(),d.createElementBlock("div",hN,[(d.openBlock(),d.createElementBlock("svg",pN,[d.createElementVNode("path",{d:o.value,fill:gN},null,8,mN)]))]))}}),yN={class:"wov-image-block"},wN={key:0,class:"wov-image-placeholder"},kN={key:1,class:"wov-image-placeholder wov-image-error"},vN=["src","alt"],bN={key:3,class:"wov-image-upload-overlay"},SN={class:"wov-image-upload-status"},Dy=d.defineComponent({__name:"ImageBlock",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=d.inject(En);if(!n)throw new Error("ImageBlock must be used within a WovenCanvas component");const r=n,o=mt(e.entityId,Bo),s=mt(e.entityId,pi),i=d.ref(null),a=d.ref(!0),l=d.ref(!1);let c=!0;d.onUnmounted(()=>{c=!1});async function u(){const p=r.getAssetManager();if(!p){a.value=!1,l.value=!0;return}const m=o.value;if(!m){a.value=!1;return}try{a.value=!0,l.value=!1;const g=await p.getDisplayUrl(m.identifier);if(!c)return;g?(i.value=g,a.value=!1):m.uploadState===nr.Failed&&(l.value=!0,a.value=!1)}catch(g){if(!c)return;console.error("Failed to get display URL:",g),l.value=!0,a.value=!1}}d.watch(()=>o.value,()=>{u()},{immediate:!0}),d.onMounted(()=>{u()});const f=d.computed(()=>{const p=o.value;if(!p)return null;switch(p.uploadState){case nr.Pending:return"Loading...";case nr.Uploading:return"Loading...";case nr.Failed:return"Failed";default:return null}}),h=d.computed(()=>({width:"100%",height:"100%",objectFit:"fill"}));return(p,m)=>{var g;return d.openBlock(),d.createElementBlock("div",yN,[a.value&&!i.value?(d.openBlock(),d.createElementBlock("div",wN,[...m[0]||(m[0]=[d.createElementVNode("span",null,"Loading...",-1)])])):l.value?(d.openBlock(),d.createElementBlock("div",kN,[...m[1]||(m[1]=[d.createElementVNode("span",null,"Failed to load image",-1)])])):i.value?(d.openBlock(),d.createElementBlock("img",{key:2,src:i.value,alt:((g=d.unref(s))==null?void 0:g.alt)||"",style:d.normalizeStyle(h.value),draggable:"false"},null,12,vN)):d.createCommentVNode("",!0),f.value?(d.openBlock(),d.createElementBlock("div",bN,[d.createElementVNode("span",SN,d.toDisplayString(f.value),1)])):d.createCommentVNode("",!0)])}}});function EN(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Oy={exports:{}};(function(t){(function(){function e(a,l){var c=a.x-l.x,u=a.y-l.y;return c*c+u*u}function n(a,l,c){var u=l.x,f=l.y,h=c.x-u,p=c.y-f;if(h!==0||p!==0){var m=((a.x-u)*h+(a.y-f)*p)/(h*h+p*p);m>1?(u=c.x,f=c.y):m>0&&(u+=h*m,f+=p*m)}return h=a.x-u,p=a.y-f,h*h+p*p}function r(a,l){for(var c=a[0],u=[c],f,h=1,p=a.length;h<p;h++)f=a[h],e(f,c)>l&&(u.push(f),c=f);return c!==f&&u.push(f),u}function o(a,l,c,u,f){for(var h=u,p,m=l+1;m<c;m++){var g=n(a[m],a[l],a[c]);g>h&&(p=m,h=g)}h>u&&(p-l>1&&o(a,l,p,u,f),f.push(a[p]),c-p>1&&o(a,p,c,u,f))}function s(a,l){var c=a.length-1,u=[a[0]];return o(a,0,c,l,u),u.push(a[c]),u}function i(a,l,c){if(a.length<=2)return a;var u=l!==void 0?l*l:1;return a=c?a:r(a,u),a=s(a,u),a}t.exports=i,t.exports.default=i})()})(Oy);var CN=Oy.exports;const Ry=EN(CN);var xN=Object.defineProperty,gd=(t,e)=>{for(var n in e)xN(t,n,{get:e[n],enumerable:!0})},zy=le("start-pen-stroke"),$y=le("add-pen-stroke-point"),Ly=le("complete-pen-stroke"),Vy=le("remove-pen-stroke"),Fy={};gd(Fy,{POINTS_CAPACITY:()=>yl,PenStroke:()=>Wn});var yl=256,TN={points:C.buffer(C.float32()).size(yl*2),pressures:C.buffer(C.float32()).size(yl),pointCount:C.uint32().default(0),thickness:C.float32().default(8),originalLeft:C.float32().default(0),originalTop:C.float32().default(0),originalWidth:C.float32().default(0),originalHeight:C.float32().default(0),isComplete:C.boolean().default(!1),hasPressure:C.boolean().default(!1)},MN=class extends Kt{constructor(){super({name:"penStroke",sync:"document"},TN)}snapshot(t,e){const n=super.snapshot(t,e),r=n.pointCount;return n.points=n.points.slice(0,r*2),n.pressures=n.hasPressure?n.pressures.slice(0,r):new Float32Array(0),n}},Wn=new MN,AN=8,_N="pen",Wy={};gd(Wy,{PenStateSingleton:()=>yd});var $o={Idle:"idle",Drawing:"drawing"},yd=to("penState",{state:C.string().max(16).default($o.Idle),activeStroke:C.ref(),lastWorldPosition:C.tuple(C.float64(),2).default([0,0])}),Uy={};gd(Uy,{capturePenSystem:()=>BN,updatePenSystem:()=>PN});var IN=br({guards:{},actions:{startStroke:({event:t})=>{const e=t.pointerType===Jr.Pen?t.pressure:null;zy.spawn(t.ctx,{worldPosition:t.worldPosition,pressure:e,thickness:AN})},addPoint:Re({lastWorldPosition:({event:t,context:e})=>{if(!e.activeStroke)return e.lastWorldPosition;const n=t.pointerType===Jr.Pen?t.pressure:null;return $y.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition,pressure:n}),t.worldPosition}}),completeStroke:({event:t,context:e})=>{e.activeStroke&&Ly.spawn(t.ctx,{strokeId:e.activeStroke})},removeStroke:({event:t,context:e})=>{e.activeStroke&&Vy.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:Re({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"pen",initial:$o.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[$o.Idle]:{entry:["resetContext"],on:{pointerDown:{target:$o.Drawing,actions:["startStroke"]}}},[$o.Drawing]:{on:{pointerMove:{actions:["addPoint"]},pointerUp:{target:$o.Idle,actions:["completeStroke"]},cancel:{target:$o.Idle,actions:["removeStroke"]}}}}}),BN=ge({phase:"capture",priority:100},t=>{const e=et.getButtons(t,"pen"),n=xr(t,e);n.length!==0&&yd.run(t,IN,n)}),NN=re(t=>t.tracking(Wn)),PN=ge({phase:"update"},t=>{ae(t,zy,(e,{worldPosition:n,pressure:r,thickness:o})=>{DN(e,n,r,o)}),ae(t,$y,(e,{strokeId:n,worldPosition:r,pressure:o})=>{ON(e,n,r,o)}),ae(t,Ly,(e,{strokeId:n})=>{RN(e,n)}),ae(t,Vy,(e,{strokeId:n})=>{zN(e,n)});for(const e of NN.addedOrChanged(t))Wn.read(t,e).isComplete&&Hy(t,e)});function DN(t,e,n,r){const o=r/2,s=bt(t);J(t,s,de,{id:crypto.randomUUID()}),J(t,s,A,{tag:"pen-stroke",rank:Dn.genNext(t),position:[e[0]-o,e[1]-o],size:[o*2,o*2]}),J(t,s,yn,{});const{sessionId:i}=Ve(t);J(t,s,Tt,{sessionId:i});const a=n!==null;J(t,s,Wn,{points:e,pressures:[a?n:.5],pointCount:1,thickness:r,originalLeft:e[0]-o,originalTop:e[1]-o,originalWidth:o*2,originalHeight:o*2,isComplete:!1,hasPressure:a});const c=yd.write(t);c.activeStroke=s,c.lastWorldPosition=e}function ON(t,e,n,r){const o=Wn.write(t,e),s=o.pointCount;if(!(s>=yl)&&(o.points[s*2]=n[0],o.points[s*2+1]=n[1],r!==null?o.pressures[s]=r:o.pressures[s]=.5,o.pointCount++,!Be.containsPoint(t,e,n))){Be.expandByPoint(t,e,n);const{value:i}=Be.read(t,e),a=A.write(t,e);L.set(a.position,ee.left(i),ee.top(i)),L.set(a.size,ee.width(i),ee.height(i)),o.originalLeft=a.position[0],o.originalTop=a.position[1],o.originalWidth=a.size[0],o.originalHeight=a.size[1]}}function RN(t,e){const n=Wn.write(t,e);n.isComplete=!0,nn(t,e,Tt),Hy(t,e)}function zN(t,e){qe(t,e)}function Hy(t,e){const n=Wn.read(t,e),r=[];for(let u=0;u<n.pointCount;u++)r.push({x:n.points[u*2],y:n.points[u*2+1]});let o=n.thickness,s=Ry(r,o,!1);for(;s.length-1>Ms;)o*=2,s=Ry(r,o,!1);if(s.length===1){const u=s[0];s.push({x:u.x,y:u.y})}O(t,e,ke)?ke.clear(t,e):J(t,e,ke,{});const{originalLeft:i,originalTop:a,originalWidth:l,originalHeight:c}=n;for(let u=0;u<s.length-1;u++){const f=s[u],h=s[u+1],p=[(f.x-i)/l,(f.y-a)/c],m=[(h.x-i)/l,(h.y-a)/c];ke.addCapsuleUv(t,e,p,m,n.thickness)}}var $N=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function LN(){return{name:_N,components:Object.values(Fy).filter(t=>t instanceof Kt),singletons:Object.values(Wy).filter(t=>t instanceof St),blockDefs:[{tag:"pen-stroke",resizeMode:"free",components:[Wn,yn],connectors:{enabled:!1}}],systems:$N(Uy),resources:{}}}const VN=["data-complete"],FN={preserveAspectRatio:"none"},WN=["d","fill"],UN={key:0,class:"highlight",preserveAspectRatio:"none"},HN=["d"],jy=Oo(d.defineComponent({__name:"PenStroke",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=mt(e.entityId,Wn),r=mt(e.entityId,A),o=mt(e.entityId,yn),s=d.shallowRef(""),i=d.shallowRef("");function a(f,h){return(f+h)/2}function l(f,h,p){if(h<=4||f.length<3){const k=p/2;return`M ${k},0 a ${k},${k} 0 1 0 0.0001 0`}let m=f[0],g=f[1];const y=f[2];let w=`M${m[0].toFixed(2)},${m[1].toFixed(2)} Q${g[0].toFixed(2)},${g[1].toFixed(2)} ${a(g[0],y[0]).toFixed(2)},${a(g[1],y[1]).toFixed(2)} T`;for(let k=2;k<f.length-1;k++)m=f[k],g=f[k+1],w+=`${a(m[0],g[0]).toFixed(2)},${a(m[1],g[1]).toFixed(2)} `;return w+=`${g[0].toFixed(2)},${g[1].toFixed(2)} `,w+="Z",w}d.watch([n,r],([f,h])=>{if(!f||!h){s.value="",i.value="";return}if(!f.originalWidth||!f.originalHeight){s.value="",i.value="";return}const p=h.size[0]/f.originalWidth,m=h.size[1]/f.originalHeight,g=[];for(let w=0;w<f.pointCount;w++){const k=f.points[w*2],b=f.points[w*2+1],S=(k-f.originalLeft)*p,v=(b-f.originalTop)*m;f.hasPressure?g.push([S,v,f.pressures[w]]):g.push([S,v])}const y=md(g,{last:f.isComplete,size:f.thickness,simulatePressure:!f.hasPressure});if(s.value=l(y,f.pointCount,f.thickness),f.isComplete){const w=g.length===1?f.thickness:1,k=md(g,{last:!0,size:w,simulatePressure:!f.hasPressure});i.value=l(k,f.pointCount,w)}},{immediate:!0});const c=d.computed(()=>o.value?`rgb(${o.value.red}, ${o.value.green}, ${o.value.blue})`:"#000000"),u=d.computed(()=>e.selected||e.hovered);return(f,h)=>{var p;return d.openBlock(),d.createElementBlock("div",{class:"wov-pen-stroke","data-complete":((p=d.unref(n))==null?void 0:p.isComplete)||void 0},[(d.openBlock(),d.createElementBlock("svg",FN,[d.createElementVNode("path",{d:s.value,fill:c.value},null,8,WN)])),u.value?(d.openBlock(),d.createElementBlock("svg",UN,[d.createElementVNode("path",{d:i.value,stroke:"var(--wov-highlighted-block-outline-color)",style:{"stroke-width":"calc(1px / var(--wov-zoom))"},fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},null,8,HN)])):d.createCommentVNode("",!0)],8,VN)}}}),[["__scopeId","data-v-9b41c649"]]);function tt(){const t=d.inject(En);if(!t)throw new Error("useEditorContext must be used within a WovenCanvas component");return{getEditor:()=>t.getEditor(),nextEditorTick(e){return new Promise(n=>{const r=t.getEditor();r&&r.nextTick(o=>{e==null||e(o),n(o)})})}}}const Di={rectangle:"M0,0 L100,0 L100,100 L0,100 Z",ellipse:"M50,0 A50,50 0 1,1 50,100 A50,50 0 1,1 50,0",triangle:"M50,0 L100,100 L0,100 Z",diamond:"M50,0 L100,50 L50,100 L0,50 Z",pentagon:"M50,0 L100,38.2 L80.9,100 L19.1,100 L0,38.2 Z",hexagon:"M50,0 L100,25 L100,75 L50,100 L0,75 L0,25 Z",star:"M50,0 L61.8,38.2 L100,38.2 L69.1,61.8 L80.9,100 L50,76.4 L19.1,100 L30.9,61.8 L0,38.2 L38.2,38.2 Z",heart:"M50,16 C44,7 37,0 26,0 11,0 0,12 0,28 0,60 16,65 50,100 84,65 100,60 100,28 100,12 89,0 74,0 63,0 56,7 50,16 Z",arrow:"M0,35 L60,35 L60,0 L100,50 L60,100 L60,65 L0,65 Z"};function At(t){this.content=t}At.prototype={constructor:At,find:function(t){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return e==-1?void 0:this.content[e+1]},update:function(t,e,n){var r=n&&n!=t?this.remove(n):this,o=r.find(t),s=r.content.slice();return o==-1?s.push(n||t,e):(s[o+1]=e,n&&(s[o]=n)),new At(s)},remove:function(t){var e=this.find(t);if(e==-1)return this;var n=this.content.slice();return n.splice(e,2),new At(n)},addToStart:function(t,e){return new At([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new At(n)},addBefore:function(t,e,n){var r=this.remove(e),o=r.content.slice(),s=r.find(t);return o.splice(s==-1?o.length:s,0,e,n),new At(o)},forEach:function(t){for(var e=0;e<this.content.length;e+=2)t(this.content[e],this.content[e+1])},prepend:function(t){return t=At.from(t),t.size?new At(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=At.from(t),t.size?new At(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=At.from(t);for(var n=0;n<t.content.length;n+=2)e=e.remove(t.content[n]);return e},toObject:function(){var t={};return this.forEach(function(e,n){t[e]=n}),t},get size(){return this.content.length>>1}},At.from=function(t){if(t instanceof At)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new At(e)};function Zy(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let o=t.child(r),s=e.child(r);if(o==s){n+=o.nodeSize;continue}if(!o.sameMarkup(s))return n;if(o.isText&&o.text!=s.text){for(let i=0;o.text[i]==s.text[i];i++)n++;return n}if(o.content.size||s.content.size){let i=Zy(o.content,s.content,n+1);if(i!=null)return i}n+=o.nodeSize}}function Ky(t,e,n,r){for(let o=t.childCount,s=e.childCount;;){if(o==0||s==0)return o==s?null:{a:n,b:r};let i=t.child(--o),a=e.child(--s),l=i.nodeSize;if(i==a){n-=l,r-=l;continue}if(!i.sameMarkup(a))return{a:n,b:r};if(i.isText&&i.text!=a.text){let c=0,u=Math.min(i.text.length,a.text.length);for(;c<u&&i.text[i.text.length-c-1]==a.text[a.text.length-c-1];)c++,n--,r--;return{a:n,b:r}}if(i.content.size||a.content.size){let c=Ky(i.content,a.content,n-1,r-1);if(c)return c}n-=l,r-=l}}class D{constructor(e,n){if(this.content=e,this.size=n||0,n==null)for(let r=0;r<e.length;r++)this.size+=e[r].nodeSize}nodesBetween(e,n,r,o=0,s){for(let i=0,a=0;a<n;i++){let l=this.content[i],c=a+l.nodeSize;if(c>e&&r(l,o+a,s||null,i)!==!1&&l.content.size){let u=a+1;l.nodesBetween(Math.max(0,e-u),Math.min(l.content.size,n-u),r,o+u)}a=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,o){let s="",i=!0;return this.nodesBetween(e,n,(a,l)=>{let c=a.isText?a.text.slice(Math.max(e,l)-l,n-l):a.isLeaf?o?typeof o=="function"?o(a):o:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&c||a.isTextblock)&&r&&(i?i=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,o=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(o[o.length-1]=n.withText(n.text+r.text),s=1);s<e.content.length;s++)o.push(e.content[s]);return new D(o,this.size+e.size)}cut(e,n=this.size){if(e==0&&n==this.size)return this;let r=[],o=0;if(n>e)for(let s=0,i=0;i<n;s++){let a=this.content[s],l=i+a.nodeSize;l>e&&((i<e||l>n)&&(a.isText?a=a.cut(Math.max(0,e-i),Math.min(a.text.length,n-i)):a=a.cut(Math.max(0,e-i-1),Math.min(a.content.size,n-i-1))),r.push(a),o+=a.nodeSize),i=l}return new D(r,o)}cutByIndex(e,n){return e==n?D.empty:e==0&&n==this.content.length?this:new D(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let o=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return o[e]=n,new D(o,s)}addToStart(e){return new D([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new D(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;n<this.content.length;n++)if(!this.content[n].eq(e.content[n]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(e){let n=this.content[e];if(!n)throw new RangeError("Index "+e+" out of range for "+this);return n}maybeChild(e){return this.content[e]||null}forEach(e){for(let n=0,r=0;n<this.content.length;n++){let o=this.content[n];e(o,r,n),r+=o.nodeSize}}findDiffStart(e,n=0){return Zy(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return Ky(this,e,n,r)}findIndex(e){if(e==0)return wl(0,e);if(e==this.size)return wl(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let o=this.child(n),s=r+o.nodeSize;if(s>=e)return s==e?wl(n+1,s):wl(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return D.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new D(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return D.empty;let n,r=0;for(let o=0;o<e.length;o++){let s=e[o];r+=s.nodeSize,o&&s.isText&&e[o-1].sameMarkup(s)?(n||(n=e.slice(0,o)),n[n.length-1]=s.withText(n[n.length-1].text+s.text)):n&&n.push(s)}return new D(n||e,r)}static from(e){if(!e)return D.empty;if(e instanceof D)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new D([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}D.empty=new D([],0);const wd={index:0,offset:0};function wl(t,e){return wd.index=t,wd.offset=e,wd}function kl(t,e){if(t===e)return!0;if(!(t&&typeof t=="object")||!(e&&typeof e=="object"))return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let r=0;r<t.length;r++)if(!kl(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!kl(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let Ne=class ih{constructor(e,n){this.type=e,this.attrs=n}addToSet(e){let n,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(this.eq(s))return e;if(this.type.excludes(s.type))n||(n=e.slice(0,o));else{if(s.type.excludes(this.type))return e;!r&&s.type.rank>this.type.rank&&(n||(n=e.slice(0,o)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return e.slice(0,n).concat(e.slice(n+1));return e}isInSet(e){for(let n=0;n<e.length;n++)if(this.eq(e[n]))return!0;return!1}eq(e){return this==e||this.type==e.type&&kl(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Mark.fromJSON");let r=e.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);let o=r.create(n.attrs);return r.checkAttrs(o.attrs),o}static sameSet(e,n){if(e==n)return!0;if(e.length!=n.length)return!1;for(let r=0;r<e.length;r++)if(!e[r].eq(n[r]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return ih.none;if(e instanceof ih)return[e];let n=e.slice();return n.sort((r,o)=>r.type.rank-o.type.rank),n}};Ne.none=[];class vl extends Error{}class Z{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=qy(this.content,e+this.openStart,n);return r&&new Z(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Z(Yy(this.content,e+this.openStart,n+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,n){if(!n)return Z.empty;let r=n.openStart||0,o=n.openEnd||0;if(typeof r!="number"||typeof o!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Z(D.fromJSON(e,n.content),r,o)}static maxOpen(e,n=!0){let r=0,o=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)o++;return new Z(e,r,o)}}Z.empty=new Z(D.empty,0,0);function Yy(t,e,n){let{index:r,offset:o}=t.findIndex(e),s=t.maybeChild(r),{index:i,offset:a}=t.findIndex(n);if(o==e||s.isText){if(a!=n&&!t.child(i).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=i)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(Yy(s.content,e-o-1,n-o-1)))}function qy(t,e,n,r){let{index:o,offset:s}=t.findIndex(e),i=t.maybeChild(o);if(s==e||i.isText)return r&&!r.canReplace(o,o,n)?null:t.cut(0,e).append(n).append(t.cut(e));let a=qy(i.content,e-s-1,n,i);return a&&t.replaceChild(o,i.copy(a))}function jN(t,e,n){if(n.openStart>t.depth)throw new vl("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new vl("Inconsistent open depths");return Xy(t,e,n,0)}function Xy(t,e,n,r){let o=t.index(r),s=t.node(r);if(o==e.index(r)&&r<t.depth-n.openStart){let i=Xy(t,e,n,r+1);return s.copy(s.content.replaceChild(o,i))}else if(n.content.size)if(!n.openStart&&!n.openEnd&&t.depth==r&&e.depth==r){let i=t.parent,a=i.content;return Vo(i,a.cut(0,t.parentOffset).append(n.content).append(a.cut(e.parentOffset)))}else{let{start:i,end:a}=ZN(n,t);return Vo(s,Jy(t,i,a,e,r))}else return Vo(s,bl(t,e,r))}function Gy(t,e){if(!e.type.compatibleContent(t.type))throw new vl("Cannot join "+e.type.name+" onto "+t.type.name)}function kd(t,e,n){let r=t.node(n);return Gy(r,e.node(n)),r}function Lo(t,e){let n=e.length-1;n>=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function Oi(t,e,n,r){let o=(e||t).node(n),s=0,i=e?e.index(n):o.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Lo(t.nodeAfter,r),s++));for(let a=s;a<i;a++)Lo(o.child(a),r);e&&e.depth==n&&e.textOffset&&Lo(e.nodeBefore,r)}function Vo(t,e){return t.type.checkContent(e),t.copy(e)}function Jy(t,e,n,r,o){let s=t.depth>o&&kd(t,e,o+1),i=r.depth>o&&kd(n,r,o+1),a=[];return Oi(null,t,o,a),s&&i&&e.index(o)==n.index(o)?(Gy(s,i),Lo(Vo(s,Jy(t,e,n,r,o+1)),a)):(s&&Lo(Vo(s,bl(t,e,o+1)),a),Oi(e,n,o,a),i&&Lo(Vo(i,bl(n,r,o+1)),a)),Oi(r,null,o,a),new D(a)}function bl(t,e,n){let r=[];if(Oi(null,t,n,r),t.depth>n){let o=kd(t,e,n+1);Lo(Vo(o,bl(t,e,n+1)),r)}return Oi(e,null,n,r),new D(r)}function ZN(t,e){let n=e.depth-t.openStart,o=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)o=e.node(s).copy(D.from(o));return{start:o.resolveNoCache(t.openStart+n),end:o.resolveNoCache(o.content.size-t.openEnd-n)}}class Ri{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.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,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],o=e.child(n);return r?e.child(n).cut(r):o}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],o=n==0?0:this.path[n*3-1]+1;for(let s=0;s<e;s++)o+=r.child(s).nodeSize;return o}marks(){let e=this.parent,n=this.index();if(e.content.size==0)return Ne.none;if(this.textOffset)return e.child(n).marks;let r=e.maybeChild(n-1),o=e.maybeChild(n);if(!r){let a=r;r=o,o=a}let s=r.marks;for(var i=0;i<s.length;i++)s[i].type.spec.inclusive===!1&&(!o||!s[i].isInSet(o.marks))&&(s=s[i--].removeFromSet(s));return s}marksAcross(e){let n=this.parent.maybeChild(this.index());if(!n||!n.isInline)return null;let r=n.marks,o=e.parent.maybeChild(e.index());for(var s=0;s<r.length;s++)r[s].type.spec.inclusive===!1&&(!o||!r[s].isInSet(o.marks))&&(r=r[s--].removeFromSet(r));return r}sharedDepth(e){for(let n=this.depth;n>0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos<this.pos)return e.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);r>=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new Sl(this,e,r);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<this.pos?e:this}toString(){let e="";for(let n=1;n<=this.depth;n++)e+=(e?"/":"")+this.node(n).type.name+"_"+this.index(n-1);return e+":"+this.parentOffset}static resolve(e,n){if(!(n>=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],o=0,s=n;for(let i=e;;){let{index:a,offset:l}=i.content.findIndex(s),c=s-l;if(r.push(i,a,o+l),!c||(i=i.child(a),i.isText))break;s=c-1,o+=l+1}return new Ri(n,r,s)}static resolveCached(e,n){let r=Qy.get(e);if(r)for(let s=0;s<r.elts.length;s++){let i=r.elts[s];if(i.pos==n)return i}else Qy.set(e,r=new KN);let o=r.elts[r.i]=Ri.resolve(e,n);return r.i=(r.i+1)%YN,o}}class KN{constructor(){this.elts=[],this.i=0}}const YN=12,Qy=new WeakMap;class Sl{constructor(e,n,r){this.$from=e,this.$to=n,this.depth=r}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const qN=Object.create(null);let Mr=class ah{constructor(e,n,r,o=Ne.none){this.type=e,this.attrs=n,this.marks=o,this.content=r||D.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,n,r,o=0){this.content.nodesBetween(e,n,r,o,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,n,r,o){return this.content.textBetween(e,n,r,o)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,n,r){return this.type==e&&kl(this.attrs,n||e.defaultAttrs||qN)&&Ne.sameSet(this.marks,r||Ne.none)}copy(e=null){return e==this.content?this:new ah(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new ah(this.type,this.attrs,this.content,e)}cut(e,n=this.content.size){return e==0&&n==this.content.size?this:this.copy(this.content.cut(e,n))}slice(e,n=this.content.size,r=!1){if(e==n)return Z.empty;let o=this.resolve(e),s=this.resolve(n),i=r?0:o.sharedDepth(n),a=o.start(i),c=o.node(i).content.cut(o.pos-a,s.pos-a);return new Z(c,o.depth-i,s.depth-i)}replace(e,n,r){return jN(this.resolve(e),this.resolve(n),r)}nodeAt(e){for(let n=this;;){let{index:r,offset:o}=n.content.findIndex(e);if(n=n.maybeChild(r),!n)return null;if(o==e||n.isText)return n;e-=o+1}}childAfter(e){let{index:n,offset:r}=this.content.findIndex(e);return{node:this.content.maybeChild(n),index:n,offset:r}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:n,offset:r}=this.content.findIndex(e);if(r<e)return{node:this.content.child(n),index:n,offset:r};let o=this.content.child(n-1);return{node:o,index:n-1,offset:r-o.nodeSize}}resolve(e){return Ri.resolveCached(this,e)}resolveNoCache(e){return Ri.resolve(this,e)}rangeHasMark(e,n,r){let o=!1;return n>e&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(o=!0),!o)),o}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()+")"),e0(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=D.empty,o=0,s=r.childCount){let i=this.contentMatchAt(e).matchFragment(r,o,s),a=i&&i.matchFragment(this.content,n);if(!a||!a.validEnd)return!1;for(let l=o;l<s;l++)if(!this.type.allowsMarks(r.child(l).marks))return!1;return!0}canReplaceWith(e,n,r,o){if(o&&!this.type.allowsMarks(o))return!1;let s=this.contentMatchAt(e).matchType(r),i=s&&s.matchFragment(this.content,n);return i?i.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=Ne.none;for(let n=0;n<this.marks.length;n++){let r=this.marks[n];r.type.checkAttrs(r.attrs),e=r.addToSet(e)}if(!Ne.sameSet(e,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(n=>n.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n 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(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let o=D.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,o,r);return s.type.checkAttrs(s.attrs),s}};Mr.prototype.text=void 0;class El extends Mr{constructor(e,n,r,o){if(super(e,n,null,o),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):e0(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new El(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new El(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function e0(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Fo{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new XN(e,n);if(r.next==null)return Fo.empty;let o=t0(r);r.next&&r.err("Unexpected trailing text");let s=rP(nP(o));return oP(s,r),s}matchType(e){for(let n=0;n<this.next.length;n++)if(this.next[n].type==e)return this.next[n].next;return null}matchFragment(e,n=0,r=e.childCount){let o=this;for(let s=n;o&&s<r;s++)o=o.matchType(e.child(s).type);return o}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:n}=this.next[e];if(!(n.isText||n.hasRequiredAttrs()))return n}return null}compatible(e){for(let n=0;n<this.next.length;n++)for(let r=0;r<e.next.length;r++)if(this.next[n].type==e.next[r].type)return!0;return!1}fillBefore(e,n=!1,r=0){let o=[this];function s(i,a){let l=i.matchFragment(e,r);if(l&&(!n||l.validEnd))return D.from(a.map(c=>c.createAndFill()));for(let c=0;c<i.next.length;c++){let{type:u,next:f}=i.next[c];if(!(u.isText||u.hasRequiredAttrs())&&o.indexOf(f)==-1){o.push(f);let h=s(f,a.concat(u));if(h)return h}}return null}return s(this,[])}findWrapping(e){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==e)return this.wrapCache[r+1];let n=this.computeWrapping(e);return this.wrapCache.push(e,n),n}computeWrapping(e){let n=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let o=r.shift(),s=o.match;if(s.matchType(e)){let i=[];for(let a=o;a.type;a=a.via)i.push(a.type);return i.reverse()}for(let i=0;i<s.next.length;i++){let{type:a,next:l}=s.next[i];!a.isLeaf&&!a.hasRequiredAttrs()&&!(a.name in n)&&(!o.type||l.validEnd)&&(r.push({match:a.contentMatch,type:a,via:o}),n[a.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let o=0;o<r.next.length;o++)e.indexOf(r.next[o].next)==-1&&n(r.next[o].next)}return n(this),e.map((r,o)=>{let s=o+(r.validEnd?"*":" ")+" ";for(let i=0;i<r.next.length;i++)s+=(i?", ":"")+r.next[i].type.name+"->"+e.indexOf(r.next[i].next);return s}).join(`
70
+ `)}}Fo.empty=new Fo(!0);class XN{constructor(e,n){this.string=e,this.nodeTypes=n,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 t0(t){let e=[];do e.push(GN(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function GN(t){let e=[];do e.push(JN(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function JN(t){let e=tP(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=QN(t,e);else break;return e}function n0(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function QN(t,e){let n=n0(t),r=n;return t.eat(",")&&(t.next!="}"?r=n0(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function eP(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let o=[];for(let s in n){let i=n[s];i.isInGroup(e)&&o.push(i)}return o.length==0&&t.err("No node type or group '"+e+"' found"),o}function tP(t){if(t.eat("(")){let e=t0(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=eP(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function nP(t){let e=[[]];return o(s(t,0),n()),e;function n(){return e.push([])-1}function r(i,a,l){let c={term:l,to:a};return e[i].push(c),c}function o(i,a){i.forEach(l=>l.to=a)}function s(i,a){if(i.type=="choice")return i.exprs.reduce((l,c)=>l.concat(s(c,a)),[]);if(i.type=="seq")for(let l=0;;l++){let c=s(i.exprs[l],a);if(l==i.exprs.length-1)return c;o(c,a=n())}else if(i.type=="star"){let l=n();return r(a,l),o(s(i.expr,l),l),[r(l)]}else if(i.type=="plus"){let l=n();return o(s(i.expr,a),l),o(s(i.expr,l),l),[r(l)]}else{if(i.type=="opt")return[r(a)].concat(s(i.expr,a));if(i.type=="range"){let l=a;for(let c=0;c<i.min;c++){let u=n();o(s(i.expr,l),u),l=u}if(i.max==-1)o(s(i.expr,l),l);else for(let c=i.min;c<i.max;c++){let u=n();r(l,u),o(s(i.expr,l),u),l=u}return[r(l)]}else{if(i.type=="name")return[r(a,void 0,i.value)];throw new Error("Unknown expr type")}}}}function r0(t,e){return e-t}function o0(t,e){let n=[];return r(e),n.sort(r0);function r(o){let s=t[o];if(s.length==1&&!s[0].term)return r(s[0].to);n.push(o);for(let i=0;i<s.length;i++){let{term:a,to:l}=s[i];!a&&n.indexOf(l)==-1&&r(l)}}}function rP(t){let e=Object.create(null);return n(o0(t,0));function n(r){let o=[];r.forEach(i=>{t[i].forEach(({term:a,to:l})=>{if(!a)return;let c;for(let u=0;u<o.length;u++)o[u][0]==a&&(c=o[u][1]);o0(t,l).forEach(u=>{c||o.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new Fo(r.indexOf(t.length-1)>-1);for(let i=0;i<o.length;i++){let a=o[i][1].sort(r0);s.next.push({type:o[i][0],next:e[a.join(",")]||n(a)})}return s}}function oP(t,e){for(let n=0,r=[t];n<r.length;n++){let o=r[n],s=!o.validEnd,i=[];for(let a=0;a<o.next.length;a++){let{type:l,next:c}=o.next[a];i.push(l.name),s&&!(l.isText||l.hasRequiredAttrs())&&(s=!1),r.indexOf(c)==-1&&r.push(c)}s&&e.err("Only non-generatable nodes ("+i.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function s0(t){let e=Object.create(null);for(let n in t){let r=t[n];if(!r.hasDefault)return null;e[n]=r.default}return e}function i0(t,e){let n=Object.create(null);for(let r in t){let o=e&&e[r];if(o===void 0){let s=t[r];if(s.hasDefault)o=s.default;else throw new RangeError("No value supplied for attribute "+r)}n[r]=o}return n}function a0(t,e,n,r){for(let o in e)if(!(o in t))throw new RangeError(`Unsupported attribute ${o} for ${n} of type ${o}`);for(let o in t){let s=t[o];s.validate&&s.validate(e[o])}}function l0(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new iP(t,r,e[r]);return n}let c0=class Rv{constructor(e,n,r){this.name=e,this.schema=n,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=l0(e,r.attrs),this.defaultAttrs=s0(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==Fo.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-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:i0(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Mr(this,this.computeAttrs(e),D.from(n),Ne.setFrom(r))}createChecked(e=null,n,r){return n=D.from(n),this.checkContent(n),new Mr(this,this.computeAttrs(e),n,Ne.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=D.from(n),n.size){let i=this.contentMatch.fillBefore(n);if(!i)return null;n=i.append(n)}let o=this.contentMatch.matchFragment(n),s=o&&o.fillBefore(D.empty,!0);return s?new Mr(this,e,n.append(s),Ne.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r<e.childCount;r++)if(!this.allowsMarks(e.child(r).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){a0(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;n<e.length;n++)if(!this.allowsMarkType(e[n].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let n;for(let r=0;r<e.length;r++)this.allowsMarkType(e[r].type)?n&&n.push(e[r]):n||(n=e.slice(0,r));return n?n.length?n:Ne.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,i)=>r[s]=new Rv(s,n,i));let o=n.spec.topNode||"doc";if(!r[o])throw new RangeError("Schema is missing its top node type ('"+o+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function sP(t,e,n){let r=n.split("|");return o=>{let s=o===null?"null":typeof o;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class iP{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?sP(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Cl{constructor(e,n,r,o){this.name=e,this.rank=n,this.schema=r,this.spec=o,this.attrs=l0(e,o.attrs),this.excluded=null;let s=s0(this.attrs);this.instance=s?new Ne(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Ne(this,i0(this.attrs,e))}static compile(e,n){let r=Object.create(null),o=0;return e.forEach((s,i)=>r[s]=new Cl(s,o++,n,i)),r}removeFromSet(e){for(var n=0;n<e.length;n++)e[n].type==this&&(e=e.slice(0,n).concat(e.slice(n+1)),n--);return e}isInSet(e){for(let n=0;n<e.length;n++)if(e[n].type==this)return e[n]}checkAttrs(e){a0(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class u0{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let o in e)n[o]=e[o];n.nodes=At.from(e.nodes),n.marks=At.from(e.marks||{}),this.nodes=c0.compile(this.spec.nodes,this),this.marks=Cl.compile(this.spec.marks,this);let r=Object.create(null);for(let o in this.nodes){if(o in this.marks)throw new RangeError(o+" can not be both a node and a mark");let s=this.nodes[o],i=s.spec.content||"",a=s.spec.marks;if(s.contentMatch=r[i]||(r[i]=Fo.parse(i,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=a=="_"?null:a?d0(this,a.split(" ")):a==""||!s.inlineContent?[]:null}for(let o in this.marks){let s=this.marks[o],i=s.spec.excludes;s.excluded=i==null?[s]:i==""?[]:d0(this,i.split(" "))}this.nodeFromJSON=o=>Mr.fromJSON(this,o),this.markFromJSON=o=>Ne.fromJSON(this,o),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,o){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof c0){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(n,r,o)}text(e,n){let r=this.nodes.text;return new El(r,r.defaultAttrs,e,Ne.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function d0(t,e){let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t.marks[o],i=s;if(s)n.push(s);else for(let a in t.marks){let l=t.marks[a];(o=="_"||l.spec.group&&l.spec.group.split(" ").indexOf(o)>-1)&&n.push(i=l)}if(!i)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function aP(t){return t.tag!=null}function lP(t){return t.style!=null}class Ar{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(o=>{if(aP(o))this.tags.push(o);else if(lP(o)){let s=/[^=]*/.exec(o.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(o)}}),this.normalizeLists=!this.tags.some(o=>{if(!/^(ul|ol)\b/.test(o.tag)||!o.node)return!1;let s=e.nodes[o.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new m0(this,n,!1);return r.addAll(e,Ne.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new m0(this,n,!0);return r.addAll(e,Ne.none,n.from,n.to),Z.maxOpen(r.finish())}matchTag(e,n,r){for(let o=r?this.tags.indexOf(r)+1:0;o<this.tags.length;o++){let s=this.tags[o];if(dP(e,s.tag)&&(s.namespace===void 0||e.namespaceURI==s.namespace)&&(!s.context||n.matchesContext(s.context))){if(s.getAttrs){let i=s.getAttrs(e);if(i===!1)continue;s.attrs=i||void 0}return s}}}matchStyle(e,n,r,o){for(let s=o?this.styles.indexOf(o)+1:0;s<this.styles.length;s++){let i=this.styles[s],a=i.style;if(!(a.indexOf(e)!=0||i.context&&!r.matchesContext(i.context)||a.length>e.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=n))){if(i.getAttrs){let l=i.getAttrs(n);if(l===!1)continue;i.attrs=l||void 0}return i}}}static schemaRules(e){let n=[];function r(o){let s=o.priority==null?50:o.priority,i=0;for(;i<n.length;i++){let a=n[i];if((a.priority==null?50:a.priority)<s)break}n.splice(i,0,o)}for(let o in e.marks){let s=e.marks[o].spec.parseDOM;s&&s.forEach(i=>{r(i=g0(i)),i.mark||i.ignore||i.clearMark||(i.mark=o)})}for(let o in e.nodes){let s=e.nodes[o].spec.parseDOM;s&&s.forEach(i=>{r(i=g0(i)),i.node||i.ignore||i.mark||(i.node=o)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Ar(e,Ar.schemaRules(e)))}}const f0={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},cP={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},h0={ol:!0,ul:!0},zi=1,vd=2,$i=4;function p0(t,e,n){return e!=null?(e?zi:0)|(e==="full"?vd:0):t&&t.whitespace=="pre"?zi|vd:n&~$i}class xl{constructor(e,n,r,o,s,i){this.type=e,this.attrs=n,this.marks=r,this.solid=o,this.options=i,this.content=[],this.activeMarks=Ne.none,this.match=s||(i&$i?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(D.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,o;return(o=r.findWrapping(e.type))?(this.match=r,o):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&zi)){let r=this.content[this.content.length-1],o;if(r&&r.isText&&(o=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==o[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-o[0].length))}}let n=D.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(D.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!f0.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class m0{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let o=n.topNode,s,i=p0(null,n.preserveWhitespace,0)|(r?$i:0);o?s=new xl(o.type,o.attrs,Ne.none,!0,n.topMatch||o.type.contentMatch,i):r?s=new xl(null,null,Ne.none,!0,null,i):s=new xl(e.schema.topNodeType,null,Ne.none,!0,null,i),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,o=this.top,s=o.options&vd?"full":this.localPreserveWS||(o.options&zi)>0,{schema:i}=this.parser;if(s==="full"||o.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,`
71
+ `);else if(i.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(i.linebreakReplacement.create())){let a=r.split(/\r?\n|\r/);for(let l=0;l<a.length;l++)l&&this.insertNode(i.linebreakReplacement.create(),n,!0),a[l]&&this.insertNode(i.text(a[l]),n,!/\S/.test(a[l]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let a=o.content[o.content.length-1],l=e.previousSibling;(!a||l&&l.nodeName=="BR"||a.isText&&/[ \t\r\n\u000c]$/.test(a.text))&&(r=r.slice(1))}r&&this.insertNode(i.text(r),n,!/\S/.test(r)),this.findInText(e)}else this.findInside(e)}addElement(e,n,r){let o=this.localPreserveWS,s=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let i=e.nodeName.toLowerCase(),a;h0.hasOwnProperty(i)&&this.parser.normalizeLists&&uP(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:cP.hasOwnProperty(i))this.findInside(e),this.ignoreFallback(e,n);else if(!l||l.skip||l.closeParent){l&&l.closeParent?this.open=Math.max(0,this.open-1):l&&l.skip.nodeType&&(e=l.skip);let c,u=this.needsBlock;if(f0.hasOwnProperty(i))s.content.length&&s.content[0].isInline&&this.open&&(this.open--,s=this.top),c=!0,s.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,n);break e}let f=l&&l.skip?n:this.readStyles(e,n);f&&this.addAll(e,f),c&&this.sync(s),this.needsBlock=u}else{let c=this.readStyles(e,n);c&&this.addElementByRule(e,l,c,l.consuming===!1?a:void 0)}this.localPreserveWS=o}leafFallback(e,n){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
72
+ `),n)}ignoreFallback(e,n){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),n,!0)}readStyles(e,n){let r=e.style;if(r&&r.length)for(let o=0;o<this.parser.matchedStyles.length;o++){let s=this.parser.matchedStyles[o],i=r.getPropertyValue(s);if(i)for(let a=void 0;;){let l=this.parser.matchStyle(s,i,this,a);if(!l)break;if(l.ignore)return null;if(l.clearMark?n=n.filter(c=>!l.clearMark(c)):n=n.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)a=l;else break}}return n}addElementByRule(e,n,r,o){let s,i;if(n.node)if(i=this.parser.schema.nodes[n.node],i.isLeaf)this.insertNode(i.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let l=this.enter(i,n.attrs||null,r,n.preserveWhitespace);l&&(s=!0,r=l)}else{let l=this.parser.schema.marks[n.mark];r=r.concat(l.create(n.attrs))}let a=this.top;if(i&&i.isLeaf)this.findInside(e);else if(o)this.addElement(e,r,o);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=e;typeof n.contentElement=="string"?l=e.querySelector(n.contentElement):typeof n.contentElement=="function"?l=n.contentElement(e):n.contentElement&&(l=n.contentElement),this.findAround(e,l,!0),this.addAll(l,r),this.findAround(e,l,!1)}s&&this.sync(a)&&this.open--}addAll(e,n,r,o){let s=r||0;for(let i=r?e.childNodes[r]:e.firstChild,a=o==null?null:e.childNodes[o];i!=a;i=i.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(i,n);this.findAtPoint(e,s)}findPlace(e,n,r){let o,s;for(let i=this.open,a=0;i>=0;i--){let l=this.nodes[i],c=l.findWrapping(e);if(c&&(!o||o.length>c.length+a)&&(o=c,s=l,!c.length))break;if(l.solid){if(r)break;a+=2}}if(!o)return null;this.sync(s);for(let i=0;i<o.length;i++)n=this.enterInner(o[i],null,n,!1);return n}insertNode(e,n,r){if(e.isInline&&this.needsBlock&&!this.top.type){let s=this.textblockFromContext();s&&(n=this.enterInner(s,null,n))}let o=this.findPlace(e,n,r);if(o){this.closeExtra();let s=this.top;s.match&&(s.match=s.match.matchType(e.type));let i=Ne.none;for(let a of o.concat(e.marks))(s.type?s.type.allowsMarkType(a.type):y0(a.type,e.type))&&(i=a.addToSet(i));return s.content.push(e.mark(i)),!0}return!1}enter(e,n,r,o){let s=this.findPlace(e.create(n),r,!1);return s&&(s=this.enterInner(e,n,r,!0,o)),s}enterInner(e,n,r,o=!1,s){this.closeExtra();let i=this.top;i.match=i.match&&i.match.matchType(e);let a=p0(e,s,i.options);i.options&$i&&i.content.length==0&&(a|=$i);let l=Ne.none;return r=r.filter(c=>(i.type?i.type.allowsMarkType(c.type):y0(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new xl(e,n,l,o,null,a)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].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 n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=zi)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let o=r.length-1;o>=0;o--)e+=r[o].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==e&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&e.nodeType==1&&e.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(e,n,r){if(e!=n&&this.find)for(let o=0;o<this.find.length;o++)this.find[o].pos==null&&e.nodeType==1&&e.contains(this.find[o].node)&&n.compareDocumentPosition(this.find[o].node)&(r?2:4)&&(this.find[o].pos=this.currentPos)}findInText(e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==e&&(this.find[n].pos=this.currentPos-(e.nodeValue.length-this.find[n].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,o=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(o?0:1),i=(a,l)=>{for(;a>=0;a--){let c=n[a];if(c==""){if(a==n.length-1||a==0)continue;for(;l>=s;l--)if(i(a-1,l))return!0;return!1}else{let u=l>0||l==0&&o?this.nodes[l].type:r&&l>=s?r.node(l-s).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;l--}}return!0};return i(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function uP(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&h0.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function dP(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function g0(t){let e={};for(let n in t)e[n]=t[n];return e}function y0(t,e){let n=e.schema.nodes;for(let r in n){let o=n[r];if(!o.allowsMarkType(t))continue;let s=[],i=a=>{s.push(a);for(let l=0;l<a.edgeCount;l++){let{type:c,next:u}=a.edge(l);if(c==e||s.indexOf(u)<0&&i(u))return!0}};if(i(o.contentMatch))return!0}}class Wo{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=bd(n).createDocumentFragment());let o=r,s=[];return e.forEach(i=>{if(s.length||i.marks.length){let a=0,l=0;for(;a<s.length&&l<i.marks.length;){let c=i.marks[l];if(!this.marks[c.type.name]){l++;continue}if(!c.eq(s[a][0])||c.type.spec.spanning===!1)break;a++,l++}for(;a<s.length;)o=s.pop()[1];for(;l<i.marks.length;){let c=i.marks[l++],u=this.serializeMark(c,i.isInline,n);u&&(s.push([c,o]),o.appendChild(u.dom),o=u.contentDOM||u.dom)}}o.appendChild(this.serializeNodeInner(i,n))}),r}serializeNodeInner(e,n){let{dom:r,contentDOM:o}=Tl(bd(n),this.nodes[e.type.name](e),null,e.attrs);if(o){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,n,o)}return r}serializeNode(e,n={}){let r=this.serializeNodeInner(e,n);for(let o=e.marks.length-1;o>=0;o--){let s=this.serializeMark(e.marks[o],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let o=this.marks[e.type.name];return o&&Tl(bd(r),o(e,n),null,e.attrs)}static renderSpec(e,n,r=null,o){return Tl(e,n,r,o)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Wo(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=w0(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return w0(e.marks)}}function w0(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function bd(t){return t.document||window.document}const k0=new WeakMap;function fP(t){let e=k0.get(t);return e===void 0&&k0.set(t,e=hP(t)),e}function hP(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let o=0;o<r.length;o++)n(r[o]);else for(let o in r)n(r[o])}return n(t),e}function Tl(t,e,n,r){if(typeof e=="string")return{dom:t.createTextNode(e)};if(e.nodeType!=null)return{dom:e};if(e.dom&&e.dom.nodeType!=null)return e;let o=e[0],s;if(typeof o!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(s=fP(r))&&s.indexOf(e)>-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 i=o.indexOf(" ");i>0&&(n=o.slice(0,i),o=o.slice(i+1));let a,l=n?t.createElementNS(n,o):t.createElement(o),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let f in c)if(c[f]!=null){let h=f.indexOf(" ");h>0?l.setAttributeNS(f.slice(0,h),f.slice(h+1),c[f]):f=="style"&&l.style?l.style.cssText=c[f]:l.setAttribute(f,c[f])}}for(let f=u;f<e.length;f++){let h=e[f];if(h===0){if(f<e.length-1||f>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:l,contentDOM:l}}else{let{dom:p,contentDOM:m}=Tl(t,h,n,r);if(l.appendChild(p),m){if(a)throw new RangeError("Multiple content holes");a=m}}}return{dom:l,contentDOM:a}}const v0=65535,b0=Math.pow(2,16);function pP(t,e){return t+e*b0}function S0(t){return t&v0}function mP(t){return(t-(t&v0))/b0}const E0=1,C0=2,Ml=4,x0=8;class Sd{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&x0)>0}get deletedBefore(){return(this.delInfo&(E0|Ml))>0}get deletedAfter(){return(this.delInfo&(C0|Ml))>0}get deletedAcross(){return(this.delInfo&Ml)>0}}class dn{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&dn.empty)return dn.empty}recover(e){let n=0,r=S0(e);if(!this.inverted)for(let o=0;o<r;o++)n+=this.ranges[o*3+2]-this.ranges[o*3+1];return this.ranges[r*3]+n+mP(e)}mapResult(e,n=1){return this._map(e,n,!1)}map(e,n=1){return this._map(e,n,!0)}_map(e,n,r){let o=0,s=this.inverted?2:1,i=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?o:0);if(l>e)break;let c=this.ranges[a+s],u=this.ranges[a+i],f=l+c;if(e<=f){let h=c?e==l?-1:e==f?1:n:n,p=l+o+(h<0?0:u);if(r)return p;let m=e==(n<0?l:f)?null:pP(a/3,e-l),g=e==l?C0:e==f?E0:Ml;return(n<0?e!=l:e!=f)&&(g|=x0),new Sd(p,g,m)}o+=u-c}return r?e+o:new Sd(e+o,0,null)}touches(e,n){let r=0,o=S0(n),s=this.inverted?2:1,i=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?r:0);if(l>e)break;let c=this.ranges[a+s],u=l+c;if(e<=u&&a==o*3)return!0;r+=this.ranges[a+i]-c}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let o=0,s=0;o<this.ranges.length;o+=3){let i=this.ranges[o],a=i-(this.inverted?s:0),l=i+(this.inverted?0:s),c=this.ranges[o+n],u=this.ranges[o+r];e(a,a+c,l,l+u),s+=u-c}}invert(){return new dn(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?dn.empty:new dn(e<0?[0,-e,0]:[0,0,e])}}dn.empty=new dn([]);class Li{constructor(e,n,r=0,o=e?e.length:0){this.mirror=n,this.from=r,this.to=o,this._maps=e||[],this.ownData=!(e||n)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new Li(this._maps,this.mirror,e,n)}appendMap(e,n){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),n!=null&&this.setMirror(this._maps.length-1,n)}appendMapping(e){for(let n=0,r=this._maps.length;n<e._maps.length;n++){let o=e.getMirror(n);this.appendMap(e._maps[n],o!=null&&o<n?r+o:void 0)}}getMirror(e){if(this.mirror){for(let n=0;n<this.mirror.length;n++)if(this.mirror[n]==e)return this.mirror[n+(n%2?-1:1)]}}setMirror(e,n){this.mirror||(this.mirror=[]),this.mirror.push(e,n)}appendMappingInverted(e){for(let n=e.maps.length-1,r=this._maps.length+e._maps.length;n>=0;n--){let o=e.getMirror(n);this.appendMap(e._maps[n].invert(),o!=null&&o>n?r-o-1:void 0)}}invert(){let e=new Li;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;r<this.to;r++)e=this._maps[r].map(e,n);return e}mapResult(e,n=1){return this._map(e,n,!1)}_map(e,n,r){let o=0;for(let s=this.from;s<this.to;s++){let i=this._maps[s],a=i.mapResult(e,n);if(a.recover!=null){let l=this.getMirror(s);if(l!=null&&l>s&&l<this.to){s=l,e=this._maps[l].recover(a.recover);continue}}o|=a.delInfo,e=a.pos}return r?e:new Sd(e,o,null)}}const Ed=Object.create(null);class Rt{getMap(){return dn.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Ed[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in Ed)throw new RangeError("Duplicate use of step JSON ID "+e);return Ed[e]=n,n.prototype.jsonID=e,n}}class nt{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new nt(e,null)}static fail(e){return new nt(null,e)}static fromReplace(e,n,r,o){try{return nt.ok(e.replace(n,r,o))}catch(s){if(s instanceof vl)return nt.fail(s.message);throw s}}}function Cd(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let s=t.child(o);s.content.size&&(s=s.copy(Cd(s.content,e,s))),s.isInline&&(s=e(s,n,o)),r.push(s)}return D.fromArray(r)}class ro extends Rt{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=e.resolve(this.from),o=r.node(r.sharedDepth(this.to)),s=new Z(Cd(n.content,(i,a)=>!i.isAtom||!a.type.allowsMarkType(this.mark.type)?i:i.mark(this.mark.addToSet(i.marks)),o),n.openStart,n.openEnd);return nt.fromReplace(e,this.from,this.to,s)}invert(){return new Un(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new ro(n.pos,r.pos,this.mark)}merge(e){return e instanceof ro&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ro(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,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new ro(n.from,n.to,e.markFromJSON(n.mark))}}Rt.jsonID("addMark",ro);class Un extends Rt{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new Z(Cd(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),e),n.openStart,n.openEnd);return nt.fromReplace(e,this.from,this.to,r)}invert(){return new ro(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Un(n.pos,r.pos,this.mark)}merge(e){return e instanceof Un&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Un(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,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Un(n.from,n.to,e.markFromJSON(n.mark))}}Rt.jsonID("removeMark",Un);class oo extends Rt{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return nt.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return nt.fromReplace(e,this.pos,this.pos+1,new Z(D.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let o=0;o<n.marks.length;o++)if(!n.marks[o].isInSet(r))return new oo(this.pos,n.marks[o]);return new oo(this.pos,this.mark)}}return new Uo(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new oo(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new oo(n.pos,e.markFromJSON(n.mark))}}Rt.jsonID("addNodeMark",oo);class Uo extends Rt{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return nt.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return nt.fromReplace(e,this.pos,this.pos+1,new Z(D.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new oo(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Uo(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new Uo(n.pos,e.markFromJSON(n.mark))}}Rt.jsonID("removeNodeMark",Uo);class gt extends Rt{constructor(e,n,r,o=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=o}apply(e){return this.structure&&xd(e,this.from,this.to)?nt.fail("Structure replace would overwrite content"):nt.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new dn([this.from,this.to-this.from,this.slice.size])}invert(e){return new gt(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new gt(n.pos,Math.max(n.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof gt)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let n=this.slice.size+e.slice.size==0?Z.empty:new Z(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new gt(this.from,this.to+(e.to-e.from),n,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let n=this.slice.size+e.slice.size==0?Z.empty:new Z(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new gt(e.from,this.to,n,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new gt(n.from,n.to,Z.fromJSON(e,n.slice),!!n.structure)}}Rt.jsonID("replace",gt);class yt extends Rt{constructor(e,n,r,o,s,i,a=!1){super(),this.from=e,this.to=n,this.gapFrom=r,this.gapTo=o,this.slice=s,this.insert=i,this.structure=a}apply(e){if(this.structure&&(xd(e,this.from,this.gapFrom)||xd(e,this.gapTo,this.to)))return nt.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return nt.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?nt.fromReplace(e,this.from,this.to,r):nt.fail("Content does not fit in gap")}getMap(){return new dn([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new yt(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),o=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),s=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||o<n.pos||s>r.pos?null:new yt(n.pos,r.pos,o,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,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new yt(n.from,n.to,n.gapFrom,n.gapTo,Z.fromJSON(e,n.slice),n.insert,!!n.structure)}}Rt.jsonID("replaceAround",yt);function xd(t,e,n){let r=t.resolve(e),o=n-e,s=r.depth;for(;o>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,o--;if(o>0){let i=r.node(s).maybeChild(r.indexAfter(s));for(;o>0;){if(!i||i.isLeaf)return!0;i=i.firstChild,o--}}return!1}function gP(t,e,n,r){let o=[],s=[],i,a;t.doc.nodesBetween(e,n,(l,c,u)=>{if(!l.isInline)return;let f=l.marks;if(!r.isInSet(f)&&u.type.allowsMarkType(r.type)){let h=Math.max(c,e),p=Math.min(c+l.nodeSize,n),m=r.addToSet(f);for(let g=0;g<f.length;g++)f[g].isInSet(m)||(i&&i.to==h&&i.mark.eq(f[g])?i.to=p:o.push(i=new Un(h,p,f[g])));a&&a.to==h?a.to=p:s.push(a=new ro(h,p,r))}}),o.forEach(l=>t.step(l)),s.forEach(l=>t.step(l))}function yP(t,e,n,r){let o=[],s=0;t.doc.nodesBetween(e,n,(i,a)=>{if(!i.isInline)return;s++;let l=null;if(r instanceof Cl){let c=i.marks,u;for(;u=r.isInSet(c);)(l||(l=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(i.marks)&&(l=[r]):l=i.marks;if(l&&l.length){let c=Math.min(a+i.nodeSize,n);for(let u=0;u<l.length;u++){let f=l[u],h;for(let p=0;p<o.length;p++){let m=o[p];m.step==s-1&&f.eq(o[p].style)&&(h=m)}h?(h.to=c,h.step=s):o.push({style:f,from:Math.max(a,e),to:c,step:s})}}}),o.forEach(i=>t.step(new Un(i.from,i.to,i.style)))}function Td(t,e,n,r=n.contentMatch,o=!0){let s=t.doc.nodeAt(e),i=[],a=e+1;for(let l=0;l<s.childCount;l++){let c=s.child(l),u=a+c.nodeSize,f=r.matchType(c.type);if(!f)i.push(new gt(a,u,Z.empty));else{r=f;for(let h=0;h<c.marks.length;h++)n.allowsMarkType(c.marks[h].type)||t.step(new Un(a,u,c.marks[h]));if(o&&c.isText&&n.whitespace!="pre"){let h,p=/\r?\n|\r/g,m;for(;h=p.exec(c.text);)m||(m=new Z(D.from(n.schema.text(" ",n.allowedMarks(c.marks))),0,0)),i.push(new gt(a+h.index,a+h.index+h[0].length,m))}}a=u}if(!r.validEnd){let l=r.fillBefore(D.empty,!0);t.replace(a,a,new Z(l,0,0))}for(let l=i.length-1;l>=0;l--)t.step(i[l])}function wP(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Vs(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,o=0,s=0;;--r){let i=t.$from.node(r),a=t.$from.index(r)+o,l=t.$to.indexAfter(r)-s;if(r<t.depth&&i.canReplace(a,l,n))return r;if(r==0||i.type.spec.isolating||!wP(i,a,l))break;a&&(o=1),l<i.childCount&&(s=1)}return null}function kP(t,e,n){let{$from:r,$to:o,depth:s}=e,i=r.before(s+1),a=o.after(s+1),l=i,c=a,u=D.empty,f=0;for(let m=s,g=!1;m>n;m--)g||r.index(m)>0?(g=!0,u=D.from(r.node(m).copy(u)),f++):l--;let h=D.empty,p=0;for(let m=s,g=!1;m>n;m--)g||o.after(m+1)<o.end(m)?(g=!0,h=D.from(o.node(m).copy(h)),p++):c++;t.step(new yt(l,c,i,a,new Z(u.append(h),f,p),u.size-f,!0))}function T0(t,e,n=null,r=t){let o=vP(t,e),s=o&&bP(r,e);return s?o.map(M0).concat({type:e,attrs:n}).concat(s.map(M0)):null}function M0(t){return{type:t,attrs:null}}function vP(t,e){let{parent:n,startIndex:r,endIndex:o}=t,s=n.contentMatchAt(r).findWrapping(e);if(!s)return null;let i=s.length?s[0]:e;return n.canReplaceWith(r,o,i)?s:null}function bP(t,e){let{parent:n,startIndex:r,endIndex:o}=t,s=n.child(r),i=e.contentMatch.findWrapping(s.type);if(!i)return null;let l=(i.length?i[i.length-1]:e).contentMatch;for(let c=r;l&&c<o;c++)l=l.matchType(n.child(c).type);return!l||!l.validEnd?null:i}function SP(t,e,n){let r=D.empty;for(let i=n.length-1;i>=0;i--){if(r.size){let a=n[i].type.contentMatch.matchFragment(r);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=D.from(n[i].type.create(n[i].attrs,r))}let o=e.start,s=e.end;t.step(new yt(o,s,o,s,new Z(r,0,0),n.length,!0))}function EP(t,e,n,r,o){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(i,a)=>{let l=typeof o=="function"?o(i):o;if(i.isTextblock&&!i.hasMarkup(r,l)&&CP(t.doc,t.mapping.slice(s).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",m=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!m?c=!1:!p&&m&&(c=!0)}c===!1&&_0(t,i,a,s),Td(t,t.mapping.slice(s).map(a,1),r,void 0,c===null);let u=t.mapping.slice(s),f=u.map(a,1),h=u.map(a+i.nodeSize,1);return t.step(new yt(f,h,f+1,h-1,new Z(D.from(r.create(l,null,i.marks)),0,0),1,!0)),c===!0&&A0(t,i,a,s),!1}})}function A0(t,e,n,r){e.forEach((o,s)=>{if(o.isText){let i,a=/\r?\n|\r/g;for(;i=a.exec(o.text);){let l=t.mapping.slice(r).map(n+1+s+i.index);t.replaceWith(l,l+1,e.type.schema.linebreakReplacement.create())}}})}function _0(t,e,n,r){e.forEach((o,s)=>{if(o.type==o.type.schema.linebreakReplacement){let i=t.mapping.slice(r).map(n+1+s);t.replaceWith(i,i+1,e.type.schema.text(`
73
+ `))}})}function CP(t,e,n){let r=t.resolve(e),o=r.index();return r.parent.canReplaceWith(o,o+1,n)}function xP(t,e,n,r,o){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");n||(n=s.type);let i=n.create(r,null,o||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,i);if(!n.validContent(s.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new yt(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new Z(D.from(i),0,0),1,!0))}function _r(t,e,n=1,r){let o=t.resolve(e),s=o.depth-n,i=r&&r[r.length-1]||o.parent;if(s<0||o.parent.type.spec.isolating||!o.parent.canReplace(o.index(),o.parent.childCount)||!i.type.validContent(o.parent.content.cutByIndex(o.index(),o.parent.childCount)))return!1;for(let c=o.depth-1,u=n-2;c>s;c--,u--){let f=o.node(c),h=o.index(c);if(f.type.spec.isolating)return!1;let p=f.content.cutByIndex(h,f.childCount),m=r&&r[u+1];m&&(p=p.replaceChild(0,m.type.create(m.attrs)));let g=r&&r[u]||f;if(!f.canReplace(h+1,f.childCount)||!g.type.validContent(p))return!1}let a=o.indexAfter(s),l=r&&r[0];return o.node(s).canReplaceWith(a,a,l?l.type:o.node(s+1).type)}function TP(t,e,n=1,r){let o=t.doc.resolve(e),s=D.empty,i=D.empty;for(let a=o.depth,l=o.depth-n,c=n-1;a>l;a--,c--){s=D.from(o.node(a).copy(s));let u=r&&r[c];i=D.from(u?u.type.create(u.attrs,i):o.node(a).copy(i))}t.step(new gt(e,e,new Z(s.append(i),n,n),!0))}function Ho(t,e){let n=t.resolve(e),r=n.index();return I0(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function MP(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let o=0;o<e.childCount;o++){let s=e.child(o),i=s.type==r?t.type.schema.nodes.text:s.type;if(n=n.matchType(i),!n||!t.type.allowsMarks(s.marks))return!1}return n.validEnd}function I0(t,e){return!!(t&&e&&!t.isLeaf&&MP(t,e))}function Al(t,e,n=-1){let r=t.resolve(e);for(let o=r.depth;;o--){let s,i,a=r.index(o);if(o==r.depth?(s=r.nodeBefore,i=r.nodeAfter):n>0?(s=r.node(o+1),a++,i=r.node(o).maybeChild(a)):(s=r.node(o).maybeChild(a-1),i=r.node(o+1)),s&&!s.isTextblock&&I0(s,i)&&r.node(o).canReplace(a,a+1))return e;if(o==0)break;e=n<0?r.before(o):r.after(o)}}function AP(t,e,n){let r=null,{linebreakReplacement:o}=t.doc.type.schema,s=t.doc.resolve(e-n),i=s.node().type;if(o&&i.inlineContent){let u=i.whitespace=="pre",f=!!i.contentMatch.matchType(o);u&&!f?r=!1:!u&&f&&(r=!0)}let a=t.steps.length;if(r===!1){let u=t.doc.resolve(e+n);_0(t,u.node(),u.before(),a)}i.inlineContent&&Td(t,e+n-1,i,s.node().contentMatchAt(s.index()),r==null);let l=t.mapping.slice(a),c=l.map(e-n);if(t.step(new gt(c,l.map(e+n,-1),Z.empty,!0)),r===!0){let u=t.doc.resolve(c);A0(t,u.node(),u.before(),t.steps.length)}return t}function _P(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(r.parentOffset==0)for(let o=r.depth-1;o>=0;o--){let s=r.index(o);if(r.node(o).canReplaceWith(s,s,n))return r.before(o+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let o=r.depth-1;o>=0;o--){let s=r.indexAfter(o);if(r.node(o).canReplaceWith(s,s,n))return r.after(o+1);if(s<r.node(o).childCount)return null}return null}function B0(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let o=n.content;for(let s=0;s<n.openStart;s++)o=o.firstChild.content;for(let s=1;s<=(n.openStart==0&&n.size?2:1);s++)for(let i=r.depth;i>=0;i--){let a=i==r.depth?0:r.pos<=(r.start(i+1)+r.end(i+1))/2?-1:1,l=r.index(i)+(a>0?1:0),c=r.node(i),u=!1;if(s==1)u=c.canReplace(l,l,o);else{let f=c.contentMatchAt(l).findWrapping(o.firstChild.type);u=f&&c.canReplaceWith(l,l,f[0])}if(u)return a==0?r.pos:a<0?r.before(i+1):r.after(i+1)}return null}function _l(t,e,n=e,r=Z.empty){if(e==n&&!r.size)return null;let o=t.resolve(e),s=t.resolve(n);return N0(o,s,r)?new gt(e,n,r):new IP(o,s,r).fit()}function N0(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class IP{constructor(e,n,r){this.$from=e,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=D.empty;for(let o=0;o<=e.depth;o++){let s=e.node(o);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(o))})}for(let o=e.depth;o>0;o--)this.placed=D.from(e.node(o).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,o=this.close(e<0?this.$to:r.doc.resolve(e));if(!o)return null;let s=this.placed,i=r.depth,a=o.depth;for(;i&&a&&s.childCount==1;)s=s.firstChild.content,i--,a--;let l=new Z(s,i,a);return e>-1?new yt(r.pos,e,this.$to.pos,this.$to.end(),l,n):l.size||r.pos!=this.$to.pos?new gt(r.pos,o.pos,l):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,o=this.unplaced.openEnd;r<e;r++){let s=n.firstChild;if(n.childCount>1&&(o=0),s.type.spec.isolating&&o<=r){e=r;break}n=s.content}for(let n=1;n<=2;n++)for(let r=n==1?e:this.unplaced.openStart;r>=0;r--){let o,s=null;r?(s=Md(this.unplaced.content,r-1).firstChild,o=s.content):o=this.unplaced.content;let i=o.firstChild;for(let a=this.depth;a>=0;a--){let{type:l,match:c}=this.frontier[a],u,f=null;if(n==1&&(i?c.matchType(i.type)||(f=c.fillBefore(D.from(i),!1)):s&&l.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:a,parent:s,inject:f};if(n==2&&i&&(u=c.findWrapping(i.type)))return{sliceDepth:r,frontierDepth:a,parent:s,wrap:u};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:n,openEnd:r}=this.unplaced,o=Md(e,n);return!o.childCount||o.firstChild.isLeaf?!1:(this.unplaced=new Z(e,n+1,Math.max(r,o.size+n>=e.size-r?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:r}=this.unplaced,o=Md(e,n);if(o.childCount<=1&&n>0){let s=e.size-n<=n+o.size;this.unplaced=new Z(Vi(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new Z(Vi(e,n,1),n,r)}placeNodes({sliceDepth:e,frontierDepth:n,parent:r,inject:o,wrap:s}){for(;this.depth>n;)this.closeFrontierNode();if(s)for(let g=0;g<s.length;g++)this.openFrontierNode(s[g]);let i=this.unplaced,a=r?r.content:i.content,l=i.openStart-e,c=0,u=[],{match:f,type:h}=this.frontier[n];if(o){for(let g=0;g<o.childCount;g++)u.push(o.child(g));f=f.matchFragment(o)}let p=a.size+e-(i.content.size-i.openEnd);for(;c<a.childCount;){let g=a.child(c),y=f.matchType(g.type);if(!y)break;c++,(c>1||l==0||g.content.size)&&(f=y,u.push(P0(g.mark(h.allowedMarks(g.marks)),c==1?l:0,c==a.childCount?p:-1)))}let m=c==a.childCount;m||(p=-1),this.placed=Fi(this.placed,n,D.from(u)),this.frontier[n].match=f,m&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,y=a;g<p;g++){let w=y.lastChild;this.frontier.push({type:w.type,match:w.contentMatchAt(w.childCount)}),y=w.content}this.unplaced=m?e==0?Z.empty:new Z(Vi(i.content,e-1,1),e-1,p<0?i.openEnd:e-1):new Z(Vi(i.content,e,c),i.openStart,i.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],n;if(!e.type.isTextblock||!Ad(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(n=this.findCloseLevel(this.$to))&&n.depth==this.depth)return-1;let{depth:r}=this.$to,o=this.$to.after(r);for(;r>1&&o==this.$to.end(--r);)++o;return o}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:o}=this.frontier[n],s=n<e.depth&&e.end(n+1)==e.pos+(e.depth-(n+1)),i=Ad(e,n,o,r,s);if(i){for(let a=n-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=Ad(e,a,c,l,!0);if(!u||u.childCount)continue e}return{depth:n,fit:i,move:s?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Fi(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let o=e.node(r),s=o.type.contentMatch.fillBefore(o.content,!0,e.index(r));this.openFrontierNode(o.type,o.attrs,s)}return e}openFrontierNode(e,n=null,r){let o=this.frontier[this.depth];o.match=o.match.matchType(e),this.placed=Fi(this.placed,this.depth,D.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(D.empty,!0);n.childCount&&(this.placed=Fi(this.placed,this.frontier.length,n))}}function Vi(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Vi(t.firstChild.content,e-1,n)))}function Fi(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Fi(t.lastChild.content,e-1,n)))}function Md(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function P0(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,P0(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(D.empty,!0)))),t.copy(r)}function Ad(t,e,n,r,o){let s=t.node(e),i=o?t.indexAfter(e):t.index(e);if(i==s.childCount&&!n.compatibleContent(s.type))return null;let a=r.fillBefore(s.content,!0,i);return a&&!BP(n,s.content,i)?a:null}function BP(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function NP(t){return t.spec.defining||t.spec.definingForContent}function PP(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let o=t.doc.resolve(e),s=t.doc.resolve(n);if(N0(o,s,r))return t.step(new gt(e,n,r));let i=O0(o,s);i[i.length-1]==0&&i.pop();let a=-(o.depth+1);i.unshift(a);for(let h=o.depth,p=o.pos-1;h>0;h--,p--){let m=o.node(h).type.spec;if(m.defining||m.definingAsContext||m.isolating)break;i.indexOf(h)>-1?a=h:o.before(h)==p&&i.splice(1,0,-h)}let l=i.indexOf(a),c=[],u=r.openStart;for(let h=r.content,p=0;;p++){let m=h.firstChild;if(c.push(m),p==r.openStart)break;h=m.content}for(let h=u-1;h>=0;h--){let p=c[h],m=NP(p.type);if(m&&!p.sameMarkup(o.node(Math.abs(a)-1)))u=h;else if(m||!p.type.isTextblock)break}for(let h=r.openStart;h>=0;h--){let p=(h+u+1)%(r.openStart+1),m=c[p];if(m)for(let g=0;g<i.length;g++){let y=i[(g+l)%i.length],w=!0;y<0&&(w=!1,y=-y);let k=o.node(y-1),b=o.index(y-1);if(k.canReplaceWith(b,b,m.type,m.marks))return t.replace(o.before(y),w?s.after(y):n,new Z(D0(r.content,0,r.openStart,p),p,r.openEnd))}}let f=t.steps.length;for(let h=i.length-1;h>=0&&(t.replace(e,n,r),!(t.steps.length>f));h--){let p=i[h];p<0||(e=o.before(p),n=s.after(p))}}function D0(t,e,n,r,o){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(D0(s.content,e+1,n,r,s)))}if(e>r){let s=o.contentMatchAt(0),i=s.fillBefore(t).append(t);t=i.append(s.matchFragment(i).fillBefore(D.empty,!0))}return t}function DP(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let o=_P(t.doc,e,r.type);o!=null&&(e=n=o)}t.replaceRange(e,n,new Z(D.from(r),0,0))}function OP(t,e,n){let r=t.doc.resolve(e),o=t.doc.resolve(n),s=O0(r,o);for(let i=0;i<s.length;i++){let a=s[i],l=i==s.length-1;if(l&&a==0||r.node(a).type.contentMatch.validEnd)return t.delete(r.start(a),o.end(a));if(a>0&&(l||r.node(a-1).canReplace(r.index(a-1),o.indexAfter(a-1))))return t.delete(r.before(a),o.after(a))}for(let i=1;i<=r.depth&&i<=o.depth;i++)if(e-r.start(i)==r.depth-i&&n>r.end(i)&&o.end(i)-n!=o.depth-i&&r.start(i-1)==o.start(i-1)&&r.node(i-1).canReplace(r.index(i-1),o.index(i-1)))return t.delete(r.before(i),n);t.delete(e,n)}function O0(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let o=r;o>=0;o--){let s=t.start(o);if(s<t.pos-(t.depth-o)||e.end(o)>e.pos+(e.depth-o)||t.node(o).type.spec.isolating||e.node(o).type.spec.isolating)break;(s==e.start(o)||o==t.depth&&o==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&o&&e.start(o-1)==s-1)&&n.push(o)}return n}class Fs extends Rt{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return nt.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let o=n.type.create(r,null,n.marks);return nt.fromReplace(e,this.pos,this.pos+1,new Z(D.from(o),0,n.isLeaf?0:1))}getMap(){return dn.empty}invert(e){return new Fs(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Fs(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Fs(n.pos,n.attr,n.value)}}Rt.jsonID("attr",Fs);class Wi extends Rt{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let o in e.attrs)n[o]=e.attrs[o];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return nt.ok(r)}getMap(){return dn.empty}invert(e){return new Wi(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Wi(n.attr,n.value)}}Rt.jsonID("docAttr",Wi);let Ws=class extends Error{};Ws=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n},Ws.prototype=Object.create(Error.prototype),Ws.prototype.constructor=Ws,Ws.prototype.name="TransformError";class R0{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new Li}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Ws(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let o=this.mapping.maps[r];r&&(e=o.map(e,1),n=o.map(n,-1)),o.forEach((s,i,a,l)=>{e=Math.min(e,a),n=Math.max(n,l)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=Z.empty){let o=_l(this.doc,e,n,r);return o&&this.step(o),this}replaceWith(e,n,r){return this.replace(e,n,new Z(D.from(r),0,0))}delete(e,n){return this.replace(e,n,Z.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return PP(this,e,n,r),this}replaceRangeWith(e,n,r){return DP(this,e,n,r),this}deleteRange(e,n){return OP(this,e,n),this}lift(e,n){return kP(this,e,n),this}join(e,n=1){return AP(this,e,n),this}wrap(e,n){return SP(this,e,n),this}setBlockType(e,n=e,r,o=null){return EP(this,e,n,r,o),this}setNodeMarkup(e,n,r=null,o){return xP(this,e,n,r,o),this}setNodeAttribute(e,n,r){return this.step(new Fs(e,n,r)),this}setDocAttribute(e,n){return this.step(new Wi(e,n)),this}addNodeMark(e,n){return this.step(new oo(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof Ne)n.isInSet(r.marks)&&this.step(new Uo(e,n));else{let o=r.marks,s,i=[];for(;s=n.isInSet(o);)i.push(new Uo(e,s)),o=s.removeFromSet(o);for(let a=i.length-1;a>=0;a--)this.step(i[a])}return this}split(e,n=1,r){return TP(this,e,n,r),this}addMark(e,n,r){return gP(this,e,n,r),this}removeMark(e,n,r){return yP(this,e,n,r),this}clearIncompatible(e,n,r){return Td(this,e,n,r),this}}const _d=Object.create(null);class fe{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new RP(e.min(n),e.max(n))]}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 n=0;n<e.length;n++)if(e[n].$from.pos!=e[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,n=Z.empty){let r=n.content.lastChild,o=null;for(let a=0;a<n.openEnd;a++)o=r,r=r.lastChild;let s=e.steps.length,i=this.ranges;for(let a=0;a<i.length;a++){let{$from:l,$to:c}=i[a],u=e.mapping.slice(s);e.replaceRange(u.map(l.pos),u.map(c.pos),a?Z.empty:n),a==0&&L0(e,s,(r?r.isInline:o&&o.isTextblock)?-1:1)}}replaceWith(e,n){let r=e.steps.length,o=this.ranges;for(let s=0;s<o.length;s++){let{$from:i,$to:a}=o[s],l=e.mapping.slice(r),c=l.map(i.pos),u=l.map(a.pos);s?e.deleteRange(c,u):(e.replaceRangeWith(c,u,n),L0(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let o=e.parent.inlineContent?new ce(e):Us(e.node(0),e.parent,e.pos,e.index(),n,r);if(o)return o;for(let s=e.depth-1;s>=0;s--){let i=n<0?Us(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Us(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(i)return i}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new fn(e.node(0))}static atStart(e){return Us(e,e,0,0,1)||new fn(e)}static atEnd(e){return Us(e,e,e.content.size,e.childCount,-1)||new fn(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=_d[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in _d)throw new RangeError("Duplicate use of selection JSON ID "+e);return _d[e]=n,n.prototype.jsonID=e,n}getBookmark(){return ce.between(this.$anchor,this.$head).getBookmark()}}fe.prototype.visible=!0;class RP{constructor(e,n){this.$from=e,this.$to=n}}let z0=!1;function $0(t){!z0&&!t.parent.inlineContent&&(z0=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class ce extends fe{constructor(e,n=e){$0(e),$0(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return fe.near(r);let o=e.resolve(n.map(this.anchor));return new ce(o.parent.inlineContent?o:r,r)}replace(e,n=Z.empty){if(super.replace(e,n),n==Z.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof ce&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Il(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new ce(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let o=e.resolve(n);return new this(o,r==n?o:e.resolve(r))}static between(e,n,r){let o=e.pos-n.pos;if((!r||o)&&(r=o>=0?1:-1),!n.parent.inlineContent){let s=fe.findFrom(n,r,!0)||fe.findFrom(n,-r,!0);if(s)n=s.$head;else return fe.near(n,r)}return e.parent.inlineContent||(o==0?e=n:(e=(fe.findFrom(e,-r,!0)||fe.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=o<0&&(e=n))),new ce(e,n)}}fe.jsonID("text",ce);class Il{constructor(e,n){this.anchor=e,this.head=n}map(e){return new Il(e.map(this.anchor),e.map(this.head))}resolve(e){return ce.between(e.resolve(this.anchor),e.resolve(this.head))}}class oe extends fe{constructor(e){let n=e.nodeAfter,r=e.node(0).resolve(e.pos+n.nodeSize);super(e,r),this.node=n}map(e,n){let{deleted:r,pos:o}=n.mapResult(this.anchor),s=e.resolve(o);return r?fe.near(s):new oe(s)}content(){return new Z(D.from(this.node),0,0)}eq(e){return e instanceof oe&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Id(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new oe(e.resolve(n.anchor))}static create(e,n){return new oe(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}oe.prototype.visible=!1,fe.jsonID("node",oe);class Id{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Il(r,r):new Id(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&oe.isSelectable(r)?new oe(n):fe.near(n)}}class fn extends fe{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=Z.empty){if(n==Z.empty){e.delete(0,e.doc.content.size);let r=fe.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new fn(e)}map(e){return new fn(e)}eq(e){return e instanceof fn}getBookmark(){return zP}}fe.jsonID("all",fn);const zP={map(){return this},resolve(t){return new fn(t)}};function Us(t,e,n,r,o,s=!1){if(e.inlineContent)return ce.create(t,n);for(let i=r-(o>0?0:1);o>0?i<e.childCount:i>=0;i+=o){let a=e.child(i);if(a.isAtom){if(!s&&oe.isSelectable(a))return oe.create(t,n-(o<0?a.nodeSize:0))}else{let l=Us(t,a,n+o,o<0?a.childCount:0,o,s);if(l)return l}n+=a.nodeSize*o}return null}function L0(t,e,n){let r=t.steps.length-1;if(r<e)return;let o=t.steps[r];if(!(o instanceof gt||o instanceof yt))return;let s=t.mapping.maps[r],i;s.forEach((a,l,c,u)=>{i==null&&(i=u)}),t.setSelection(fe.near(t.doc.resolve(i),n))}const V0=1,Bl=2,F0=4;class $P extends R0{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.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(e){if(e.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=e,this.curSelectionFor=this.steps.length,this.updated=(this.updated|V0)&~Bl,this.storedMarks=null,this}get selectionSet(){return(this.updated&V0)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Bl,this}ensureMarks(e){return Ne.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&Bl)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~Bl,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Ne.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let o=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(o.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let i=this.doc.resolve(n);s=r==n?i.marks():i.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,o.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(fe.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,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|=F0,this}get scrolledIntoView(){return(this.updated&F0)>0}}function W0(t,e){return!e||!t?t:t.bind(e)}class Ui{constructor(e,n,r){this.name=e,this.init=W0(n.init,r),this.apply=W0(n.apply,r)}}const LP=[new Ui("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Ui("selection",{init(t,e){return t.selection||fe.atStart(e.doc)},apply(t){return t.selection}}),new Ui("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Ui("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class Bd{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=LP.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Ui(r.key,r.spec.state,r))})}}class Hs{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,n=-1){for(let r=0;r<this.config.plugins.length;r++)if(r!=n){let o=this.config.plugins[r];if(o.spec.filterTransaction&&!o.spec.filterTransaction.call(o,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let n=[e],r=this.applyInner(e),o=null;for(;;){let s=!1;for(let i=0;i<this.config.plugins.length;i++){let a=this.config.plugins[i];if(a.spec.appendTransaction){let l=o?o[i].n:0,c=o?o[i].state:this,u=l<n.length&&a.spec.appendTransaction.call(a,l?n.slice(l):n,c,r);if(u&&r.filterTransaction(u,i)){if(u.setMeta("appendedTransaction",e),!o){o=[];for(let f=0;f<this.config.plugins.length;f++)o.push(f<i?{state:r,n:n.length}:{state:this,n:0})}n.push(u),r=r.applyInner(u),s=!0}o&&(o[i]={state:r,n:n.length})}}if(!s)return{state:r,transactions:n}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new Hs(this.config),r=this.config.fields;for(let o=0;o<r.length;o++){let s=r[o];n[s.name]=s.apply(e,this[s.name],this,n)}return n}get tr(){return new $P(this)}static create(e){let n=new Bd(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new Hs(n);for(let o=0;o<n.fields.length;o++)r[n.fields[o].name]=n.fields[o].init(e,r);return r}reconfigure(e){let n=new Bd(this.schema,e.plugins),r=n.fields,o=new Hs(n);for(let s=0;s<r.length;s++){let i=r[s].name;o[i]=this.hasOwnProperty(i)?this[i]:r[s].init(e,o)}return o}toJSON(e){let n={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(n.storedMarks=this.storedMarks.map(r=>r.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let o=e[r],s=o.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(o,this[o.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let o=new Bd(e.schema,e.plugins),s=new Hs(o);return o.fields.forEach(i=>{if(i.name=="doc")s.doc=Mr.fromJSON(e.schema,n.doc);else if(i.name=="selection")s.selection=fe.fromJSON(s.doc,n.selection);else if(i.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let a in r){let l=r[a],c=l.spec.state;if(l.key==i.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(n,a)){s[i.name]=c.fromJSON.call(l,e,n[a],s);return}}s[i.name]=i.init(e,s)}}),s}}function U0(t,e,n){for(let r in t){let o=t[r];o instanceof Function?o=o.bind(e):r=="handleDOMEvents"&&(o=U0(o,e,{})),n[r]=o}return n}class ct{constructor(e){this.spec=e,this.props={},e.props&&U0(e.props,this,this.props),this.key=e.key?e.key.key:H0("plugin")}getState(e){return e[this.key]}}const Nd=Object.create(null);function H0(t){return t in Nd?t+"$"+ ++Nd[t]:(Nd[t]=0,t+"$")}class Wt{constructor(e="key"){this.key=H0(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Pd=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function j0(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const Z0=(t,e,n)=>{let r=j0(t,n);if(!r)return!1;let o=Dd(r);if(!o){let i=r.blockRange(),a=i&&Vs(i);return a==null?!1:(e&&e(t.tr.lift(i,a).scrollIntoView()),!0)}let s=o.nodeBefore;if(tw(t,o,e,-1))return!0;if(r.parent.content.size==0&&(js(s,"end")||oe.isSelectable(s)))for(let i=r.depth;;i--){let a=_l(t.doc,r.before(i),r.after(i),Z.empty);if(a&&a.slice.size<a.to-a.from){if(e){let l=t.tr.step(a);l.setSelection(js(s,"end")?fe.findFrom(l.doc.resolve(l.mapping.map(o.pos,-1)),-1):oe.create(l.doc,o.pos-s.nodeSize)),e(l.scrollIntoView())}return!0}if(i==1||r.node(i-1).childCount>1)break}return s.isAtom&&o.depth==r.depth-1?(e&&e(t.tr.delete(o.pos-s.nodeSize,o.pos).scrollIntoView()),!0):!1},VP=(t,e,n)=>{let r=j0(t,n);if(!r)return!1;let o=Dd(r);return o?K0(t,o,e):!1},FP=(t,e,n)=>{let r=q0(t,n);if(!r)return!1;let o=Od(r);return o?K0(t,o,e):!1};function K0(t,e,n){let r=e.nodeBefore,o=r,s=e.pos-1;for(;!o.isTextblock;s--){if(o.type.spec.isolating)return!1;let u=o.lastChild;if(!u)return!1;o=u}let i=e.nodeAfter,a=i,l=e.pos+1;for(;!a.isTextblock;l++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let c=_l(t.doc,s,l,Z.empty);if(!c||c.from!=s||c instanceof gt&&c.slice.size>=l-s)return!1;if(n){let u=t.tr.step(c);u.setSelection(ce.create(u.doc,s)),n(u.scrollIntoView())}return!0}function js(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const Y0=(t,e,n)=>{let{$head:r,empty:o}=t.selection,s=r;if(!o)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=Dd(r)}let i=s&&s.nodeBefore;return!i||!oe.isSelectable(i)?!1:(e&&e(t.tr.setSelection(oe.create(t.doc,s.pos-i.nodeSize)).scrollIntoView()),!0)};function Dd(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function q0(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const X0=(t,e,n)=>{let r=q0(t,n);if(!r)return!1;let o=Od(r);if(!o)return!1;let s=o.nodeAfter;if(tw(t,o,e,1))return!0;if(r.parent.content.size==0&&(js(s,"start")||oe.isSelectable(s))){let i=_l(t.doc,r.before(),r.after(),Z.empty);if(i&&i.slice.size<i.to-i.from){if(e){let a=t.tr.step(i);a.setSelection(js(s,"start")?fe.findFrom(a.doc.resolve(a.mapping.map(o.pos)),1):oe.create(a.doc,a.mapping.map(o.pos))),e(a.scrollIntoView())}return!0}}return s.isAtom&&o.depth==r.depth-1?(e&&e(t.tr.delete(o.pos,o.pos+s.nodeSize).scrollIntoView()),!0):!1},G0=(t,e,n)=>{let{$head:r,empty:o}=t.selection,s=r;if(!o)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;s=Od(r)}let i=s&&s.nodeAfter;return!i||!oe.isSelectable(i)?!1:(e&&e(t.tr.setSelection(oe.create(t.doc,s.pos)).scrollIntoView()),!0)};function Od(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let n=t.node(e);if(t.index(e)+1<n.childCount)return t.doc.resolve(t.after(e+1));if(n.type.spec.isolating)break}return null}const WP=(t,e)=>{let n=t.selection,r=n instanceof oe,o;if(r){if(n.node.isTextblock||!Ho(t.doc,n.from))return!1;o=n.from}else if(o=Al(t.doc,n.from,-1),o==null)return!1;if(e){let s=t.tr.join(o);r&&s.setSelection(oe.create(s.doc,o-t.doc.resolve(o).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},UP=(t,e)=>{let n=t.selection,r;if(n instanceof oe){if(n.node.isTextblock||!Ho(t.doc,n.to))return!1;r=n.to}else if(r=Al(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},HP=(t,e)=>{let{$from:n,$to:r}=t.selection,o=n.blockRange(r),s=o&&Vs(o);return s==null?!1:(e&&e(t.tr.lift(o,s).scrollIntoView()),!0)},J0=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(`
74
+ `).scrollIntoView()),!0)};function Rd(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}const jP=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let o=n.node(-1),s=n.indexAfter(-1),i=Rd(o.contentMatchAt(s));if(!i||!o.canReplaceWith(s,s,i))return!1;if(e){let a=n.after(),l=t.tr.replaceWith(a,a,i.createAndFill());l.setSelection(fe.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},Q0=(t,e)=>{let n=t.selection,{$from:r,$to:o}=n;if(n instanceof fn||r.parent.inlineContent||o.parent.inlineContent)return!1;let s=Rd(o.parent.contentMatchAt(o.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let i=(!r.parentOffset&&o.index()<o.parent.childCount?r:o).pos,a=t.tr.insert(i,s.createAndFill());a.setSelection(ce.create(a.doc,i+1)),e(a.scrollIntoView())}return!0},ew=(t,e)=>{let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let s=n.before();if(_r(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),o=r&&Vs(r);return o==null?!1:(e&&e(t.tr.lift(r,o).scrollIntoView()),!0)};function ZP(t){return(e,n)=>{let{$from:r,$to:o}=e.selection;if(e.selection instanceof oe&&e.selection.node.isBlock)return!r.parentOffset||!_r(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],i,a,l=!1,c=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){l=r.end(p)==r.pos+(r.depth-p),c=r.start(p)==r.pos-(r.depth-p),a=Rd(r.node(p-1).contentMatchAt(r.indexAfter(p-1))),s.unshift(l&&a?{type:a}:null),i=p;break}else{if(p==1)return!1;s.unshift(null)}let u=e.tr;(e.selection instanceof ce||e.selection instanceof fn)&&u.deleteSelection();let f=u.mapping.map(r.pos),h=_r(u.doc,f,s.length,s);if(h||(s[0]=a?{type:a}:null,h=_r(u.doc,f,s.length,s)),!h)return!1;if(u.split(f,s.length,s),!l&&c&&r.node(i).type!=a){let p=u.mapping.map(r.before(i)),m=u.doc.resolve(p);a&&r.node(i-1).canReplaceWith(m.index(),m.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(i)),a)}return n&&n(u.scrollIntoView()),!0}}const KP=ZP(),YP=(t,e)=>{let{$from:n,to:r}=t.selection,o,s=n.sharedDepth(r);return s==0?!1:(o=n.before(s),e&&e(t.tr.setSelection(oe.create(t.doc,o))),!0)};function qP(t,e,n){let r=e.nodeBefore,o=e.nodeAfter,s=e.index();return!r||!o||!r.type.compatibleContent(o.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(o.isTextblock||Ho(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function tw(t,e,n,r){let o=e.nodeBefore,s=e.nodeAfter,i,a,l=o.type.spec.isolating||s.type.spec.isolating;if(!l&&qP(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(i=(a=o.contentMatchAt(o.childCount)).findWrapping(s.type))&&a.matchType(i[0]||s.type).validEnd){if(n){let p=e.pos+s.nodeSize,m=D.empty;for(let w=i.length-1;w>=0;w--)m=D.from(i[w].create(null,m));m=D.from(o.copy(m));let g=t.tr.step(new yt(e.pos-1,p,e.pos,p,new Z(m,1,0),i.length,!0)),y=g.doc.resolve(p+2*i.length);y.nodeAfter&&y.nodeAfter.type==o.type&&Ho(g.doc,y.pos)&&g.join(y.pos),n(g.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&l?null:fe.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),h=f&&Vs(f);if(h!=null&&h>=e.depth)return n&&n(t.tr.lift(f,h).scrollIntoView()),!0;if(c&&js(s,"start",!0)&&js(o,"end")){let p=o,m=[];for(;m.push(p),!p.isTextblock;)p=p.lastChild;let g=s,y=1;for(;!g.isTextblock;g=g.firstChild)y++;if(p.canReplace(p.childCount,p.childCount,g.content)){if(n){let w=D.empty;for(let b=m.length-1;b>=0;b--)w=D.from(m[b].copy(w));let k=t.tr.step(new yt(e.pos-m.length,e.pos+s.nodeSize,e.pos+y,e.pos+s.nodeSize-y,new Z(w,m.length,0),0,!0));n(k.scrollIntoView())}return!0}}return!1}function nw(t){return function(e,n){let r=e.selection,o=t<0?r.$from:r.$to,s=o.depth;for(;o.node(s).isInline;){if(!s)return!1;s--}return o.node(s).isTextblock?(n&&n(e.tr.setSelection(ce.create(e.doc,t<0?o.start(s):o.end(s)))),!0):!1}}const XP=nw(-1),GP=nw(1);function JP(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s),a=i&&T0(i,t,e);return a?(r&&r(n.tr.wrap(i,a).scrollIntoView()),!0):!1}}function rw(t,e=null){return function(n,r){let o=!1;for(let s=0;s<n.selection.ranges.length&&!o;s++){let{$from:{pos:i},$to:{pos:a}}=n.selection.ranges[s];n.doc.nodesBetween(i,a,(l,c)=>{if(o)return!1;if(!(!l.isTextblock||l.hasMarkup(t,e)))if(l.type==t)o=!0;else{let u=n.doc.resolve(c),f=u.index();o=u.parent.canReplaceWith(f,f+1,t)}})}if(!o)return!1;if(r){let s=n.tr;for(let i=0;i<n.selection.ranges.length;i++){let{$from:{pos:a},$to:{pos:l}}=n.selection.ranges[i];s.setBlockType(a,l,t,e)}r(s.scrollIntoView())}return!0}}function zd(...t){return function(e,n,r){for(let o=0;o<t.length;o++)if(t[o](e,n,r))return!0;return!1}}zd(Pd,Z0,Y0),zd(Pd,X0,G0),zd(J0,Q0,ew,KP),typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function QP(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s);if(!i)return!1;let a=r?n.tr:null;return eD(a,i,t,e)?(r&&r(a.scrollIntoView()),!0):!1}}function eD(t,e,n,r=null){let o=!1,s=e,i=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let l=i.resolve(e.start-2);s=new Sl(l,l,e.depth),e.endIndex<e.parent.childCount&&(e=new Sl(e.$from,i.resolve(e.$to.end(e.depth)),e.depth)),o=!0}let a=T0(s,n,r,e);return a?(t&&tD(t,e,a,o,n),!0):!1}function tD(t,e,n,r,o){let s=D.empty;for(let u=n.length-1;u>=0;u--)s=D.from(n[u].type.create(n[u].attrs,s));t.step(new yt(e.start-(r?2:0),e.end,e.start,e.end,new Z(s,0,0),n.length,!0));let i=0;for(let u=0;u<n.length;u++)n[u].type==o&&(i=u+1);let a=n.length-i,l=e.start+n.length-(r?2:0),c=e.parent;for(let u=e.startIndex,f=e.endIndex,h=!0;u<f;u++,h=!1)!h&&_r(t.doc,l,a)&&(t.split(l,a),l+=2*a),l+=c.child(u).nodeSize;return t}function nD(t){return function(e,n){let{$from:r,$to:o}=e.selection,s=r.blockRange(o,i=>i.childCount>0&&i.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?rD(e,n,t,s):oD(e,n,s):!0:!1}}function rD(t,e,n,r){let o=t.tr,s=r.end,i=r.$to.end(r.depth);s<i&&(o.step(new yt(s-1,i,s,i,new Z(D.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new Sl(o.doc.resolve(r.$from.pos),o.doc.resolve(i),r.depth));const a=Vs(r);if(a==null)return!1;o.lift(r,a);let l=o.doc.resolve(o.mapping.map(s,-1)-1);return Ho(o.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&o.join(l.pos),e(o.scrollIntoView()),!0}function oD(t,e,n){let r=t.tr,o=n.parent;for(let p=n.end,m=n.endIndex-1,g=n.startIndex;m>g;m--)p-=o.child(m).nodeSize,r.delete(p-1,p+1);let s=r.doc.resolve(n.start),i=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let a=n.startIndex==0,l=n.endIndex==o.childCount,c=s.node(-1),u=s.index(-1);if(!c.canReplace(u+(a?0:1),u+1,i.content.append(l?D.empty:D.from(o))))return!1;let f=s.pos,h=f+i.nodeSize;return r.step(new yt(f-(a?1:0),h+(l?1:0),f+1,h-1,new Z((a?D.empty:D.from(o.copy(D.empty))).append(l?D.empty:D.from(o.copy(D.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function sD(t){return function(e,n){let{$from:r,$to:o}=e.selection,s=r.blockRange(o,c=>c.childCount>0&&c.firstChild.type==t);if(!s)return!1;let i=s.startIndex;if(i==0)return!1;let a=s.parent,l=a.child(i-1);if(l.type!=t)return!1;if(n){let c=l.lastChild&&l.lastChild.type==a.type,u=D.from(c?t.create():null),f=new Z(D.from(t.create(null,D.from(a.type.create(null,u)))),c?3:1,0),h=s.start,p=s.end;n(e.tr.step(new yt(h-(c?3:1),p,h,p,f,1,!0)).scrollIntoView())}return!0}}const _t=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Zs=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let $d=null;const Ir=function(t,e,n){let r=$d||($d=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},iD=function(){$d=null},jo=function(t,e,n,r){return n&&(ow(t,e,n,r,-1)||ow(t,e,n,r,1))},aD=/^(img|br|input|textarea|hr)$/i;function ow(t,e,n,r,o){for(var s;;){if(t==n&&e==r)return!0;if(e==(o<0?0:xn(t))){let i=t.parentNode;if(!i||i.nodeType!=1||Hi(t)||aD.test(t.nodeName)||t.contentEditable=="false")return!1;e=_t(t)+(o<0?0:1),t=i}else if(t.nodeType==1){let i=t.childNodes[e+(o<0?-1:0)];if(i.nodeType==1&&i.contentEditable=="false")if(!((s=i.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=o;else return!1;else t=i,e=o<0?xn(t):0}else return!1}}function xn(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function lD(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=xn(t)}else if(t.parentNode&&!Hi(t))e=_t(t),t=t.parentNode;else return null}}function cD(t,e){for(;;){if(t.nodeType==3&&e<t.nodeValue.length)return t;if(t.nodeType==1&&e<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[e],e=0}else if(t.parentNode&&!Hi(t))e=_t(t)+1,t=t.parentNode;else return null}}function uD(t,e,n){for(let r=e==0,o=e==xn(t);r||o;){if(t==n)return!0;let s=_t(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,o=o&&s==xn(t)}}function Hi(t){let e;for(let n=t;n&&!(e=n.pmViewDesc);n=n.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}const Nl=function(t){return t.focusNode&&jo(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Zo(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function dD(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function fD(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(xn(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(xn(r.startContainer),r.startOffset)}}}const or=typeof navigator<"u"?navigator:null,sw=typeof document<"u"?document:null,so=or&&or.userAgent||"",Ld=/Edge\/(\d+)/.exec(so),iw=/MSIE \d/.exec(so),Vd=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(so),Qt=!!(iw||Vd||Ld),io=iw?document.documentMode:Vd?+Vd[1]:Ld?+Ld[1]:0,Tn=!Qt&&/gecko\/(\d+)/i.test(so);Tn&&+(/Firefox\/(\d+)/.exec(so)||[0,0])[1];const Fd=!Qt&&/Chrome\/(\d+)/.exec(so),wt=!!Fd,aw=Fd?+Fd[1]:0,It=!Qt&&!!or&&/Apple Computer/.test(or.vendor),Ks=It&&(/Mobile\/\w+/.test(so)||!!or&&or.maxTouchPoints>2),Mn=Ks||(or?/Mac/.test(or.platform):!1),lw=or?/Win/.test(or.platform):!1,Br=/Android \d/.test(so),ji=!!sw&&"webkitFontSmoothing"in sw.documentElement.style,hD=ji?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function pD(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function Nr(t,e){return typeof t=="number"?t:t[e]}function mD(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function cw(t,e,n){let r=t.someProp("scrollThreshold")||0,o=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let i=n||t.dom;i;){if(i.nodeType!=1){i=Zs(i);continue}let a=i,l=a==s.body,c=l?pD(s):mD(a),u=0,f=0;if(e.top<c.top+Nr(r,"top")?f=-(c.top-e.top+Nr(o,"top")):e.bottom>c.bottom-Nr(r,"bottom")&&(f=e.bottom-e.top>c.bottom-c.top?e.top+Nr(o,"top")-c.top:e.bottom-c.bottom+Nr(o,"bottom")),e.left<c.left+Nr(r,"left")?u=-(c.left-e.left+Nr(o,"left")):e.right>c.right-Nr(r,"right")&&(u=e.right-c.right+Nr(o,"right")),u||f)if(l)s.defaultView.scrollBy(u,f);else{let p=a.scrollLeft,m=a.scrollTop;f&&(a.scrollTop+=f),u&&(a.scrollLeft+=u);let g=a.scrollLeft-p,y=a.scrollTop-m;e={left:e.left-g,top:e.top-y,right:e.right-g,bottom:e.bottom-y}}let h=l?"fixed":getComputedStyle(i).position;if(/^(fixed|sticky)$/.test(h))break;i=h=="absolute"?i.offsetParent:Zs(i)}}function gD(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,o;for(let s=(e.left+e.right)/2,i=n+1;i<Math.min(innerHeight,e.bottom);i+=5){let a=t.root.elementFromPoint(s,i);if(!a||a==t.dom||!t.dom.contains(a))continue;let l=a.getBoundingClientRect();if(l.top>=n-20){r=a,o=l.top;break}}return{refDOM:r,refTop:o,stack:uw(t.dom)}}function uw(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Zs(r));return e}function yD({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;dw(n,r==0?0:r-e)}function dw(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:o,left:s}=t[n];r.scrollTop!=o+e&&(r.scrollTop=o+e),r.scrollLeft!=s&&(r.scrollLeft=s)}}let Ys=null;function wD(t){if(t.setActive)return t.setActive();if(Ys)return t.focus(Ys);let e=uw(t);t.focus(Ys==null?{get preventScroll(){return Ys={preventScroll:!0},!0}}:void 0),Ys||(Ys=!1,dw(e,0))}function fw(t,e){let n,r=2e8,o,s=0,i=e.top,a=e.top,l,c;for(let u=t.firstChild,f=0;u;u=u.nextSibling,f++){let h;if(u.nodeType==1)h=u.getClientRects();else if(u.nodeType==3)h=Ir(u).getClientRects();else continue;for(let p=0;p<h.length;p++){let m=h[p];if(m.top<=i&&m.bottom>=a){i=Math.max(m.bottom,i),a=Math.min(m.top,a);let g=m.left>e.left?m.left-e.left:m.right<e.left?e.left-m.right:0;if(g<r){n=u,r=g,o=g&&n.nodeType==3?{left:m.right<e.left?m.right:m.left,top:e.top}:e,u.nodeType==1&&g&&(s=f+(e.left>=(m.left+m.right)/2?1:0));continue}}else m.top>e.top&&!l&&m.left<=e.left&&m.right>=e.left&&(l=u,c={left:Math.max(m.left,Math.min(m.right,e.left)),top:m.top});!n&&(e.left>=m.right&&e.top>=m.top||e.left>=m.left&&e.top>=m.bottom)&&(s=f+1)}}return!n&&l&&(n=l,o=c,r=0),n&&n.nodeType==3?kD(n,o):!n||r&&n.nodeType==1?{node:t,offset:s}:fw(n,o)}function kD(t,e){let n=t.nodeValue.length,r=document.createRange(),o;for(let s=0;s<n;s++){r.setEnd(t,s+1),r.setStart(t,s);let i=ao(r,1);if(i.top!=i.bottom&&Wd(e,i)){o={node:t,offset:s+(e.left>=(i.left+i.right)/2?1:0)};break}}return r.detach(),o||{node:t,offset:0}}function Wd(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function vD(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function bD(t,e,n){let{node:r,offset:o}=fw(e,n),s=-1;if(r.nodeType==1&&!r.firstChild){let i=r.getBoundingClientRect();s=i.left!=i.right&&n.left>(i.left+i.right)/2?1:-1}return t.docView.posFromDOM(r,o,s)}function SD(t,e,n,r){let o=-1;for(let s=e,i=!1;s!=t.dom;){let a=t.docView.nearestDesc(s,!0),l;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((l=a.dom.getBoundingClientRect()).width||l.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!i&&l.left>r.left||l.top>r.top?o=a.posBefore:(!i&&l.right<r.left||l.bottom<r.top)&&(o=a.posAfter),i=!0),!a.contentDOM&&o<0&&!a.node.isText))return(a.node.isBlock?r.top<(l.top+l.bottom)/2:r.left<(l.left+l.right)/2)?a.posBefore:a.posAfter;s=a.dom.parentNode}return o>-1?o:t.docView.posFromDOM(e,n,-1)}function hw(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let o=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),s=o;;){let i=t.childNodes[s];if(i.nodeType==1){let a=i.getClientRects();for(let l=0;l<a.length;l++){let c=a[l];if(Wd(e,c))return hw(i,e,c)}}if((s=(s+1)%r)==o)break}return t}function ED(t,e){let n=t.dom.ownerDocument,r,o=0,s=fD(n,e.left,e.top);s&&({node:r,offset:o}=s);let i=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top),a;if(!i||!t.dom.contains(i.nodeType!=1?i.parentNode:i)){let c=t.dom.getBoundingClientRect();if(!Wd(e,c)||(i=hw(t.dom,e,c),!i))return null}if(It)for(let c=i;r&&c;c=Zs(c))c.draggable&&(r=void 0);if(i=vD(i,e),r){if(Tn&&r.nodeType==1&&(o=Math.min(o,r.childNodes.length),o<r.childNodes.length)){let u=r.childNodes[o],f;u.nodeName=="IMG"&&(f=u.getBoundingClientRect()).right<=e.left&&f.bottom>e.top&&o++}let c;ji&&o&&r.nodeType==1&&(c=r.childNodes[o-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&o--,r==t.dom&&o==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?a=t.state.doc.content.size:(o==0||r.nodeType!=1||r.childNodes[o-1].nodeName!="BR")&&(a=SD(t,r,o,e))}a==null&&(a=bD(t,i,e));let l=t.docView.nearestDesc(i,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function pw(t){return t.top<t.bottom||t.left<t.right}function ao(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(pw(r))return r}return Array.prototype.find.call(n,pw)||t.getBoundingClientRect()}const CD=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function mw(t,e,n){let{node:r,offset:o,atom:s}=t.docView.domFromPos(e,n<0?-1:1),i=ji||Tn;if(r.nodeType==3)if(i&&(CD.test(r.nodeValue)||(n<0?!o:o==r.nodeValue.length))){let l=ao(Ir(r,o,o),n);if(Tn&&o&&/\s/.test(r.nodeValue[o-1])&&o<r.nodeValue.length){let c=ao(Ir(r,o-1,o-1),-1);if(c.top==l.top){let u=ao(Ir(r,o,o+1),-1);if(u.top!=l.top)return Zi(u,u.left<c.left)}}return l}else{let l=o,c=o,u=n<0?1:-1;return n<0&&!o?(c++,u=-1):n>=0&&o==r.nodeValue.length?(l--,u=1):n<0?l--:c++,Zi(ao(Ir(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&o&&(n<0||o==xn(r))){let l=r.childNodes[o-1];if(l.nodeType==1)return Ud(l.getBoundingClientRect(),!1)}if(s==null&&o<xn(r)){let l=r.childNodes[o];if(l.nodeType==1)return Ud(l.getBoundingClientRect(),!0)}return Ud(r.getBoundingClientRect(),n>=0)}if(s==null&&o&&(n<0||o==xn(r))){let l=r.childNodes[o-1],c=l.nodeType==3?Ir(l,xn(l)-(i?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return Zi(ao(c,1),!1)}if(s==null&&o<xn(r)){let l=r.childNodes[o];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?Ir(l,0,i?0:1):l.nodeType==1?l:null:null;if(c)return Zi(ao(c,-1),!0)}return Zi(ao(r.nodeType==3?Ir(r):r,-n),n>=0)}function Zi(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Ud(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function gw(t,e,n){let r=t.state,o=t.root.activeElement;r!=e&&t.updateState(e),o!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),o!=t.dom&&o&&o.focus()}}function xD(t,e,n){let r=e.selection,o=n=="up"?r.$from:r.$to;return gw(t,e,()=>{let{node:s}=t.docView.domFromPos(o.pos,n=="up"?-1:1);for(;;){let a=t.docView.nearestDesc(s,!0);if(!a)break;if(a.node.isBlock){s=a.contentDOM||a.dom;break}s=a.dom.parentNode}let i=mw(t,o.pos,1);for(let a=s.firstChild;a;a=a.nextSibling){let l;if(a.nodeType==1)l=a.getClientRects();else if(a.nodeType==3)l=Ir(a,0,a.nodeValue.length).getClientRects();else continue;for(let c=0;c<l.length;c++){let u=l[c];if(u.bottom>u.top+1&&(n=="up"?i.top-u.top>(u.bottom-i.top)*2:u.bottom-i.bottom>(i.bottom-u.top)*2))return!1}}return!0})}const TD=/[\u0590-\u08ac]/;function MD(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let o=r.parentOffset,s=!o,i=o==r.parent.content.size,a=t.domSelection();return a?!TD.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?s:i:gw(t,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:f}=t.domSelectionRange(),h=a.caretBidiLevel;a.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:m,focusOffset:g}=t.domSelectionRange(),y=m&&!p.contains(m.nodeType==1?m:m.parentNode)||l==m&&c==g;try{a.collapse(u,f),l&&(l!=u||c!=f)&&a.extend&&a.extend(l,c)}catch{}return h!=null&&(a.caretBidiLevel=h),y}):r.pos==r.start()||r.pos==r.end()}let yw=null,ww=null,kw=!1;function AD(t,e,n){return yw==e&&ww==n?kw:(yw=e,ww=n,kw=n=="up"||n=="down"?xD(t,e,n):MD(t,e,n))}const An=0,vw=1,Ko=2,sr=3;class Ki{constructor(e,n,r,o){this.parent=e,this.children=n,this.dom=r,this.contentDOM=o,this.dirty=An,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;n<this.children.length;n++)e+=this.children[n].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let n=0,r=this.posAtStart;;n++){let o=this.children[n];if(o==e)return r;r+=o.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(e,n,r){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(r<0){let s,i;if(e==this.contentDOM)s=e.childNodes[n-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.previousSibling}for(;s&&!((i=s.pmViewDesc)&&i.parent==this);)s=s.previousSibling;return s?this.posBeforeChild(i)+i.size:this.posAtStart}else{let s,i;if(e==this.contentDOM)s=e.childNodes[n];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;s=e.nextSibling}for(;s&&!((i=s.pmViewDesc)&&i.parent==this);)s=s.nextSibling;return s?this.posBeforeChild(i):this.posAtEnd}let o;if(e==this.dom&&this.contentDOM)o=n>_t(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))o=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){o=!1;break}if(s.previousSibling)break}if(o==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){o=!0;break}if(s.nextSibling)break}}return o??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,o=e;o;o=o.parentNode){let s=this.getDesc(o),i;if(s&&(!n||s.node))if(r&&(i=s.nodeDOM)&&!(i.nodeType==1?i.contains(e.nodeType==1?e:e.parentNode):i==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let o=e;o;o=o.parentNode){let s=this.getDesc(o);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;n<this.children.length;n++){let o=this.children[n],s=r+o.size;if(r==e&&s!=r){for(;!o.border&&o.children.length;)for(let i=0;i<o.children.length;i++){let a=o.children[i];if(a.size){o=a;break}}return o}if(e<s)return o.descAt(e-r-o.border);r=s}}domFromPos(e,n){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,o=0;for(let s=0;r<this.children.length;r++){let i=this.children[r],a=s+i.size;if(a>e||i instanceof Ew){o=e-s;break}s=a}if(o)return this.children[r].domFromPos(o-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof bw&&s.side>=0;r--);if(n<=0){let s,i=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,i=!1);return s&&n&&i&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?_t(s.dom)+1:0}}else{let s,i=!0;for(;s=r<this.children.length?this.children[r]:null,!(!s||s.dom.parentNode==this.contentDOM);r++,i=!1);return s&&i&&!s.border&&!s.domAtom?s.domFromPos(0,n):{node:this.contentDOM,offset:s?_t(s.dom):this.contentDOM.childNodes.length}}}parseRange(e,n,r=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:n,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let o=-1,s=-1;for(let i=r,a=0;;a++){let l=this.children[a],c=i+l.size;if(o==-1&&e<=c){let u=i+l.border;if(e>=u&&n<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(e,n,u);e=i;for(let f=a;f>0;f--){let h=this.children[f-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){o=_t(h.dom)+1;break}e-=h.size}o==-1&&(o=0)}if(o>-1&&(c>n||a==this.children.length-1)){n=c;for(let u=a+1;u<this.children.length;u++){let f=this.children[u];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(-1)){s=_t(f.dom);break}n+=f.size}s==-1&&(s=this.contentDOM.childNodes.length);break}i=c}return{node:this.contentDOM,from:e,to:n,fromOffset:o,toOffset:s}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let n=this.children[e<0?0:this.children.length-1];return n.size==0||n.emptyChildAt(e)}domAfterPos(e){let{node:n,offset:r}=this.domFromPos(e,0);if(n.nodeType!=1||r==n.childNodes.length)throw new RangeError("No node after pos "+e);return n.childNodes[r]}setSelection(e,n,r,o=!1){let s=Math.min(e,n),i=Math.max(e,n);for(let p=0,m=0;p<this.children.length;p++){let g=this.children[p],y=m+g.size;if(s>m&&i<y)return g.setSelection(e-m-g.border,n-m-g.border,r,o);m=y}let a=this.domFromPos(e,e?-1:1),l=n==e?a:this.domFromPos(n,n?-1:1),c=r.root.getSelection(),u=r.domSelectionRange(),f=!1;if((Tn||It)&&e==n){let{node:p,offset:m}=a;if(p.nodeType==3){if(f=!!(m&&p.nodeValue[m-1]==`
75
+ `),f&&m==p.nodeValue.length)for(let g=p,y;g;g=g.parentNode){if(y=g.nextSibling){y.nodeName=="BR"&&(a=l={node:y.parentNode,offset:_t(y)+1});break}let w=g.pmViewDesc;if(w&&w.node&&w.node.isBlock)break}}else{let g=p.childNodes[m-1];f=g&&(g.nodeName=="BR"||g.contentEditable=="false")}}if(Tn&&u.focusNode&&u.focusNode!=l.node&&u.focusNode.nodeType==1){let p=u.focusNode.childNodes[u.focusOffset];p&&p.contentEditable=="false"&&(o=!0)}if(!(o||f&&It)&&jo(a.node,a.offset,u.anchorNode,u.anchorOffset)&&jo(l.node,l.offset,u.focusNode,u.focusOffset))return;let h=!1;if((c.extend||e==n)&&!(f&&Tn)){c.collapse(a.node,a.offset);try{e!=n&&c.extend(l.node,l.offset),h=!0}catch{}}if(!h){if(e>n){let m=a;a=l,l=m}let p=document.createRange();p.setEnd(l.node,l.offset),p.setStart(a.node,a.offset),c.removeAllRanges(),c.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,n){for(let r=0,o=0;o<this.children.length;o++){let s=this.children[o],i=r+s.size;if(r==i?e<=i&&n>=r:e<i&&n>r){let a=r+s.border,l=i-s.border;if(e>=a&&n<=l){this.dirty=e==r||n==i?Ko:vw,e==a&&n==l&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=sr:s.markDirty(e-a,n-a);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?Ko:sr}r=i}this.dirty=Ko}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?Ko:vw;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class bw extends Ki{constructor(e,n,r,o){let s,i=n.type.toDOM;if(typeof i=="function"&&(i=i(r,()=>{if(!s)return o;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(i.nodeType!=1){let a=document.createElement("span");a.appendChild(i),i=a}i.contentEditable="false",i.classList.add("ProseMirror-widget")}super(e,[],i,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==An&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(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 ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class _D extends Ki{constructor(e,n,r,o){super(e,[],n,null),this.textDOM=r,this.text=o}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Yo extends Ki{constructor(e,n,r,o,s){super(e,[],r,o),this.mark=n,this.spec=s}static create(e,n,r,o){let s=o.nodeViews[n.type.name],i=s&&s(n,o,r);return(!i||!i.dom)&&(i=Wo.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Yo(e,n,i.dom,i.contentDOM||i.dom,i)}parseRule(){return this.dirty&sr||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=sr&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=An){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=An}}slice(e,n,r){let o=Yo.create(this.parent,this.mark,!0,r),s=this.children,i=this.size;n<i&&(s=jd(s,n,i,r)),e>0&&(s=jd(s,0,e,r));for(let a=0;a<s.length;a++)s[a].parent=o;return o.children=s,o}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class lo extends Ki{constructor(e,n,r,o,s,i,a,l,c){super(e,[],s,i),this.node=n,this.outerDeco=r,this.innerDeco=o,this.nodeDOM=a}static create(e,n,r,o,s,i){let a=s.nodeViews[n.type.name],l,c=a&&a(n,s,()=>{if(!l)return i;if(l.parent)return l.parent.posBeforeChild(l)},r,o),u=c&&c.dom,f=c&&c.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:f}=Wo.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!f&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let h=u;return u=Tw(u,r,n),c?l=new ID(e,n,r,o,u,f||null,h,c,s,i+1):n.isText?new Pl(e,n,r,o,u,h,s):new lo(e,n,r,o,u,f||null,h,s,i+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 n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>D.empty)}return e}matchesNode(e,n,r){return this.dirty==An&&e.eq(this.node)&&Dl(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,o=n,s=e.composing?this.localCompositionInfo(e,n):null,i=s&&s.pos>-1?s:null,a=s&&s.pos<0,l=new ND(this,i&&i.node,e);OD(this.node,this.innerDeco,(c,u,f)=>{c.spec.marks?l.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!f&&l.syncToMarks(u==this.node.childCount?Ne.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,o)},(c,u,f,h)=>{l.syncToMarks(c.marks,r,e,h);let p;l.findNodeMatch(c,u,f,h)||a&&e.state.selection.from>o&&e.state.selection.to<o+c.nodeSize&&(p=l.findIndexWithChild(s.node))>-1&&l.updateNodeAt(c,u,f,p,e)||l.updateNextNode(c,u,f,e,h,o)||l.addNode(c,u,f,e,o),o+=c.nodeSize}),l.syncToMarks([],r,e,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==Ko)&&(i&&this.protectLocalComposition(e,i),Cw(this.contentDOM,this.children,e),Ks&&RD(this.dom))}localCompositionInfo(e,n){let{from:r,to:o}=e.state.selection;if(!(e.state.selection instanceof ce)||r<n||o>n+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 i=s.nodeValue,a=zD(this.node.content,i,r-n,o-n);return a<0?null:{node:s,pos:a,text:i}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:o}){if(this.getDesc(n))return;let s=n;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 i=new _D(this,s,n,o);e.input.compositionNodes.push(i),this.children=jd(this.children,r,r+o.length,e,i)}update(e,n,r,o){return this.dirty==sr||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,o),!0)}updateInner(e,n,r,o){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(o,this.posAtStart),this.dirty=An}updateOuterDeco(e){if(Dl(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=xw(this.dom,this.nodeDOM,Hd(this.outerDeco,this.node,n),Hd(e,this.node,n)),this.dom!=r&&(r.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.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function Sw(t,e,n,r,o){Tw(r,e,t);let s=new lo(void 0,t,e,n,r,r,r,o,0);return s.contentDOM&&s.updateChildren(o,0),s}class Pl extends lo{constructor(e,n,r,o,s,i,a){super(e,n,r,o,s,null,i,a,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,o){return this.dirty==sr||this.dirty!=An&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=An||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,o.trackWrites==this.nodeDOM&&(o.trackWrites=null)),this.node=e,this.dirty=An,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let o=this.node.cut(e,n),s=document.createTextNode(o.text);return new Pl(this.parent,o,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=sr)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Ew extends Ki{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==An&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class ID extends lo{constructor(e,n,r,o,s,i,a,l,c,u){super(e,n,r,o,s,i,a,c,u),this.spec=l}update(e,n,r,o){if(this.dirty==sr)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,o),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,o)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,o){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,o)}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 Cw(t,e,n){let r=t.firstChild,o=!1;for(let s=0;s<e.length;s++){let i=e[s],a=i.dom;if(a.parentNode==t){for(;a!=r;)r=Mw(r),o=!0;r=r.nextSibling}else o=!0,t.insertBefore(a,r);if(i instanceof Yo){let l=r?r.previousSibling:t.lastChild;Cw(i.contentDOM,i.children,n),r=l?l.nextSibling:t.firstChild}}for(;r;)r=Mw(r),o=!0;o&&n.trackWrites==t&&(n.trackWrites=null)}const Yi=function(t){t&&(this.nodeName=t)};Yi.prototype=Object.create(null);const qo=[new Yi];function Hd(t,e,n){if(t.length==0)return qo;let r=n?qo[0]:new Yi,o=[r];for(let s=0;s<t.length;s++){let i=t[s].type.attrs;if(i){i.nodeName&&o.push(r=new Yi(i.nodeName));for(let a in i){let l=i[a];l!=null&&(n&&o.length==1&&o.push(r=new Yi(e.isInline?"span":"div")),a=="class"?r.class=(r.class?r.class+" ":"")+l:a=="style"?r.style=(r.style?r.style+";":"")+l:a!="nodeName"&&(r[a]=l))}}}return o}function xw(t,e,n,r){if(n==qo&&r==qo)return e;let o=e;for(let s=0;s<r.length;s++){let i=r[s],a=n[s];if(s){let l;a&&a.nodeName==i.nodeName&&o!=t&&(l=o.parentNode)&&l.nodeName.toLowerCase()==i.nodeName||(l=document.createElement(i.nodeName),l.pmIsDeco=!0,l.appendChild(o),a=qo[0]),o=l}BD(o,a||qo[0],i)}return o}function BD(t,e,n){for(let r in e)r!="class"&&r!="style"&&r!="nodeName"&&!(r in n)&&t.removeAttribute(r);for(let r in n)r!="class"&&r!="style"&&r!="nodeName"&&n[r]!=e[r]&&t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],o=n.class?n.class.split(" ").filter(Boolean):[];for(let s=0;s<r.length;s++)o.indexOf(r[s])==-1&&t.classList.remove(r[s]);for(let s=0;s<o.length;s++)r.indexOf(o[s])==-1&&t.classList.add(o[s]);t.classList.length==0&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,o;for(;o=r.exec(e.style);)t.style.removeProperty(o[1])}n.style&&(t.style.cssText+=n.style)}}function Tw(t,e,n){return xw(t,t,qo,Hd(e,n,t.nodeType!=1))}function Dl(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].type.eq(e[n].type))return!1;return!0}function Mw(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class ND{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=PD(e.node.content,e)}destroyBetween(e,n){if(e!=n){for(let r=e;r<n;r++)this.top.children[r].destroy();this.top.children.splice(e,n-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,n,r,o){let s=0,i=this.stack.length>>1,a=Math.min(i,e.length);for(;s<a&&(s==i-1?this.top:this.stack[s+1<<1]).matchesMark(e[s])&&e[s].type.spec.spanning!==!1;)s++;for(;s<i;)this.destroyRest(),this.top.dirty=An,this.index=this.stack.pop(),this.top=this.stack.pop(),i--;for(;i<e.length;){this.stack.push(this.top,this.index+1);let l=-1,c=this.top.children.length;o<this.preMatch.index&&(c=Math.min(this.index+3,c));for(let u=this.index;u<c;u++){let f=this.top.children[u];if(f.matchesMark(e[i])&&!this.isLocked(f.dom)){l=u;break}}if(l>-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let u=Yo.create(this.top,e[i],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,i++}}findNodeMatch(e,n,r,o){let s=-1,i;if(o>=this.preMatch.index&&(i=this.preMatch.matches[o-this.preMatch.index]).parent==this.top&&i.matchesNode(e,n,r))s=this.top.children.indexOf(i,this.index);else for(let a=this.index,l=Math.min(this.top.children.length,a+5);a<l;a++){let c=this.top.children[a];if(c.matchesNode(e,n,r)&&!this.preMatch.matched.has(c)){s=a;break}}return s<0?!1:(this.destroyBetween(this.index,s),this.index++,!0)}updateNodeAt(e,n,r,o,s){let i=this.top.children[o];return i.dirty==sr&&i.dom==i.contentDOM&&(i.dirty=Ko),i.update(e,n,r,s)?(this.destroyBetween(this.index,o),this.index++,!0):!1}findIndexWithChild(e){for(;;){let n=e.parentNode;if(!n)return-1;if(n==this.top.contentDOM){let r=e.pmViewDesc;if(r){for(let o=this.index;o<this.top.children.length;o++)if(this.top.children[o]==r)return o}return-1}e=n}}updateNextNode(e,n,r,o,s,i){for(let a=this.index;a<this.top.children.length;a++){let l=this.top.children[a];if(l instanceof lo){let c=this.preMatch.matched.get(l);if(c!=null&&c!=s)return!1;let u=l.dom,f,h=this.isLocked(u)&&!(e.isText&&l.node&&l.node.isText&&l.nodeDOM.nodeValue==e.text&&l.dirty!=sr&&Dl(n,l.outerDeco));if(!h&&l.update(e,n,r,o))return this.destroyBetween(this.index,a),l.dom!=u&&(this.changed=!0),this.index++,!0;if(!h&&(f=this.recreateWrapper(l,e,n,r,o,i)))return this.destroyBetween(this.index,a),this.top.children[this.index]=f,f.contentDOM&&(f.dirty=Ko,f.updateChildren(o,i+1),f.dirty=An),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,n,r,o,s,i){if(e.dirty||n.isAtom||!e.children.length||!e.node.content.eq(n.content)||!Dl(r,e.outerDeco)||!o.eq(e.innerDeco))return null;let a=lo.create(this.top,n,r,o,s,i);if(a.contentDOM){a.children=e.children,e.children=[];for(let l of a.children)l.parent=a}return e.destroy(),a}addNode(e,n,r,o,s){let i=lo.create(this.top,e,n,r,o,s);i.contentDOM&&i.updateChildren(o,s+1),this.top.children.splice(this.index++,0,i),this.changed=!0}placeWidget(e,n,r){let o=this.index<this.top.children.length?this.top.children[this.index]:null;if(o&&o.matchesWidget(e)&&(e==o.widget||!o.widget.type.toDOM.parentNode))this.index++;else{let s=new bw(this.top,e,n,r);this.top.children.splice(this.index++,0,s),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],n=this.top;for(;e instanceof Yo;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof Pl)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((It||wt)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",n),this.addHackNode("BR",this.top))}addHackNode(e,n){if(n==this.top&&this.index<n.children.length&&n.children[this.index].matchesHack(e))this.index++;else{let r=document.createElement(e);e=="IMG"&&(r.className="ProseMirror-separator",r.alt=""),e=="BR"&&(r.className="ProseMirror-trailingBreak");let o=new Ew(this.top,[],r,null);n!=this.top?n.children.push(o):n.children.splice(this.index++,0,o),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function PD(t,e){let n=e,r=n.children.length,o=t.childCount,s=new Map,i=[];e:for(;o>0;){let a;for(;;)if(r){let c=n.children[r-1];if(c instanceof Yo)n=c,r=c.children.length;else{a=c,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let l=a.node;if(l){if(l!=t.child(o-1))break;--o,s.set(a,o),i.push(a)}}return{index:o,matched:s,matches:i.reverse()}}function DD(t,e){return t.type.side-e.type.side}function OD(t,e,n,r){let o=e.locals(t),s=0;if(o.length==0){for(let c=0;c<t.childCount;c++){let u=t.child(c);r(u,o,e.forChild(s,u),c),s+=u.nodeSize}return}let i=0,a=[],l=null;for(let c=0;;){let u,f;for(;i<o.length&&o[i].to==s;){let y=o[i++];y.widget&&(u?(f||(f=[u])).push(y):u=y)}if(u)if(f){f.sort(DD);for(let y=0;y<f.length;y++)n(f[y],c,!!l)}else n(u,c,!!l);let h,p;if(l)p=-1,h=l,l=null;else if(c<t.childCount)p=c,h=t.child(c++);else break;for(let y=0;y<a.length;y++)a[y].to<=s&&a.splice(y--,1);for(;i<o.length&&o[i].from<=s&&o[i].to>s;)a.push(o[i++]);let m=s+h.nodeSize;if(h.isText){let y=m;i<o.length&&o[i].from<y&&(y=o[i].from);for(let w=0;w<a.length;w++)a[w].to<y&&(y=a[w].to);y<m&&(l=h.cut(y-s),h=h.cut(0,y-s),m=y,p=-1)}else for(;i<o.length&&o[i].to<m;)i++;let g=h.isInline&&!h.isLeaf?a.filter(y=>!y.inline):a.slice();r(h,g,e.forChild(s,h),p),s=m}}function RD(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function zD(t,e,n,r){for(let o=0,s=0;o<t.childCount&&s<=r;){let i=t.child(o++),a=s;if(s+=i.nodeSize,!i.isText)continue;let l=i.text;for(;o<t.childCount;){let c=t.child(o++);if(s+=c.nodeSize,!c.isText)break;l+=c.text}if(s>=n){if(s>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let c=a<r?l.lastIndexOf(e,r-a-1):-1;if(c>=0&&c+e.length+a>=n)return a+c;if(n==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}function jd(t,e,n,r,o){let s=[];for(let i=0,a=0;i<t.length;i++){let l=t[i],c=a,u=a+=l.size;c>=n||u<=e?s.push(l):(c<e&&s.push(l.slice(0,e-c,r)),o&&(s.push(o),o=void 0),u>n&&s.push(l.slice(n-c,l.size,r)))}return s}function Zd(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let o=t.docView.nearestDesc(n.focusNode),s=o&&o.size==0,i=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(i<0)return null;let a=r.resolve(i),l,c;if(Nl(n)){for(l=i;o&&!o.node;)o=o.parent;let f=o.node;if(o&&f.isAtom&&oe.isSelectable(f)&&o.parent&&!(f.isInline&&uD(n.focusNode,n.focusOffset,o.dom))){let h=o.posBefore;c=new oe(i==h?a:r.resolve(h))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let f=i,h=i;for(let p=0;p<n.rangeCount;p++){let m=n.getRangeAt(p);f=Math.min(f,t.docView.posFromDOM(m.startContainer,m.startOffset,1)),h=Math.max(h,t.docView.posFromDOM(m.endContainer,m.endOffset,-1))}if(f<0)return null;[l,i]=h==t.state.selection.anchor?[h,f]:[f,h],a=r.resolve(i)}else l=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(l<0)return null}let u=r.resolve(l);if(!c){let f=e=="pointer"||t.state.selection.head<a.pos&&!s?1:-1;c=Yd(t,u,a,f)}return c}function Aw(t){return t.editable?t.hasFocus():Ow(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function Pr(t,e=!1){let n=t.state.selection;if(Nw(t,n),!!Aw(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&wt){let r=t.domSelectionRange(),o=t.domObserver.currentSelection;if(r.anchorNode&&o.anchorNode&&jo(r.anchorNode,r.anchorOffset,o.anchorNode,o.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)LD(t);else{let{anchor:r,head:o}=n,s,i;_w&&!(n instanceof ce)&&(n.$from.parent.inlineContent||(s=Iw(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(i=Iw(t,n.to))),t.docView.setSelection(r,o,t,e),_w&&(s&&Bw(s),i&&Bw(i)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&$D(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const _w=It||wt&&aw<63;function Iw(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),o=r<n.childNodes.length?n.childNodes[r]:null,s=r?n.childNodes[r-1]:null;if(It&&o&&o.contentEditable=="false")return Kd(o);if((!o||o.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(o)return Kd(o);if(s)return Kd(s)}}function Kd(t){return t.contentEditable="true",It&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function Bw(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function $D(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,o=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{(n.anchorNode!=r||n.anchorOffset!=o)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Aw(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function LD(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,_t(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&Qt&&io<=11&&(n.disabled=!0,n.disabled=!1)}function Nw(t,e){if(e instanceof oe){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(Pw(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else Pw(t)}function Pw(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function Yd(t,e,n,r){return t.someProp("createSelectionBetween",o=>o(t,e,n))||ce.between(e,n,r)}function Dw(t){return t.editable&&!t.hasFocus()?!1:Ow(t)}function Ow(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function VD(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return jo(e.node,e.offset,n.anchorNode,n.anchorOffset)}function qd(t,e){let{$anchor:n,$head:r}=t.selection,o=e>0?n.max(r):n.min(r),s=o.parent.inlineContent?o.depth?t.doc.resolve(e>0?o.after():o.before()):null:o;return s&&fe.findFrom(s,e)}function co(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function Rw(t,e,n){let r=t.state.selection;if(r instanceof ce)if(n.indexOf("s")>-1){let{$head:o}=r,s=o.textOffset?null:e<0?o.nodeBefore:o.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let i=t.state.doc.resolve(o.pos+s.nodeSize*(e<0?-1:1));return co(t,new ce(r.$anchor,i))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let o=qd(t.state,e);return o&&o instanceof oe?co(t,o):!1}else if(!(Mn&&n.indexOf("m")>-1)){let o=r.$head,s=o.textOffset?null:e<0?o.nodeBefore:o.nodeAfter,i;if(!s||s.isText)return!1;let a=e<0?o.pos-s.nodeSize:o.pos;return s.isAtom||(i=t.docView.descAt(a))&&!i.contentDOM?oe.isSelectable(s)?co(t,new oe(e<0?t.state.doc.resolve(o.pos-s.nodeSize):o)):ji?co(t,new ce(t.state.doc.resolve(e<0?a:a+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof oe&&r.node.isInline)return co(t,new ce(e>0?r.$to:r.$from));{let o=qd(t.state,e);return o?co(t,o):!1}}}function Ol(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function qi(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function qs(t,e){return e<0?FD(t):WD(t)}function FD(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,s,i=!1;for(Tn&&n.nodeType==1&&r<Ol(n)&&qi(n.childNodes[r],-1)&&(i=!0);;)if(r>0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(qi(a,-1))o=n,s=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(zw(n))break;{let a=n.previousSibling;for(;a&&qi(a,-1);)o=n.parentNode,s=_t(a),a=a.previousSibling;if(a)n=a,r=Ol(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}i?Xd(t,n,r):o&&Xd(t,o,s)}function WD(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o=Ol(n),s,i;for(;;)if(r<o){if(n.nodeType!=1)break;let a=n.childNodes[r];if(qi(a,1))s=n,i=++r;else break}else{if(zw(n))break;{let a=n.nextSibling;for(;a&&qi(a,1);)s=a.parentNode,i=_t(a)+1,a=a.nextSibling;if(a)n=a,r=0,o=Ol(n);else{if(n=n.parentNode,n==t.dom)break;r=o=0}}}s&&Xd(t,s,i)}function zw(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function UD(t,e){for(;t&&e==t.childNodes.length&&!Hi(t);)e=_t(t)+1,t=t.parentNode;for(;t&&e<t.childNodes.length;){let n=t.childNodes[e];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=0}}function HD(t,e){for(;t&&!e&&!Hi(t);)e=_t(t),t=t.parentNode;for(;t&&e;){let n=t.childNodes[e-1];if(n.nodeType==3)return n;if(n.nodeType==1&&n.contentEditable=="false")break;t=n,e=t.childNodes.length}}function Xd(t,e,n){if(e.nodeType!=3){let s,i;(i=UD(e,n))?(e=i,n=0):(s=HD(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(Nl(r)){let s=document.createRange();s.setEnd(e,n),s.setStart(e,n),r.removeAllRanges(),r.addRange(s)}else r.extend&&r.extend(e,n);t.domObserver.setCurSelection();let{state:o}=t;setTimeout(()=>{t.state==o&&Pr(t)},50)}function $w(t,e){let n=t.state.doc.resolve(e);if(!(wt||lw)&&n.parent.inlineContent){let o=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),i=(s.top+s.bottom)/2;if(i>o.top&&i<o.bottom&&Math.abs(s.left-o.left)>1)return s.left<o.left?"ltr":"rtl"}if(e<n.end()){let s=t.coordsAtPos(e+1),i=(s.top+s.bottom)/2;if(i>o.top&&i<o.bottom&&Math.abs(s.left-o.left)>1)return s.left>o.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function Lw(t,e,n){let r=t.state.selection;if(r instanceof ce&&!r.empty||n.indexOf("s")>-1||Mn&&n.indexOf("m")>-1)return!1;let{$from:o,$to:s}=r;if(!o.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let i=qd(t.state,e);if(i&&i instanceof oe)return co(t,i)}if(!o.parent.inlineContent){let i=e<0?o:s,a=r instanceof fn?fe.near(i,e):fe.findFrom(i,e);return a?co(t,a):!1}return!1}function Vw(t,e){if(!(t.state.selection instanceof ce))return!0;let{$head:n,$anchor:r,empty:o}=t.state.selection;if(!n.sameParent(r))return!0;if(!o)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let i=t.state.tr;return e<0?i.delete(n.pos-s.nodeSize,n.pos):i.delete(n.pos,n.pos+s.nodeSize),t.dispatch(i),!0}return!1}function Fw(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function jD(t){if(!It||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Fw(t,r,"true"),setTimeout(()=>Fw(t,r,"false"),20)}return!1}function ZD(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function KD(t,e){let n=e.keyCode,r=ZD(e);if(n==8||Mn&&n==72&&r=="c")return Vw(t,-1)||qs(t,-1);if(n==46&&!e.shiftKey||Mn&&n==68&&r=="c")return Vw(t,1)||qs(t,1);if(n==13||n==27)return!0;if(n==37||Mn&&n==66&&r=="c"){let o=n==37?$w(t,t.state.selection.from)=="ltr"?-1:1:-1;return Rw(t,o,r)||qs(t,o)}else if(n==39||Mn&&n==70&&r=="c"){let o=n==39?$w(t,t.state.selection.from)=="ltr"?1:-1:1;return Rw(t,o,r)||qs(t,o)}else{if(n==38||Mn&&n==80&&r=="c")return Lw(t,-1,r)||qs(t,-1);if(n==40||Mn&&n==78&&r=="c")return jD(t)||Lw(t,1,r)||qs(t,1);if(r==(Mn?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function Gd(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:o,openEnd:s}=e;for(;o>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){o--,s--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let i=t.someProp("clipboardSerializer")||Wo.fromSchema(t.state.schema),a=qw(),l=a.createElement("div");l.appendChild(i.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=Kw[c.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let m=a.createElement(u[p]);for(;l.firstChild;)m.appendChild(l.firstChild);l.appendChild(m),f++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${o} ${s}${f?` -${f}`:""} ${JSON.stringify(n)}`);let h=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,`
76
+
77
+ `);return{dom:l,text:h,slice:e}}function Ww(t,e,n,r,o){let s=o.parent.type.spec.code,i,a;if(!n&&!e)return null;let l=!!e&&(r||s||!n);if(l){if(t.someProp("transformPastedText",h=>{e=h(e,s||r,t)}),s)return a=new Z(D.from(t.state.schema.text(e.replace(/\r\n?/g,`
78
+ `))),0,0),t.someProp("transformPasted",h=>{a=h(a,t,!0)}),a;let f=t.someProp("clipboardTextParser",h=>h(e,o,r,t));if(f)a=f;else{let h=o.marks(),{schema:p}=t.state,m=Wo.fromSchema(p);i=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(g=>{let y=i.appendChild(document.createElement("p"));g&&y.appendChild(m.serializeNode(p.text(g,h)))})}}else t.someProp("transformPastedHTML",f=>{n=f(n,t)}),i=GD(n),ji&&JD(i);let c=i&&i.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let f=+u[3];f>0;f--){let h=i.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;i=h}if(a||(a=(t.someProp("clipboardParser")||t.someProp("domParser")||Ar.fromSchema(t.state.schema)).parseSlice(i,{preserveWhitespace:!!(l||u),context:o,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!YD.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)a=QD(Zw(a,+u[1],+u[2]),u[4]);else if(a=Z.maxOpen(qD(a.content,o),!0),a.openStart||a.openEnd){let f=0,h=0;for(let p=a.content.firstChild;f<a.openStart&&!p.type.spec.isolating;f++,p=p.firstChild);for(let p=a.content.lastChild;h<a.openEnd&&!p.type.spec.isolating;h++,p=p.lastChild);a=Zw(a,f,h)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}const YD=/^(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 qD(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let o=e.node(n).contentMatchAt(e.index(n)),s,i=[];if(t.forEach(a=>{if(!i)return;let l=o.findWrapping(a.type),c;if(!l)return i=null;if(c=i.length&&s.length&&Hw(l,s,a,i[i.length-1],0))i[i.length-1]=c;else{i.length&&(i[i.length-1]=jw(i[i.length-1],s.length));let u=Uw(a,l);i.push(u),o=o.matchType(u.type),s=l}}),i)return D.from(i)}return t}function Uw(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,D.from(t));return t}function Hw(t,e,n,r,o){if(o<t.length&&o<e.length&&t[o]==e[o]){let s=Hw(t,e,n,r.lastChild,o+1);if(s)return r.copy(r.content.replaceChild(r.childCount-1,s));if(r.contentMatchAt(r.childCount).matchType(o==t.length-1?n.type:t[o+1]))return r.copy(r.content.append(D.from(Uw(n,t,o+1))))}}function jw(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,jw(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(D.empty,!0);return t.copy(n.append(r))}function Jd(t,e,n,r,o,s){let i=e<0?t.firstChild:t.lastChild,a=i.content;return t.childCount>1&&(s=0),o<r-1&&(a=Jd(a,e,n,r,o+1,s)),o>=n&&(a=e<0?i.contentMatchAt(0).fillBefore(a,s<=o).append(a):a.append(i.contentMatchAt(i.childCount).fillBefore(D.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,i.copy(a))}function Zw(t,e,n){return e<t.openStart&&(t=new Z(Jd(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new Z(Jd(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Kw={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};let Yw=null;function qw(){return Yw||(Yw=document.implementation.createHTMLDocument("title"))}let Qd=null;function XD(t){let e=window.trustedTypes;return e?(Qd||(Qd=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),Qd.createHTML(t)):t}function GD(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=qw().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),o;if((o=r&&Kw[r[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=XD(t),o)for(let s=0;s<o.length;s++)n=n.querySelector(o[s])||n;return n}function JD(t){let e=t.querySelectorAll(wt?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];r.childNodes.length==1&&r.textContent==" "&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}function QD(t,e){if(!t.size)return t;let n=t.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return t}let{content:o,openStart:s,openEnd:i}=t;for(let a=r.length-2;a>=0;a-=2){let l=n.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;o=D.from(l.create(r[a+1],o)),s++,i++}return new Z(o,s,i)}const Ut={},Ht={},eO={touchstart:!0,touchmove:!0};class tO{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},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.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function nO(t){for(let e in Ut){let n=Ut[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{oO(t,r)&&!tf(t,r)&&(t.editable||!(r.type in Ht))&&n(t,r)},eO[e]?{passive:!0}:void 0)}It&&t.dom.addEventListener("input",()=>null),ef(t)}function uo(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function rO(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function ef(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>tf(t,r))})}function tf(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function oO(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function sO(t,e){!tf(t,e)&&Ut[e.type]&&(t.editable||!(e.type in Ht))&&Ut[e.type](t,e)}Ht.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Gw(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Br&&wt&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Ks&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();t.input.lastIOSEnter=r,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==r&&(t.someProp("handleKeyDown",o=>o(t,Zo(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||KD(t,n)?n.preventDefault():uo(t,"key")},Ht.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)},Ht.keypress=(t,e)=>{let n=e;if(Gw(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Mn&&n.metaKey)return;if(t.someProp("handleKeyPress",o=>o(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof ce)||!r.$from.sameParent(r.$to)){let o=String.fromCharCode(n.charCode),s=()=>t.state.tr.insertText(o).scrollIntoView();!/[\r\n]/.test(o)&&!t.someProp("handleTextInput",i=>i(t,r.$from.pos,r.$to.pos,o,s))&&t.dispatch(s()),n.preventDefault()}};function Rl(t){return{left:t.clientX,top:t.clientY}}function iO(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function nf(t,e,n,r,o){if(r==-1)return!1;let s=t.state.doc.resolve(r);for(let i=s.depth+1;i>0;i--)if(t.someProp(e,a=>i>s.depth?a(t,n,s.nodeAfter,s.before(i),o,!0):a(t,n,s.node(i),s.before(i),o,!1)))return!0;return!1}function Xs(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);r.setMeta("pointer",!0),t.dispatch(r)}function aO(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&oe.isSelectable(r)?(Xs(t,new oe(n)),!0):!1}function lO(t,e){if(e==-1)return!1;let n=t.state.selection,r,o;n instanceof oe&&(r=n.node);let s=t.state.doc.resolve(e);for(let i=s.depth+1;i>0;i--){let a=i>s.depth?s.nodeAfter:s.node(i);if(oe.isSelectable(a)){r&&n.$from.depth>0&&i>=n.$from.depth&&s.before(n.$from.depth+1)==n.$from.pos?o=s.before(n.$from.depth):o=s.before(i);break}}return o!=null?(Xs(t,oe.create(t.state.doc,o)),!0):!1}function cO(t,e,n,r,o){return nf(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(o?lO(t,n):aO(t,n))}function uO(t,e,n,r){return nf(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",o=>o(t,e,r))}function dO(t,e,n,r){return nf(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",o=>o(t,e,r))||fO(t,n,r)}function fO(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(Xs(t,ce.create(r,0,r.content.size)),!0):!1;let o=r.resolve(e);for(let s=o.depth+1;s>0;s--){let i=s>o.depth?o.nodeAfter:o.node(s),a=o.before(s);if(i.inlineContent)Xs(t,ce.create(r,a+1,a+1+i.content.size));else if(oe.isSelectable(i))Xs(t,oe.create(r,a));else continue;return!0}}function rf(t){return zl(t)}const Xw=Mn?"metaKey":"ctrlKey";Ut.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=rf(t),o=Date.now(),s="singleClick";o-t.input.lastClick.time<500&&iO(n,t.input.lastClick)&&!n[Xw]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?s="doubleClick":t.input.lastClick.type=="doubleClick"&&(s="tripleClick")),t.input.lastClick={time:o,x:n.clientX,y:n.clientY,type:s,button:n.button};let i=t.posAtCoords(Rl(n));i&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new hO(t,i,n,!!r)):(s=="doubleClick"?uO:dO)(t,i.pos,i.inside,n)?n.preventDefault():uo(t,"pointer"))};class hO{constructor(e,n,r,o){this.view=e,this.pos=n,this.event=r,this.flushed=o,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[Xw],this.allowDefault=r.shiftKey;let s,i;if(n.inside>-1)s=e.state.doc.nodeAt(n.inside),i=n.inside;else{let u=e.state.doc.resolve(n.pos);s=u.parent,i=u.depth?u.before():0}const a=o?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;(r.button==0&&s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof oe&&c.from<=i&&c.to>i)&&(this.mightDrag={node:s,pos:i,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Tn&&!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)),uo(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(()=>Pr(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Rl(e))),this.updateAllowDefault(e),this.allowDefault||!n?uo(this.view,"pointer"):cO(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||It&&this.mightDrag&&!this.mightDrag.node.isAtom||wt&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(Xs(this.view,fe.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):uo(this.view,"pointer")}move(e){this.updateAllowDefault(e),uo(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)}}Ut.touchstart=t=>{t.input.lastTouch=Date.now(),rf(t),uo(t,"pointer")},Ut.touchmove=t=>{t.input.lastTouch=Date.now(),uo(t,"pointer")},Ut.contextmenu=t=>rf(t);function Gw(t,e){return t.composing?!0:It&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const pO=Br?5e3:-1;Ht.compositionstart=Ht.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof ce&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||wt&&lw&&mO(t)))t.markCursor=t.state.storedMarks||n.marks(),zl(t,!0),t.markCursor=null;else if(zl(t,!e.selection.empty),Tn&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=t.domSelectionRange();for(let o=r.focusNode,s=r.focusOffset;o&&o.nodeType==1&&s!=0;){let i=s<0?o.lastChild:o.childNodes[s-1];if(!i)break;if(i.nodeType==3){let a=t.domSelection();a&&a.collapse(i,i.nodeValue.length);break}else o=i,s=-1}}t.input.composing=!0}Jw(t,pO)};function mO(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Ht.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,Jw(t,20))};function Jw(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>zl(t),e))}function Qw(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=yO());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function gO(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=lD(e.focusNode,e.focusOffset),r=cD(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let o=r.pmViewDesc,s=t.domObserver.lastChangedTextNode;if(n==s||r==s)return s;if(!o||!o.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let i=n.pmViewDesc;if(!(!i||!i.isText(n.nodeValue)))return r}}return n||r}function yO(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function zl(t,e=!1){if(!(Br&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),Qw(t),e||t.docView&&t.docView.dirty){let n=Zd(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function wO(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),o=document.createRange();o.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(o),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const Xi=Qt&&io<15||Ks&&hD<604;Ut.copy=Ht.cut=(t,e)=>{let n=e,r=t.state.selection,o=n.type=="cut";if(r.empty)return;let s=Xi?null:n.clipboardData,i=r.content(),{dom:a,text:l}=Gd(t,i);s?(n.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",l)):wO(t,a),o&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function kO(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function vO(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let o=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?Gi(t,r.value,null,o,e):Gi(t,r.textContent,r.innerHTML,o,e)},50)}function Gi(t,e,n,r,o){let s=Ww(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,o,s||Z.empty)))return!0;if(!s)return!1;let i=kO(s),a=i?t.state.tr.replaceSelectionWith(i,r):t.state.tr.replaceSelection(s);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function e1(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Ht.paste=(t,e)=>{let n=e;if(t.composing&&!Br)return;let r=Xi?null:n.clipboardData,o=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&Gi(t,e1(r),r.getData("text/html"),o,n)?n.preventDefault():vO(t,n)};class t1{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const bO=Mn?"altKey":"ctrlKey";function n1(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[bO]}Ut.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let o=t.state.selection,s=o.empty?null:t.posAtCoords(Rl(n)),i;if(!(s&&s.pos>=o.from&&s.pos<=(o instanceof oe?o.to-1:o.to))){if(r&&r.mightDrag)i=oe.create(t.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let f=t.docView.nearestDesc(n.target,!0);f&&f.node.type.spec.draggable&&f!=t.docView&&(i=oe.create(t.state.doc,f.posBefore))}}let a=(i||t.state.selection).content(),{dom:l,text:c,slice:u}=Gd(t,a);(!n.dataTransfer.files.length||!wt||aw>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Xi?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Xi||n.dataTransfer.setData("text/plain",c),t.dragging=new t1(u,n1(t,n),i)},Ut.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)},Ht.dragover=Ht.dragenter=(t,e)=>e.preventDefault(),Ht.drop=(t,e)=>{try{SO(t,e,t.dragging)}finally{t.dragging=null}};function SO(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Rl(e));if(!r)return;let o=t.state.doc.resolve(r.pos),s=n&&n.slice;s?t.someProp("transformPasted",p=>{s=p(s,t,!1)}):s=Ww(t,e1(e.dataTransfer),Xi?null:e.dataTransfer.getData("text/html"),!1,o);let i=!!(n&&n1(t,e));if(t.someProp("handleDrop",p=>p(t,e,s||Z.empty,i))){e.preventDefault();return}if(!s)return;e.preventDefault();let a=s?B0(t.state.doc,o.pos,s):o.pos;a==null&&(a=o.pos);let l=t.state.tr;if(i){let{node:p}=n;p?p.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,f=l.doc;if(u?l.replaceRangeWith(c,c,s.content.firstChild):l.replaceRange(c,c,s),l.doc.eq(f))return;let h=l.doc.resolve(c);if(u&&oe.isSelectable(s.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(s.content.firstChild))l.setSelection(new oe(h));else{let p=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((m,g,y,w)=>p=w),l.setSelection(Yd(t,h,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}Ut.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Pr(t)},20))},Ut.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)},Ut.beforeinput=(t,e)=>{if(wt&&Br&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:r}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=r||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",s=>s(t,Zo(8,"Backspace")))))return;let{$cursor:o}=t.state.selection;o&&o.pos>0&&t.dispatch(t.state.tr.delete(o.pos-1,o.pos).scrollIntoView())},50)}};for(let t in Ht)Ut[t]=Ht[t];function Ji(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class $l{constructor(e,n){this.toDOM=e,this.spec=n||Xo,this.side=this.spec.side||0}map(e,n,r,o){let{pos:s,deleted:i}=e.mapResult(n.from+o,this.side<0?-1:1);return i?null:new jt(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof $l&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Ji(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class fo{constructor(e,n){this.attrs=e,this.spec=n||Xo}map(e,n,r,o){let s=e.map(n.from+o,this.spec.inclusiveStart?-1:1)-r,i=e.map(n.to+o,this.spec.inclusiveEnd?1:-1)-r;return s>=i?null:new jt(s,i,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof fo&&Ji(this.attrs,e.attrs)&&Ji(this.spec,e.spec)}static is(e){return e.type instanceof fo}destroy(){}}class of{constructor(e,n){this.attrs=e,this.spec=n||Xo}map(e,n,r,o){let s=e.mapResult(n.from+o,1);if(s.deleted)return null;let i=e.mapResult(n.to+o,-1);return i.deleted||i.pos<=s.pos?null:new jt(s.pos-r,i.pos-r,this)}valid(e,n){let{index:r,offset:o}=e.content.findIndex(n.from),s;return o==n.from&&!(s=e.child(r)).isText&&o+s.nodeSize==n.to}eq(e){return this==e||e instanceof of&&Ji(this.attrs,e.attrs)&&Ji(this.spec,e.spec)}destroy(){}}class jt{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new jt(e,n,this.type)}eq(e,n=0){return this.type.eq(e.type)&&this.from+n==e.from&&this.to+n==e.to}map(e,n,r){return this.type.map(e,this,n,r)}static widget(e,n,r){return new jt(e,e,new $l(n,r))}static inline(e,n,r,o){return new jt(e,n,new fo(r,o))}static node(e,n,r,o){return new jt(e,n,new of(r,o))}get spec(){return this.type.spec}get inline(){return this.type instanceof fo}get widget(){return this.type instanceof $l}}const Gs=[],Xo={};class je{constructor(e,n){this.local=e.length?e:Gs,this.children=n.length?n:Gs}static create(e,n){return n.length?Ll(n,e,0,Xo):zt}find(e,n,r){let o=[];return this.findInner(e??0,n??1e9,o,0,r),o}findInner(e,n,r,o,s){for(let i=0;i<this.local.length;i++){let a=this.local[i];a.from<=n&&a.to>=e&&(!s||s(a.spec))&&r.push(a.copy(a.from+o,a.to+o))}for(let i=0;i<this.children.length;i+=3)if(this.children[i]<n&&this.children[i+1]>e){let a=this.children[i]+1;this.children[i+2].findInner(e-a,n-a,r,o+a,s)}}map(e,n,r){return this==zt||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Xo)}mapInner(e,n,r,o,s){let i;for(let a=0;a<this.local.length;a++){let l=this.local[a].map(e,r,o);l&&l.type.valid(n,l)?(i||(i=[])).push(l):s.onRemove&&s.onRemove(this.local[a].spec)}return this.children.length?EO(this.children,i||[],e,n,r,o,s):i?new je(i.sort(Go),Gs):zt}add(e,n){return n.length?this==zt?je.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let o,s=0;e.forEach((a,l)=>{let c=l+r,u;if(u=o1(n,a,c)){for(o||(o=this.children.slice());s<o.length&&o[s]<l;)s+=3;o[s]==l?o[s+2]=o[s+2].addInner(a,u,c+1):o.splice(s,0,l,l+a.nodeSize,Ll(u,a,c+1,Xo)),s+=3}});let i=r1(s?s1(n):n,-r);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||i.splice(a--,1);return new je(i.length?this.local.concat(i).sort(Go):this.local,o||this.children)}remove(e){return e.length==0||this==zt?this:this.removeInner(e,0)}removeInner(e,n){let r=this.children,o=this.local;for(let s=0;s<r.length;s+=3){let i,a=r[s]+n,l=r[s+1]+n;for(let u=0,f;u<e.length;u++)(f=e[u])&&f.from>a&&f.to<l&&(e[u]=null,(i||(i=[])).push(f));if(!i)continue;r==this.children&&(r=this.children.slice());let c=r[s+2].removeInner(i,a+1);c!=zt?r[s+2]=c:(r.splice(s,3),s-=3)}if(o.length){for(let s=0,i;s<e.length;s++)if(i=e[s])for(let a=0;a<o.length;a++)o[a].eq(i,n)&&(o==this.local&&(o=this.local.slice()),o.splice(a--,1))}return r==this.children&&o==this.local?this:o.length||r.length?new je(o,r):zt}forChild(e,n){if(this==zt)return this;if(n.isLeaf)return je.empty;let r,o;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(r=this.children[a+2]);break}let s=e+1,i=s+n.content.size;for(let a=0;a<this.local.length;a++){let l=this.local[a];if(l.from<i&&l.to>s&&l.type instanceof fo){let c=Math.max(s,l.from)-s,u=Math.min(i,l.to)-s;c<u&&(o||(o=[])).push(l.copy(c,u))}}if(o){let a=new je(o.sort(Go),Gs);return r?new ho([a,r]):a}return r||zt}eq(e){if(this==e)return!0;if(!(e instanceof je)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let n=0;n<this.local.length;n++)if(!this.local[n].eq(e.local[n]))return!1;for(let n=0;n<this.children.length;n+=3)if(this.children[n]!=e.children[n]||this.children[n+1]!=e.children[n+1]||!this.children[n+2].eq(e.children[n+2]))return!1;return!0}locals(e){return sf(this.localsInner(e))}localsInner(e){if(this==zt)return Gs;if(e.inlineContent||!this.local.some(fo.is))return this.local;let n=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof fo||n.push(this.local[r]);return n}forEachSet(e){e(this)}}je.empty=new je([],[]),je.removeOverlap=sf;const zt=je.empty;class ho{constructor(e){this.members=e}map(e,n){const r=this.members.map(o=>o.map(e,n,Xo));return ho.from(r)}forChild(e,n){if(n.isLeaf)return je.empty;let r=[];for(let o=0;o<this.members.length;o++){let s=this.members[o].forChild(e,n);s!=zt&&(s instanceof ho?r=r.concat(s.members):r.push(s))}return ho.from(r)}eq(e){if(!(e instanceof ho)||e.members.length!=this.members.length)return!1;for(let n=0;n<this.members.length;n++)if(!this.members[n].eq(e.members[n]))return!1;return!0}locals(e){let n,r=!0;for(let o=0;o<this.members.length;o++){let s=this.members[o].localsInner(e);if(s.length)if(!n)n=s;else{r&&(n=n.slice(),r=!1);for(let i=0;i<s.length;i++)n.push(s[i])}}return n?sf(r?n:n.sort(Go)):Gs}static from(e){switch(e.length){case 0:return zt;case 1:return e[0];default:return new ho(e.every(n=>n instanceof je)?e:e.reduce((n,r)=>n.concat(r instanceof je?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function EO(t,e,n,r,o,s,i){let a=t.slice();for(let c=0,u=s;c<n.maps.length;c++){let f=0;n.maps[c].forEach((h,p,m,g)=>{let y=g-m-(p-h);for(let w=0;w<a.length;w+=3){let k=a[w+1];if(k<0||h>k+u-f)continue;let b=a[w]+u-f;p>=b?a[w+1]=h<=b?-2:-1:h>=u&&y&&(a[w]+=y,a[w+1]+=y)}f+=y}),u=n.maps[c].map(u,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(a[c+1]==-2){l=!0,a[c+1]=-1;continue}let u=n.map(t[c]+s),f=u-o;if(f<0||f>=r.content.size){l=!0;continue}let h=n.map(t[c+1]+s,-1),p=h-o,{index:m,offset:g}=r.content.findIndex(f),y=r.maybeChild(m);if(y&&g==f&&g+y.nodeSize==p){let w=a[c+2].mapInner(n,y,u+1,t[c]+s+1,i);w!=zt?(a[c]=f,a[c+1]=p,a[c+2]=w):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=CO(a,t,e,n,o,s,i),u=Ll(c,r,0,i);e=u.local;for(let f=0;f<a.length;f+=3)a[f+1]<0&&(a.splice(f,3),f-=3);for(let f=0,h=0;f<u.children.length;f+=3){let p=u.children[f];for(;h<a.length&&a[h]<p;)h+=3;a.splice(h,0,u.children[f],u.children[f+1],u.children[f+2])}}return new je(e.sort(Go),a)}function r1(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let o=t[r];n.push(new jt(o.from+e,o.to+e,o.type))}return n}function CO(t,e,n,r,o,s,i){function a(l,c){for(let u=0;u<l.local.length;u++){let f=l.local[u].map(r,o,c);f?n.push(f):i.onRemove&&i.onRemove(l.local[u].spec)}for(let u=0;u<l.children.length;u+=3)a(l.children[u+2],l.children[u]+c+1)}for(let l=0;l<t.length;l+=3)t[l+1]==-1&&a(t[l+2],e[l]+s+1);return n}function o1(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,o=null;for(let s=0,i;s<t.length;s++)(i=t[s])&&i.from>n&&i.to<r&&((o||(o=[])).push(i),t[s]=null);return o}function s1(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Ll(t,e,n,r){let o=[],s=!1;e.forEach((a,l)=>{let c=o1(t,a,l+n);if(c){s=!0;let u=Ll(c,a,n+l+1,r);u!=zt&&o.push(l,l+a.nodeSize,u)}});let i=r1(s?s1(t):t,-n).sort(Go);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||(r.onRemove&&r.onRemove(i[a].spec),i.splice(a--,1));return i.length||o.length?new je(i,o):zt}function Go(t,e){return t.from-e.from||t.to-e.to}function sf(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let o=n+1;o<e.length;o++){let s=e[o];if(s.from==r.from){s.to!=r.to&&(e==t&&(e=t.slice()),e[o]=s.copy(s.from,r.to),i1(e,o+1,s.copy(r.to,s.to)));continue}else{s.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,s.from),i1(e,o,r.copy(s.from,r.to)));break}}}return e}function i1(t,e,n){for(;e<t.length&&Go(n,t[e])>0;)e++;t.splice(e,0,n)}function af(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=zt&&e.push(r)}),t.cursorWrapper&&e.push(je.create(t.state.doc,[t.cursorWrapper.deco])),ho.from(e)}const xO={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},TO=Qt&&io<=11;class MO{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 AO{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new MO,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let o=0;o<r.length;o++)this.queue.push(r[o]);Qt&&io<=11&&r.some(o=>o.type=="childList"&&o.removedNodes.length||o.type=="characterData"&&o.oldValue.length>o.target.nodeValue.length)?this.flushSoon():It&&e.composing&&r.some(o=>o.type=="childList"&&o.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),TO&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.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,xO)),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 n=0;n<e.length;n++)this.queue.push(e[n]);window.setTimeout(()=>this.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(Dw(this.view)){if(this.suppressingSelectionUpdates)return Pr(this.view);if(Qt&&io<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&jo(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 n=new Set,r;for(let s=e.focusNode;s;s=Zs(s))n.add(s);for(let s=e.anchorNode;s;s=Zs(s))if(n.has(s)){r=s;break}let o=r&&this.view.docView.nearestDesc(r);if(o&&o.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))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 n=this.pendingRecords();n.length&&(this.queue=[]);let r=e.domSelectionRange(),o=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Dw(e)&&!this.ignoreSelectionChange(r),s=-1,i=-1,a=!1,l=[];if(e.editable)for(let u=0;u<n.length;u++){let f=this.registerMutation(n[u],l);f&&(s=s<0?f.from:Math.min(f.from,s),i=i<0?f.to:Math.max(f.to,i),f.typeOver&&(a=!0))}if(Tn&&l.length){let u=l.filter(f=>f.nodeName=="BR");if(u.length==2){let[f,h]=u;f.parentNode&&f.parentNode.parentNode==h.parentNode?h.remove():f.remove()}else{let{focusNode:f}=this.currentSelection;for(let h of u){let p=h.parentNode;p&&p.nodeName=="LI"&&(!f||BO(e,f)!=p)&&h.remove()}}}else if((wt||It)&&l.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let f=u.nextSibling;f&&f.nodeType==1&&f.contentEditable=="false"&&u.parentNode.removeChild(u)}}let c=null;s<0&&o&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Nl(r)&&(c=Zd(e))&&c.eq(fe.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Pr(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||o)&&(s>-1&&(e.docView.markDirty(s,i),_O(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,NO(e,l)),this.handleDOMChange(s,i,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Pr(e),this.currentSelection.set(r))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let f=e.addedNodes[u];n.push(f),f.nodeType==3&&(this.lastChangedTextNode=f)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let o=e.previousSibling,s=e.nextSibling;if(Qt&&io<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:f,nextSibling:h}=e.addedNodes[u];(!f||Array.prototype.indexOf.call(e.addedNodes,f)<0)&&(o=f),(!h||Array.prototype.indexOf.call(e.addedNodes,h)<0)&&(s=h)}let i=o&&o.parentNode==e.target?_t(o)+1:0,a=r.localPosFromDOM(e.target,i,-1),l=s&&s.parentNode==e.target?_t(s):e.target.childNodes.length,c=r.localPosFromDOM(e.target,l,1);return{from:a,to:c}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let a1=new WeakMap,l1=!1;function _O(t){if(!a1.has(t)&&(a1.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=Tn,l1)return;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."),l1=!0}}function c1(t,e){let n=e.startContainer,r=e.startOffset,o=e.endContainer,s=e.endOffset,i=t.domAtPos(t.state.selection.anchor);return jo(i.node,i.offset,o,s)&&([n,r,o,s]=[o,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:o,focusOffset:s}}function IO(t,e){if(e.getComposedRanges){let o=e.getComposedRanges(t.root)[0];if(o)return c1(t,o)}let n;function r(o){o.preventDefault(),o.stopImmediatePropagation(),n=o.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?c1(t,n):null}function BO(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let r=t.docView.nearestDesc(n,!0);if(r&&r.node.isBlock)return n}return null}function NO(t,e){var n;let{focusNode:r,focusOffset:o}=t.domSelectionRange();for(let s of e)if(((n=s.parentNode)===null||n===void 0?void 0:n.nodeName)=="TR"){let i=s.nextSibling;for(;i&&i.nodeName!="TD"&&i.nodeName!="TH";)i=i.nextSibling;if(i){let a=i;for(;;){let l=a.firstChild;if(!l||l.nodeType!=1||l.contentEditable=="false"||/^(BR|IMG)$/.test(l.nodeName))break;a=l}a.insertBefore(s,a.firstChild),r==s&&t.domSelection().collapse(s,o)}else s.parentNode.removeChild(s)}}function PO(t,e,n){let{node:r,fromOffset:o,toOffset:s,from:i,to:a}=t.docView.parseRange(e,n),l=t.domSelectionRange(),c,u=l.anchorNode;if(u&&t.dom.contains(u.nodeType==1?u:u.parentNode)&&(c=[{node:u,offset:l.anchorOffset}],Nl(l)||c.push({node:l.focusNode,offset:l.focusOffset})),wt&&t.input.lastKeyCode===8)for(let y=s;y>o;y--){let w=r.childNodes[y-1],k=w.pmViewDesc;if(w.nodeName=="BR"&&!k){s=y;break}if(!k||k.size)break}let f=t.state.doc,h=t.someProp("domParser")||Ar.fromSchema(t.state.schema),p=f.resolve(i),m=null,g=h.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:o,to:s,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:DO,context:p});if(c&&c[0].pos!=null){let y=c[0].pos,w=c[1]&&c[1].pos;w==null&&(w=y),m={anchor:y+i,head:w+i}}return{doc:g,sel:m,from:i,to:a}}function DO(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(It&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||It&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const OO=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function RO(t,e,n,r,o){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let T=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,_=Zd(t,T);if(_&&!t.state.selection.eq(_)){if(wt&&Br&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",z=>z(t,Zo(13,"Enter"))))return;let I=t.state.tr.setSelection(_);T=="pointer"?I.setMeta("pointer",!0):T=="key"&&I.scrollIntoView(),s&&I.setMeta("composition",s),t.dispatch(I)}return}let i=t.state.doc.resolve(e),a=i.sharedDepth(n);e=i.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l=t.state.selection,c=PO(t,e,n),u=t.state.doc,f=u.slice(c.from,c.to),h,p;t.input.lastKeyCode===8&&Date.now()-100<t.input.lastKeyCodeTime?(h=t.state.selection.to,p="end"):(h=t.state.selection.from,p="start"),t.input.lastKeyCode=null;let m=LO(f.content,c.doc.content,c.from,h,p);if(m&&t.input.domChangeCount++,(Ks&&t.input.lastIOSEnter>Date.now()-225||Br)&&o.some(T=>T.nodeType==1&&!OO.test(T.nodeName))&&(!m||m.endA>=m.endB)&&t.someProp("handleKeyDown",T=>T(t,Zo(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!m)if(r&&l instanceof ce&&!l.empty&&l.$head.sameParent(l.$anchor)&&!t.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))m={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let T=u1(t,t.state.doc,c.sel);if(T&&!T.eq(t.state.selection)){let _=t.state.tr.setSelection(T);s&&_.setMeta("composition",s),t.dispatch(_)}}return}t.state.selection.from<t.state.selection.to&&m.start==m.endB&&t.state.selection instanceof ce&&(m.start>t.state.selection.from&&m.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?m.start=t.state.selection.from:m.endA<t.state.selection.to&&m.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(m.endB+=t.state.selection.to-m.endA,m.endA=t.state.selection.to)),Qt&&io<=11&&m.endB==m.start+1&&m.endA==m.start&&m.start>c.from&&c.doc.textBetween(m.start-c.from-1,m.start-c.from+1)=="  "&&(m.start--,m.endA--,m.endB--);let g=c.doc.resolveNoCache(m.start-c.from),y=c.doc.resolveNoCache(m.endB-c.from),w=u.resolve(m.start),k=g.sameParent(y)&&g.parent.inlineContent&&w.end()>=m.endA;if((Ks&&t.input.lastIOSEnter>Date.now()-225&&(!k||o.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!k&&g.pos<c.doc.content.size&&(!g.sameParent(y)||!g.parent.inlineContent)&&g.pos<y.pos&&!/\S/.test(c.doc.textBetween(g.pos,y.pos,"","")))&&t.someProp("handleKeyDown",T=>T(t,Zo(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>m.start&&$O(u,m.start,m.endA,g,y)&&t.someProp("handleKeyDown",T=>T(t,Zo(8,"Backspace")))){Br&&wt&&t.domObserver.suppressSelectionUpdates();return}wt&&m.endB==m.start&&(t.input.lastChromeDelete=Date.now()),Br&&!k&&g.start()!=y.start()&&y.parentOffset==0&&g.depth==y.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==m.endA&&(m.endB-=2,y=c.doc.resolveNoCache(m.endB-c.from),setTimeout(()=>{t.someProp("handleKeyDown",function(T){return T(t,Zo(13,"Enter"))})},20));let b=m.start,S=m.endA,v=T=>{let _=T||t.state.tr.replace(b,S,c.doc.slice(m.start-c.from,m.endB-c.from));if(c.sel){let I=u1(t,_.doc,c.sel);I&&!(wt&&t.composing&&I.empty&&(m.start!=m.endB||t.input.lastChromeDelete<Date.now()-100)&&(I.head==b||I.head==_.mapping.map(S)-1)||Qt&&I.empty&&I.head==b)&&_.setSelection(I)}return s&&_.setMeta("composition",s),_.scrollIntoView()},E;if(k)if(g.pos==y.pos){Qt&&io<=11&&g.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>Pr(t),20));let T=v(t.state.tr.delete(b,S)),_=u.resolve(m.start).marksAcross(u.resolve(m.endA));_&&T.ensureMarks(_),t.dispatch(T)}else if(m.endA==m.endB&&(E=zO(g.parent.content.cut(g.parentOffset,y.parentOffset),w.parent.content.cut(w.parentOffset,m.endA-w.start())))){let T=v(t.state.tr);E.type=="add"?T.addMark(b,S,E.mark):T.removeMark(b,S,E.mark),t.dispatch(T)}else if(g.parent.child(g.index()).isText&&g.index()==y.index()-(y.textOffset?0:1)){let T=g.parent.textBetween(g.parentOffset,y.parentOffset),_=()=>v(t.state.tr.insertText(T,b,S));t.someProp("handleTextInput",I=>I(t,b,S,T,_))||t.dispatch(_())}else t.dispatch(v());else t.dispatch(v())}function u1(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:Yd(t,e.resolve(n.anchor),e.resolve(n.head))}function zO(t,e){let n=t.firstChild.marks,r=e.firstChild.marks,o=n,s=r,i,a,l;for(let u=0;u<r.length;u++)o=r[u].removeFromSet(o);for(let u=0;u<n.length;u++)s=n[u].removeFromSet(s);if(o.length==1&&s.length==0)a=o[0],i="add",l=u=>u.mark(a.addToSet(u.marks));else if(o.length==0&&s.length==1)a=s[0],i="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;u<e.childCount;u++)c.push(l(e.child(u)));if(D.from(c).eq(t))return{mark:a,type:i}}function $O(t,e,n,r,o){if(n-e<=o.pos-r.pos||lf(r,!0,!1)<o.pos)return!1;let s=t.resolve(e);if(!r.parent.isTextblock){let a=s.nodeAfter;return a!=null&&n==e+a.nodeSize}if(s.parentOffset<s.parent.content.size||!s.parent.isTextblock)return!1;let i=t.resolve(lf(s,!0,!0));return!i.parent.isTextblock||i.pos>n||lf(i,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(i.parent.content)}function lf(t,e,n){let r=t.depth,o=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,o++,e=!1;if(n){let s=t.node(r).maybeChild(t.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,o++}return o}function LO(t,e,n,r,o){let s=t.findDiffStart(e,n);if(s==null)return null;let{a:i,b:a}=t.findDiffEnd(e,n+t.size,n+e.size);if(o=="end"){let l=Math.max(0,s-Math.min(i,a));r-=i+l-s}if(i<s&&t.size<e.size){let l=r<=s&&r>=i?s-r:0;s-=l,s&&s<e.size&&d1(e.textBetween(s-1,s+1))&&(s+=l?1:-1),a=s+(a-i),i=s}else if(a<s){let l=r<=s&&r>=a?s-r:0;s-=l,s&&s<t.size&&d1(t.textBetween(s-1,s+1))&&(s+=l?1:-1),i=s+(i-a),a=s}return{start:s,endA:i,endB:a}}function d1(t){if(t.length!=2)return!1;let e=t.charCodeAt(0),n=t.charCodeAt(1);return e>=56320&&e<=57343&&n>=55296&&n<=56319}class f1{constructor(e,n){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 tO,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(y1),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=m1(this),p1(this),this.nodeViews=g1(this),this.docView=Sw(this.state.doc,h1(this),af(this),this.dom,this),this.domObserver=new AO(this,(r,o,s,i)=>RO(this,r,o,s,i)),this.domObserver.start(),nO(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 n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ef(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(y1),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in e)n[r]=e[r];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var r;let o=this.state,s=!1,i=!1;e.storedMarks&&this.composing&&(Qw(this),i=!0),this.state=e;let a=o.plugins!=e.plugins||this._props.plugins!=n.plugins;if(a||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=g1(this);FO(p,this.nodeViews)&&(this.nodeViews=p,s=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&ef(this),this.editable=m1(this),p1(this);let l=af(this),c=h1(this),u=o.plugins!=e.plugins&&!o.doc.eq(e.doc)?"reset":e.scrollToSelection>o.scrollToSelection?"to selection":"preserve",f=s||!this.docView.matchesNode(e.doc,c,l);(f||!e.selection.eq(o.selection))&&(i=!0);let h=u=="preserve"&&i&&this.dom.style.overflowAnchor==null&&gD(this);if(i){this.domObserver.stop();let p=f&&(Qt||wt)&&!this.composing&&!o.selection.empty&&!e.selection.empty&&VO(o.selection,e.selection);if(f){let m=wt?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=gO(this)),(s||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=Sw(e.doc,c,l,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&VD(this))?Pr(this,p):(Nw(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(o),!((r=this.dragging)===null||r===void 0)&&r.node&&!o.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,o),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():h&&yD(h)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof oe){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&cw(this,n.getBoundingClientRect(),e)}else cw(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 n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let n=0;n<this.state.plugins.length;n++){let r=this.state.plugins[n];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let n=0;n<this.pluginViews.length;n++){let r=this.pluginViews[n];r.update&&r.update(this,e)}}updateDraggedNode(e,n){let r=e.node,o=-1;if(this.state.doc.nodeAt(r.from)==r.node)o=r.from;else{let s=r.from+(this.state.doc.content.size-n.doc.content.size);(s>0&&this.state.doc.nodeAt(s))==r.node&&(o=s)}this.dragging=new t1(e.slice,e.move,o<0?void 0:oe.create(this.state.doc,o))}someProp(e,n){let r=this._props&&this._props[e],o;if(r!=null&&(o=n?n(r):r))return o;for(let i=0;i<this.directPlugins.length;i++){let a=this.directPlugins[i].props[e];if(a!=null&&(o=n?n(a):a))return o}let s=this.state.plugins;if(s)for(let i=0;i<s.length;i++){let a=s[i].props[e];if(a!=null&&(o=n?n(a):a))return o}}hasFocus(){if(Qt){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&wD(this.dom),Pr(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let n=this.dom.parentNode;n;n=n.parentNode)if(n.nodeType==9||n.nodeType==11&&n.host)return n.getSelection||(Object.getPrototypeOf(n).getSelection=()=>n.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return ED(this,e)}coordsAtPos(e,n=1){return mw(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,r=-1){let o=this.docView.posFromDOM(e,n,r);if(o==null)throw new RangeError("DOM position not inside the editor");return o}endOfTextblock(e,n){return AD(this,n||this.state,e)}pasteHTML(e,n){return Gi(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Gi(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return Gd(this,e)}destroy(){this.docView&&(rO(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],af(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,iD())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return sO(this,e)}domSelectionRange(){let e=this.domSelection();return e?It&&this.root.nodeType===11&&dD(this.dom.ownerDocument)==this.dom&&IO(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}f1.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function h1(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let r in n)r=="class"?e.class+=" "+n[r]:r=="style"?e.style=(e.style?e.style+";":"")+n[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(n[r]))}),e.translate||(e.translate="no"),[jt.node(0,t.state.doc.content.size,e)]}function p1(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:jt.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function m1(t){return!t.someProp("editable",e=>e(t.state)===!1)}function VO(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function g1(t){let e=Object.create(null);function n(r){for(let o in r)Object.prototype.hasOwnProperty.call(e,o)||(e[o]=r[o])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function FO(t,e){let n=0,r=0;for(let o in t){if(t[o]!=e[o])return!0;n++}for(let o in e)r++;return n!=r}function y1(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}for(var po={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:"'"},Vl={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},WO=typeof navigator<"u"&&/Mac/.test(navigator.platform),UO=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Bt=0;Bt<10;Bt++)po[48+Bt]=po[96+Bt]=String(Bt);for(var Bt=1;Bt<=24;Bt++)po[Bt+111]="F"+Bt;for(var Bt=65;Bt<=90;Bt++)po[Bt]=String.fromCharCode(Bt+32),Vl[Bt]=String.fromCharCode(Bt);for(var cf in po)Vl.hasOwnProperty(cf)||(Vl[cf]=po[cf]);function HO(t){var e=WO&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||UO&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Vl:po)[t.keyCode]||t.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const jO=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),ZO=typeof navigator<"u"&&/Win/.test(navigator.platform);function KO(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let r,o,s,i;for(let a=0;a<e.length-1;a++){let l=e[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))o=!0;else if(/^s(hift)?$/i.test(l))s=!0;else if(/^mod$/i.test(l))jO?i=!0:o=!0;else throw new Error("Unrecognized modifier name: "+l)}return r&&(n="Alt-"+n),o&&(n="Ctrl-"+n),i&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function YO(t){let e=Object.create(null);for(let n in t)e[KO(n)]=t[n];return e}function uf(t,e,n=!0){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),n&&e.shiftKey&&(t="Shift-"+t),t}function qO(t){return new ct({props:{handleKeyDown:w1(t)}})}function w1(t){let e=YO(t);return function(n,r){let o=HO(r),s,i=e[uf(o,r)];if(i&&i(n.state,n.dispatch,n))return!0;if(o.length==1&&o!=" "){if(r.shiftKey){let a=e[uf(o,r,!1)];if(a&&a(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(ZO&&r.ctrlKey&&r.altKey)&&(s=po[r.keyCode])&&s!=o){let a=e[uf(s,r)];if(a&&a(n.state,n.dispatch,n))return!0}}return!1}}var XO=Object.defineProperty,df=(t,e)=>{for(var n in e)XO(t,n,{get:e[n],enumerable:!0})};function Fl(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:o}=n,{storedMarks:s}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return o},get tr(){return r=n.selection,o=n.doc,s=n.storedMarks,n}}}var Wl=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:o}=n,s=this.buildProps(o);return Object.fromEntries(Object.entries(t).map(([i,a])=>[i,(...c)=>{const u=a(...c)(s);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(o),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:o}=this,{view:s}=r,i=[],a=!!t,l=t||o.tr,c=()=>(!a&&e&&!l.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(l),i.every(f=>f===!0)),u={...Object.fromEntries(Object.entries(n).map(([f,h])=>[f,(...m)=>{const g=this.buildProps(l,e),y=h(...m)(g);return i.push(y),u}])),run:c};return u}createCan(t){const{rawCommands:e,state:n}=this,r=!1,o=t||n.tr,s=this.buildProps(o,r);return{...Object.fromEntries(Object.entries(e).map(([a,l])=>[a,(...c)=>l(...c)({...s,dispatch:void 0})])),chain:()=>this.createChain(o,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:o}=this,{view:s}=r,i={tr:t,editor:r,view:s,state:Fl({state:o,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([a,l])=>[a,(...c)=>l(...c)(i)]))}};return i}},k1={};df(k1,{blur:()=>GO,clearContent:()=>JO,clearNodes:()=>QO,command:()=>e3,createParagraphNear:()=>t3,cut:()=>n3,deleteCurrentNode:()=>r3,deleteNode:()=>o3,deleteRange:()=>s3,deleteSelection:()=>i3,enter:()=>a3,exitCode:()=>l3,extendMarkRange:()=>c3,first:()=>u3,focus:()=>f3,forEach:()=>h3,insertContent:()=>p3,insertContentAt:()=>y3,joinBackward:()=>v3,joinDown:()=>k3,joinForward:()=>b3,joinItemBackward:()=>S3,joinItemForward:()=>E3,joinTextblockBackward:()=>C3,joinTextblockForward:()=>x3,joinUp:()=>w3,keyboardShortcut:()=>M3,lift:()=>A3,liftEmptyBlock:()=>_3,liftListItem:()=>I3,newlineInCode:()=>B3,resetAttributes:()=>N3,scrollIntoView:()=>P3,selectAll:()=>D3,selectNodeBackward:()=>O3,selectNodeForward:()=>R3,selectParentNode:()=>z3,selectTextblockEnd:()=>$3,selectTextblockStart:()=>L3,setContent:()=>V3,setMark:()=>sR,setMeta:()=>iR,setNode:()=>aR,setNodeSelection:()=>lR,setTextDirection:()=>cR,setTextSelection:()=>uR,sinkListItem:()=>dR,splitBlock:()=>fR,splitListItem:()=>hR,toggleList:()=>pR,toggleMark:()=>mR,toggleNode:()=>gR,toggleWrap:()=>yR,undoInputRule:()=>wR,unsetAllMarks:()=>kR,unsetMark:()=>vR,unsetTextDirection:()=>bR,updateAttributes:()=>SR,wrapIn:()=>ER,wrapInList:()=>CR});var GO=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window==null?void 0:window.getSelection())==null||n.removeAllRanges())}),!0),JO=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),QO=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:o}=r;return n&&o.forEach(({$from:s,$to:i})=>{t.doc.nodesBetween(s.pos,i.pos,(a,l)=>{if(a.type.isText)return;const{doc:c,mapping:u}=e,f=c.resolve(u.map(l)),h=c.resolve(u.map(l+a.nodeSize)),p=f.blockRange(h);if(!p)return;const m=Vs(p);if(a.type.isTextblock){const{defaultType:g}=f.parent.contentMatchAt(f.index());e.setNodeMarkup(p.start,g)}(m||m===0)&&e.lift(p,m)})}),!0},e3=t=>e=>t(e),t3=()=>({state:t,dispatch:e})=>Q0(t,e),n3=(t,e)=>({editor:n,tr:r})=>{const{state:o}=n,s=o.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const i=r.mapping.map(e);return r.insert(i,s.content),r.setSelection(new ce(r.doc.resolve(Math.max(i-1,0)))),!0},r3=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const o=t.selection.$anchor;for(let s=o.depth;s>0;s-=1)if(o.node(s).type===r.type){if(e){const a=o.before(s),l=o.after(s);t.delete(a,l).scrollIntoView()}return!0}return!1};function kt(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var o3=t=>({tr:e,state:n,dispatch:r})=>{const o=kt(t,n.schema),s=e.selection.$anchor;for(let i=s.depth;i>0;i-=1)if(s.node(i).type===o){if(r){const l=s.before(i),c=s.after(i);e.delete(l,c).scrollIntoView()}return!0}return!1},s3=t=>({tr:e,dispatch:n})=>{const{from:r,to:o}=t;return n&&e.delete(r,o),!0},i3=()=>({state:t,dispatch:e})=>Pd(t,e),a3=()=>({commands:t})=>t.keyboardShortcut("Enter"),l3=()=>({state:t,dispatch:e})=>jP(t,e);function ff(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function Ul(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(o=>n.strict?e[o]===t[o]:ff(e[o])?e[o].test(t[o]):e[o]===t[o]):!0}function v1(t,e,n={}){return t.find(r=>r.type===e&&Ul(Object.fromEntries(Object.keys(n).map(o=>[o,r.attrs[o]])),n))}function b1(t,e,n={}){return!!v1(t,e,n)}function hf(t,e,n){var r;if(!t||!e)return;let o=t.parent.childAfter(t.parentOffset);if((!o.node||!o.node.marks.some(u=>u.type===e))&&(o=t.parent.childBefore(t.parentOffset)),!o.node||!o.node.marks.some(u=>u.type===e)||(n=n||((r=o.node.marks[0])==null?void 0:r.attrs),!v1([...o.node.marks],e,n)))return;let i=o.index,a=t.start()+o.offset,l=i+1,c=a+o.node.nodeSize;for(;i>0&&b1([...t.parent.child(i-1).marks],e,n);)i-=1,a-=t.parent.child(i).nodeSize;for(;l<t.parent.childCount&&b1([...t.parent.child(l).marks],e,n);)c+=t.parent.child(l).nodeSize,l+=1;return{from:a,to:c}}function Dr(t,e){if(typeof t=="string"){if(!e.marks[t])throw Error(`There is no mark type named '${t}'. Maybe you forgot to add the extension?`);return e.marks[t]}return t}var c3=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const s=Dr(t,r.schema),{doc:i,selection:a}=n,{$from:l,from:c,to:u}=a;if(o){const f=hf(l,s,e);if(f&&f.from<=c&&f.to>=u){const h=ce.create(i,f.from,f.to);n.setSelection(h)}}return!0},u3=t=>e=>{const n=typeof t=="function"?t(e):t;for(let r=0;r<n.length;r+=1)if(n[r](e))return!0;return!1};function S1(t){return t instanceof ce}function Jo(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function E1(t,e=null){if(!e)return null;const n=fe.atStart(t),r=fe.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const o=n.from,s=r.to;return e==="all"?ce.create(t,Jo(0,o,s),Jo(t.content.size,o,s)):ce.create(t,Jo(e,o,s),Jo(e,o,s))}function C1(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function Hl(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function d3(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var f3=(t=null,e={})=>({editor:n,view:r,tr:o,dispatch:s})=>{e={scrollIntoView:!0,...e};const i=()=>{(Hl()||C1())&&r.dom.focus(),d3()&&!Hl()&&!C1()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e!=null&&e.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&t===null||t===!1)return!0;if(s&&t===null&&!S1(n.state.selection))return i(),!0;const a=E1(o.doc,t)||n.state.selection,l=n.state.selection.eq(a);return s&&(l||o.setSelection(a),l&&o.storedMarks&&o.setStoredMarks(o.storedMarks),i()),!0},h3=(t,e)=>n=>t.every((r,o)=>e(r,{...n,index:o})),p3=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),x1=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):r.nodeType===1&&x1(r)}return t};function Qi(t){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`<body>${t}</body>`,n=new window.DOMParser().parseFromString(e,"text/html").body;return x1(n)}function ea(t,e,n){if(t instanceof Mr||t instanceof D)return t;n={slice:!0,parseOptions:{},...n};const r=typeof t=="object"&&t!==null,o=typeof t=="string";if(r)try{if(Array.isArray(t)&&t.length>0)return D.fromArray(t.map(a=>e.nodeFromJSON(a)));const i=e.nodeFromJSON(t);return n.errorOnInvalidContent&&i.check(),i}catch(s){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",s),ea("",e,n)}if(o){if(n.errorOnInvalidContent){let i=!1,a="";const l=new u0({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(i=!0,a=typeof c=="string"?c:c.outerHTML,null)}]}})});if(n.slice?Ar.fromSchema(l).parseSlice(Qi(t),n.parseOptions):Ar.fromSchema(l).parse(Qi(t),n.parseOptions),n.errorOnInvalidContent&&i)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const s=Ar.fromSchema(e);return n.slice?s.parseSlice(Qi(t),n.parseOptions).content:s.parse(Qi(t),n.parseOptions)}return ea("",e,n)}function m3(t,e,n){const r=t.steps.length-1;if(r<e)return;const o=t.steps[r];if(!(o instanceof gt||o instanceof yt))return;const s=t.mapping.maps[r];let i=0;s.forEach((a,l,c,u)=>{i===0&&(i=u)}),t.setSelection(fe.near(t.doc.resolve(i),n))}var g3=t=>!("type"in t),y3=(t,e,n)=>({tr:r,dispatch:o,editor:s})=>{var i;if(o){n={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let a;const l=y=>{s.emit("contentError",{editor:s,error:y,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{ea(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(y){l(y)}try{a=ea(e,s.schema,{parseOptions:c,errorOnInvalidContent:(i=n.errorOnInvalidContent)!=null?i:s.options.enableContentCheck})}catch(y){return l(y),!1}let{from:u,to:f}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},h=!0,p=!0;if((g3(a)?a:[a]).forEach(y=>{y.check(),h=h?y.isText&&y.marks.length===0:!1,p=p?y.isBlock:!1}),u===f&&p){const{parent:y}=r.doc.resolve(u);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(u-=1,f+=1)}let g;if(h){if(Array.isArray(e))g=e.map(y=>y.text||"").join("");else if(e instanceof D){let y="";e.forEach(w=>{w.text&&(y+=w.text)}),g=y}else typeof e=="object"&&e&&e.text?g=e.text:g=e;r.insertText(g,u,f)}else{g=a;const y=r.doc.resolve(u),w=y.node(),k=y.parentOffset===0,b=w.isText||w.isTextblock,S=w.content.size>0;k&&b&&S&&(u=Math.max(0,u-1)),r.replaceWith(u,f,g)}n.updateSelection&&m3(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:g}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:g})}return!0},w3=()=>({state:t,dispatch:e})=>WP(t,e),k3=()=>({state:t,dispatch:e})=>UP(t,e),v3=()=>({state:t,dispatch:e})=>Z0(t,e),b3=()=>({state:t,dispatch:e})=>X0(t,e),S3=()=>({state:t,dispatch:e,tr:n})=>{try{const r=Al(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},E3=()=>({state:t,dispatch:e,tr:n})=>{try{const r=Al(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},C3=()=>({state:t,dispatch:e})=>VP(t,e),x3=()=>({state:t,dispatch:e})=>FP(t,e);function T1(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function T3(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let r,o,s,i;for(let a=0;a<e.length-1;a+=1){const l=e[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))o=!0;else if(/^s(hift)?$/i.test(l))s=!0;else if(/^mod$/i.test(l))Hl()||T1()?i=!0:o=!0;else throw new Error(`Unrecognized modifier name: ${l}`)}return r&&(n=`Alt-${n}`),o&&(n=`Ctrl-${n}`),i&&(n=`Meta-${n}`),s&&(n=`Shift-${n}`),n}var M3=t=>({editor:e,view:n,tr:r,dispatch:o})=>{const s=T3(t).split(/-(?!$)/),i=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),a=new KeyboardEvent("keydown",{key:i==="Space"?" ":i,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),l=e.captureTransaction(()=>{n.someProp("handleKeyDown",c=>c(n,a))});return l==null||l.steps.forEach(c=>{const u=c.map(r.mapping);u&&o&&r.maybeStep(u)}),!0};function ta(t,e,n={}){const{from:r,to:o,empty:s}=t.selection,i=e?kt(e,t.schema):null,a=[];t.doc.nodesBetween(r,o,(f,h)=>{if(f.isText)return;const p=Math.max(r,h),m=Math.min(o,h+f.nodeSize);a.push({node:f,from:p,to:m})});const l=o-r,c=a.filter(f=>i?i.name===f.node.type.name:!0).filter(f=>Ul(f.node.attrs,n,{strict:!1}));return s?!!c.length:c.reduce((f,h)=>f+h.to-h.from,0)>=l}var A3=(t,e={})=>({state:n,dispatch:r})=>{const o=kt(t,n.schema);return ta(n,o,e)?HP(n,r):!1},_3=()=>({state:t,dispatch:e})=>ew(t,e),I3=t=>({state:e,dispatch:n})=>{const r=kt(t,e.schema);return nD(r)(e,n)},B3=()=>({state:t,dispatch:e})=>J0(t,e);function jl(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function M1(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((r,o)=>(n.includes(o)||(r[o]=t[o]),r),{})}var N3=(t,e)=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=jl(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=kt(t,r.schema)),a==="mark"&&(i=Dr(t,r.schema));let l=!1;return n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,f)=>{s&&s===u.type&&(l=!0,o&&n.setNodeMarkup(f,void 0,M1(u.attrs,e))),i&&u.marks.length&&u.marks.forEach(h=>{i===h.type&&(l=!0,o&&n.addMark(f,f+u.nodeSize,i.create(M1(h.attrs,e))))})})}),l},P3=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),D3=()=>({tr:t,dispatch:e})=>{if(e){const n=new fn(t.doc);t.setSelection(n)}return!0},O3=()=>({state:t,dispatch:e})=>Y0(t,e),R3=()=>({state:t,dispatch:e})=>G0(t,e),z3=()=>({state:t,dispatch:e})=>YP(t,e),$3=()=>({state:t,dispatch:e})=>GP(t,e),L3=()=>({state:t,dispatch:e})=>XP(t,e);function pf(t,e,n={},r={}){return ea(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var V3=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:o,tr:s,dispatch:i,commands:a})=>{const{doc:l}=s;if(r.preserveWhitespace!=="full"){const c=pf(t,o.schema,r,{errorOnInvalidContent:e??o.options.enableContentCheck});return i&&s.replaceWith(0,l.content.size,c).setMeta("preventUpdate",!n),!0}return i&&s.setMeta("preventUpdate",!n),a.insertContentAt({from:0,to:l.content.size},t,{parseOptions:r,errorOnInvalidContent:e??o.options.enableContentCheck})};function A1(t,e){const n=Dr(e,t.schema),{from:r,to:o,empty:s}=t.selection,i=[];s?(t.storedMarks&&i.push(...t.storedMarks),i.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,o,l=>{i.push(...l.marks)});const a=i.find(l=>l.type.name===n.name);return a?{...a.attrs}:{}}function F3(t,e){const n=new R0(t);return e.forEach(r=>{r.steps.forEach(o=>{n.step(o)})}),n}function W3(t){for(let e=0;e<t.edgeCount;e+=1){const{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function U3(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}function mf(t){return e=>U3(e.$from,t)}function ne(t,e,n){return t.config[e]===void 0&&t.parent?ne(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?ne(t.parent,e,n):null}):t.config[e]}function gf(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=ne(e,"addExtensions",n);return r?[e,...gf(r())]:e}).flat(10)}function Zl(t,e){const n=Wo.fromSchema(e).serializeFragment(t),o=document.implementation.createHTMLDocument().createElement("div");return o.appendChild(n),o.innerHTML}function _1(t){return typeof t=="function"}function Pe(t,e=void 0,...n){return _1(t)?e?t.bind(e)(...n):t(...n):t}function H3(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Js(t){const e=t.filter(o=>o.type==="extension"),n=t.filter(o=>o.type==="node"),r=t.filter(o=>o.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:r}}function I1(t){const e=[],{nodeExtensions:n,markExtensions:r}=Js(t),o=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(i=>{const a={name:i.name,options:i.options,storage:i.storage,extensions:o},l=ne(i,"addGlobalAttributes",a);if(!l)return;l().forEach(u=>{u.types.forEach(f=>{Object.entries(u.attributes).forEach(([h,p])=>{e.push({type:f,name:h,attribute:{...s,...p}})})})})}),o.forEach(i=>{const a={name:i.name,options:i.options,storage:i.storage},l=ne(i,"addAttributes",a);if(!l)return;const c=l();Object.entries(c).forEach(([u,f])=>{const h={...s,...f};typeof(h==null?void 0:h.default)=="function"&&(h.default=h.default()),h!=null&&h.isRequired&&(h==null?void 0:h.default)===void 0&&delete h.default,e.push({type:i.name,name:u,attribute:h})})}),e}function Qs(...t){return t.filter(e=>!!e).reduce((e,n)=>{const r={...e};return Object.entries(n).forEach(([o,s])=>{if(!r[o]){r[o]=s;return}if(o==="class"){const a=s?String(s).split(" "):[],l=r[o]?r[o].split(" "):[],c=a.filter(u=>!l.includes(u));r[o]=[...l,...c].join(" ")}else if(o==="style"){const a=s?s.split(";").map(u=>u.trim()).filter(Boolean):[],l=r[o]?r[o].split(";").map(u=>u.trim()).filter(Boolean):[],c=new Map;l.forEach(u=>{const[f,h]=u.split(":").map(p=>p.trim());c.set(f,h)}),a.forEach(u=>{const[f,h]=u.split(":").map(p=>p.trim());c.set(f,h)}),r[o]=Array.from(c.entries()).map(([u,f])=>`${u}: ${f}`).join("; ")}else r[o]=s}),r},{})}function Kl(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,r)=>Qs(n,r),{})}function j3(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function B1(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(r===!1)return!1;const o=e.reduce((s,i)=>{const a=i.attribute.parseHTML?i.attribute.parseHTML(n):j3(n.getAttribute(i.name));return a==null?s:{...s,[i.name]:a}},{});return{...r,...o}}}}function N1(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&H3(n)?!1:n!=null))}function P1(t){var e,n;const r={};return!((e=t==null?void 0:t.attribute)!=null&&e.isRequired)&&"default"in((t==null?void 0:t.attribute)||{})&&(r.default=t.attribute.default),((n=t==null?void 0:t.attribute)==null?void 0:n.validate)!==void 0&&(r.validate=t.attribute.validate),[t.name,r]}function D1(t,e){var n;const r=I1(t),{nodeExtensions:o,markExtensions:s}=Js(t),i=(n=o.find(c=>ne(c,"topNode")))==null?void 0:n.name,a=Object.fromEntries(o.map(c=>{const u=r.filter(w=>w.type===c.name),f={name:c.name,options:c.options,storage:c.storage,editor:e},h=t.reduce((w,k)=>{const b=ne(k,"extendNodeSchema",f);return{...w,...b?b(c):{}}},{}),p=N1({...h,content:Pe(ne(c,"content",f)),marks:Pe(ne(c,"marks",f)),group:Pe(ne(c,"group",f)),inline:Pe(ne(c,"inline",f)),atom:Pe(ne(c,"atom",f)),selectable:Pe(ne(c,"selectable",f)),draggable:Pe(ne(c,"draggable",f)),code:Pe(ne(c,"code",f)),whitespace:Pe(ne(c,"whitespace",f)),linebreakReplacement:Pe(ne(c,"linebreakReplacement",f)),defining:Pe(ne(c,"defining",f)),isolating:Pe(ne(c,"isolating",f)),attrs:Object.fromEntries(u.map(P1))}),m=Pe(ne(c,"parseHTML",f));m&&(p.parseDOM=m.map(w=>B1(w,u)));const g=ne(c,"renderHTML",f);g&&(p.toDOM=w=>g({node:w,HTMLAttributes:Kl(w,u)}));const y=ne(c,"renderText",f);return y&&(p.toText=y),[c.name,p]})),l=Object.fromEntries(s.map(c=>{const u=r.filter(y=>y.type===c.name),f={name:c.name,options:c.options,storage:c.storage,editor:e},h=t.reduce((y,w)=>{const k=ne(w,"extendMarkSchema",f);return{...y,...k?k(c):{}}},{}),p=N1({...h,inclusive:Pe(ne(c,"inclusive",f)),excludes:Pe(ne(c,"excludes",f)),group:Pe(ne(c,"group",f)),spanning:Pe(ne(c,"spanning",f)),code:Pe(ne(c,"code",f)),attrs:Object.fromEntries(u.map(P1))}),m=Pe(ne(c,"parseHTML",f));m&&(p.parseDOM=m.map(y=>B1(y,u)));const g=ne(c,"renderHTML",f);return g&&(p.toDOM=y=>g({mark:y,HTMLAttributes:Kl(y,u)})),[c.name,p]}));return new u0({topNode:i,nodes:a,marks:l})}function Z3(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function Yl(t){return t.sort((n,r)=>{const o=ne(n,"priority")||100,s=ne(r,"priority")||100;return o>s?-1:o<s?1:0})}function yf(t){const e=Yl(gf(t)),n=Z3(e.map(r=>r.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function O1(t,e){const n=yf(t);return D1(n,e)}function ql(t,e){const n=O1(e),r=Mr.fromJSON(n,t);return Zl(r.content,n)}function mo(t,e){const n=O1(e),r=Qi(t);return Ar.fromSchema(n).parse(r).toJSON()}function R1(t,e,n){const{from:r,to:o}=e,{blockSeparator:s=`
79
+
80
+ `,textSerializers:i={}}=n||{};let a="";return t.nodesBetween(r,o,(l,c,u,f)=>{var h;l.isBlock&&c>r&&(a+=s);const p=i==null?void 0:i[l.type.name];if(p)return u&&(a+=p({node:l,pos:c,parent:u,index:f,range:e})),!1;l.isText&&(a+=(h=l==null?void 0:l.text)==null?void 0:h.slice(Math.max(r,c)-c,o-c))}),a}function K3(t,e){const n={from:0,to:t.content.size};return R1(t,n,e)}function z1(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function Y3(t,e){const n=kt(e,t.schema),{from:r,to:o}=t.selection,s=[];t.doc.nodesBetween(r,o,a=>{s.push(a)});const i=s.reverse().find(a=>a.type.name===n.name);return i?{...i.attrs}:{}}function q3(t,e){const n=jl(typeof e=="string"?e:e.name,t.schema);return n==="node"?Y3(t,e):n==="mark"?A1(t,e):{}}function X3(t,e=JSON.stringify){const n={};return t.filter(r=>{const o=e(r);return Object.prototype.hasOwnProperty.call(n,o)?!1:n[o]=!0})}function G3(t){const e=X3(t);return e.length===1?e:e.filter((n,r)=>!e.filter((s,i)=>i!==r).some(s=>n.oldRange.from>=s.oldRange.from&&n.oldRange.to<=s.oldRange.to&&n.newRange.from>=s.newRange.from&&n.newRange.to<=s.newRange.to))}function J3(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((o,s)=>{const i=[];if(o.ranges.length)o.forEach((a,l)=>{i.push({from:a,to:l})});else{const{from:a,to:l}=n[s];if(a===void 0||l===void 0)return;i.push({from:a,to:l})}i.forEach(({from:a,to:l})=>{const c=e.slice(s).map(a,-1),u=e.slice(s).map(l),f=e.invert().map(c,-1),h=e.invert().map(u);r.push({oldRange:{from:f,to:h},newRange:{from:c,to:u}})})}),G3(r)}function $1(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(o=>{const s=n.resolve(t),i=hf(s,o.type);i&&r.push({mark:o,...i})}):n.nodesBetween(t,e,(o,s)=>{!o||(o==null?void 0:o.nodeSize)===void 0||r.push(...o.marks.map(i=>({from:s,to:s+o.nodeSize,mark:i})))}),r}function Xl(t,e){return e.nodes[t]||e.marks[t]||null}function Gl(t,e,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const o=t.find(s=>s.type===e&&s.name===r);return o?o.attribute.keepOnSplit:!1}))}var Q3=(t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(o,s,i,a)=>{var l,c;const u=((c=(l=o.type.spec).toText)==null?void 0:c.call(l,{node:o,pos:s,parent:i,index:a}))||o.textContent||"%leaf%";n+=o.isAtom&&!o.isText?u:u.slice(0,Math.max(0,r-s))}),n};function wf(t,e,n={}){const{empty:r,ranges:o}=t.selection,s=e?Dr(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>Ul(f.attrs,n,{strict:!1}));let i=0;const a=[];if(o.forEach(({$from:f,$to:h})=>{const p=f.pos,m=h.pos;t.doc.nodesBetween(p,m,(g,y)=>{if(!g.isText&&!g.marks.length)return;const w=Math.max(p,y),k=Math.min(m,y+g.nodeSize),b=k-w;i+=b,a.push(...g.marks.map(S=>({mark:S,from:w,to:k})))})}),i===0)return!1;const l=a.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>Ul(f.mark.attrs,n,{strict:!1})).reduce((f,h)=>f+h.to-h.from,0),c=a.filter(f=>s?f.mark.type!==s&&f.mark.type.excludes(s):!0).reduce((f,h)=>f+h.to-h.from,0);return(l>0?l+c:l)>=i}function eR(t,e,n={}){if(!e)return ta(t,null,n)||wf(t,null,n);const r=jl(e,t.schema);return r==="node"?ta(t,e,n):r==="mark"?wf(t,e,n):!1}function L1(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function V1(t,e){const{nodeExtensions:n}=Js(e),r=n.find(i=>i.name===t);if(!r)return!1;const o={name:r.name,options:r.options,storage:r.storage},s=Pe(ne(r,"group",o));return typeof s!="string"?!1:s.split(" ").includes("list")}function Jl(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((r=t.text)!=null?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let o=!0;return t.content.forEach(s=>{o!==!1&&(Jl(s,{ignoreWhitespace:n,checkChildren:e})||(o=!1))}),o}return!1}function tR(t){return t instanceof oe}var F1=class zv{constructor(e){this.position=e}static fromJSON(e){return new zv(e.position)}toJSON(){return{position:this.position}}};function nR(t,e){const n=e.mapping.mapResult(t.position);return{position:new F1(n.pos),mapResult:n}}function rR(t){return new F1(t)}function oR(t,e,n){var r;const{selection:o}=e;let s=null;if(S1(o)&&(s=o.$cursor),s){const a=(r=t.storedMarks)!=null?r:s.marks();return s.parent.type.allowsMarkType(n)&&(!!n.isInSet(a)||!a.some(c=>c.type.excludes(n)))}const{ranges:i}=o;return i.some(({$from:a,$to:l})=>{let c=a.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(a.pos,l.pos,(u,f,h)=>{if(c)return!1;if(u.isInline){const p=!h||h.type.allowsMarkType(n),m=!!n.isInSet(u.marks)||!u.marks.some(g=>g.type.excludes(n));c=p&&m}return!c}),c})}var sR=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const{selection:s}=n,{empty:i,ranges:a}=s,l=Dr(t,r.schema);if(o)if(i){const c=A1(r,l);n.addStoredMark(l.create({...c,...e}))}else a.forEach(c=>{const u=c.$from.pos,f=c.$to.pos;r.doc.nodesBetween(u,f,(h,p)=>{const m=Math.max(p,u),g=Math.min(p+h.nodeSize,f);h.marks.find(w=>w.type===l)?h.marks.forEach(w=>{l===w.type&&n.addMark(m,g,l.create({...w.attrs,...e}))}):n.addMark(m,g,l.create(e))})});return oR(r,n,l)},iR=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),aR=(t,e={})=>({state:n,dispatch:r,chain:o})=>{const s=kt(t,n.schema);let i;return n.selection.$anchor.sameParent(n.selection.$head)&&(i=n.selection.$anchor.parent.attrs),s.isTextblock?o().command(({commands:a})=>rw(s,{...i,...e})(n)?!0:a.clearNodes()).command(({state:a})=>rw(s,{...i,...e})(a,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},lR=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,o=Jo(t,0,r.content.size),s=oe.create(r,o);e.setSelection(s)}return!0},cR=(t,e)=>({tr:n,state:r,dispatch:o})=>{const{selection:s}=r;let i,a;return typeof e=="number"?(i=e,a=e):e&&"from"in e&&"to"in e?(i=e.from,a=e.to):(i=s.from,a=s.to),o&&n.doc.nodesBetween(i,a,(l,c)=>{l.isText||n.setNodeMarkup(c,void 0,{...l.attrs,dir:t})}),!0},uR=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:o,to:s}=typeof t=="number"?{from:t,to:t}:t,i=ce.atStart(r).from,a=ce.atEnd(r).to,l=Jo(o,i,a),c=Jo(s,i,a),u=ce.create(r,l,c);e.setSelection(u)}return!0},dR=t=>({state:e,dispatch:n})=>{const r=kt(t,e.schema);return sD(r)(e,n)};function W1(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(o=>e==null?void 0:e.includes(o.type.name));t.tr.ensureMarks(r)}}var fR=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:o})=>{const{selection:s,doc:i}=e,{$from:a,$to:l}=s,c=o.extensionManager.attributes,u=Gl(c,a.node().type.name,a.node().attrs);if(s instanceof oe&&s.node.isBlock)return!a.parentOffset||!_r(i,a.pos)?!1:(r&&(t&&W1(n,o.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const f=l.parentOffset===l.parent.content.size,h=a.depth===0?void 0:W3(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=f&&h?[{type:h,attrs:u}]:void 0,m=_r(e.doc,e.mapping.map(a.pos),1,p);if(!p&&!m&&_r(e.doc,e.mapping.map(a.pos),1,h?[{type:h}]:void 0)&&(m=!0,p=h?[{type:h,attrs:u}]:void 0),r){if(m&&(s instanceof ce&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,p),h&&!f&&!a.parentOffset&&a.parent.type!==h)){const g=e.mapping.map(a.before()),y=e.doc.resolve(g);a.node(-1).canReplaceWith(y.index(),y.index()+1,h)&&e.setNodeMarkup(e.mapping.map(a.before()),h)}t&&W1(n,o.extensionManager.splittableMarks),e.scrollIntoView()}return m},hR=(t,e={})=>({tr:n,state:r,dispatch:o,editor:s})=>{var i;const a=kt(t,r.schema),{$from:l,$to:c}=r.selection,u=r.selection.node;if(u&&u.isBlock||l.depth<2||!l.sameParent(c))return!1;const f=l.node(-1);if(f.type!==a)return!1;const h=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==a||l.index(-2)!==l.node(-2).childCount-1)return!1;if(o){let w=D.empty;const k=l.index(-1)?1:l.index(-2)?2:3;for(let _=l.depth-k;_>=l.depth-3;_-=1)w=D.from(l.node(_).copy(w));const b=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,S={...Gl(h,l.node().type.name,l.node().attrs),...e},v=((i=a.contentMatch.defaultType)==null?void 0:i.createAndFill(S))||void 0;w=w.append(D.from(a.createAndFill(null,v)||void 0));const E=l.before(l.depth-(k-1));n.replace(E,l.after(-b),new Z(w,4-k,0));let T=-1;n.doc.nodesBetween(E,n.doc.content.size,(_,I)=>{if(T>-1)return!1;_.isTextblock&&_.content.size===0&&(T=I+1)}),T>-1&&n.setSelection(ce.near(n.doc.resolve(T))),n.scrollIntoView()}return!0}const p=c.pos===l.end()?f.contentMatchAt(0).defaultType:null,m={...Gl(h,f.type.name,f.attrs),...e},g={...Gl(h,l.node().type.name,l.node().attrs),...e};n.delete(l.pos,c.pos);const y=p?[{type:a,attrs:m},{type:p,attrs:g}]:[{type:a,attrs:m}];if(!_r(n.doc,l.pos,2))return!1;if(o){const{selection:w,storedMarks:k}=r,{splittableMarks:b}=s.extensionManager,S=k||w.$to.parentOffset&&w.$from.marks();if(n.split(l.pos,2,y).scrollIntoView(),!S||!o)return!0;const v=S.filter(E=>b.includes(E.type.name));n.ensureMarks(v)}return!0},kf=(t,e)=>{const n=mf(i=>i.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const o=t.doc.nodeAt(r);return n.node.type===(o==null?void 0:o.type)&&Ho(t.doc,n.pos)&&t.join(n.pos),!0},vf=(t,e)=>{const n=mf(i=>i.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const o=t.doc.nodeAt(r);return n.node.type===(o==null?void 0:o.type)&&Ho(t.doc,r)&&t.join(r),!0},pR=(t,e,n,r={})=>({editor:o,tr:s,state:i,dispatch:a,chain:l,commands:c,can:u})=>{const{extensions:f,splittableMarks:h}=o.extensionManager,p=kt(t,i.schema),m=kt(e,i.schema),{selection:g,storedMarks:y}=i,{$from:w,$to:k}=g,b=w.blockRange(k),S=y||g.$to.parentOffset&&g.$from.marks();if(!b)return!1;const v=mf(E=>V1(E.type.name,f))(g);if(b.depth>=1&&v&&b.depth-v.depth<=1){if(v.node.type===p)return c.liftListItem(m);if(V1(v.node.type.name,f)&&p.validContent(v.node.content)&&a)return l().command(()=>(s.setNodeMarkup(v.pos,p),!0)).command(()=>kf(s,p)).command(()=>vf(s,p)).run()}return!n||!S||!a?l().command(()=>u().wrapInList(p,r)?!0:c.clearNodes()).wrapInList(p,r).command(()=>kf(s,p)).command(()=>vf(s,p)).run():l().command(()=>{const E=u().wrapInList(p,r),T=S.filter(_=>h.includes(_.type.name));return s.ensureMarks(T),E?!0:c.clearNodes()}).wrapInList(p,r).command(()=>kf(s,p)).command(()=>vf(s,p)).run()},mR=(t,e={},n={})=>({state:r,commands:o})=>{const{extendEmptyMarkRange:s=!1}=n,i=Dr(t,r.schema);return wf(r,i,e)?o.unsetMark(i,{extendEmptyMarkRange:s}):o.setMark(i,e)},gR=(t,e,n={})=>({state:r,commands:o})=>{const s=kt(t,r.schema),i=kt(e,r.schema),a=ta(r,s,n);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),a?o.setNode(i,l):o.setNode(s,{...l,...n})},yR=(t,e={})=>({state:n,commands:r})=>{const o=kt(t,n.schema);return ta(n,o,e)?r.lift(o):r.wrapIn(o,e)},wR=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r<n.length;r+=1){const o=n[r];let s;if(o.spec.isInputRules&&(s=o.getState(t))){if(e){const i=t.tr,a=s.transform;for(let l=a.steps.length-1;l>=0;l-=1)i.step(a.steps[l].invert(a.docs[l]));if(s.text){const l=i.doc.resolve(s.from).marks();i.replaceWith(s.from,s.to,t.schema.text(s.text,l))}else i.delete(s.from,s.to)}return!0}}return!1},kR=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:r,ranges:o}=n;return r||e&&o.forEach(s=>{t.removeMark(s.$from.pos,s.$to.pos)}),!0},vR=(t,e={})=>({tr:n,state:r,dispatch:o})=>{var s;const{extendEmptyMarkRange:i=!1}=e,{selection:a}=n,l=Dr(t,r.schema),{$from:c,empty:u,ranges:f}=a;if(!o)return!0;if(u&&i){let{from:h,to:p}=a;const m=(s=c.marks().find(y=>y.type===l))==null?void 0:s.attrs,g=hf(c,l,m);g&&(h=g.from,p=g.to),n.removeMark(h,p,l)}else f.forEach(h=>{n.removeMark(h.$from.pos,h.$to.pos,l)});return n.removeStoredMark(l),!0},bR=t=>({tr:e,state:n,dispatch:r})=>{const{selection:o}=n;let s,i;return typeof t=="number"?(s=t,i=t):t&&"from"in t&&"to"in t?(s=t.from,i=t.to):(s=o.from,i=o.to),r&&e.doc.nodesBetween(s,i,(a,l)=>{if(a.isText)return;const c={...a.attrs};delete c.dir,e.setNodeMarkup(l,void 0,c)}),!0},SR=(t,e={})=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=jl(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=kt(t,r.schema)),a==="mark"&&(i=Dr(t,r.schema));let l=!1;return n.selection.ranges.forEach(c=>{const u=c.$from.pos,f=c.$to.pos;let h,p,m,g;n.selection.empty?r.doc.nodesBetween(u,f,(y,w)=>{s&&s===y.type&&(l=!0,m=Math.max(w,u),g=Math.min(w+y.nodeSize,f),h=w,p=y)}):r.doc.nodesBetween(u,f,(y,w)=>{w<u&&s&&s===y.type&&(l=!0,m=Math.max(w,u),g=Math.min(w+y.nodeSize,f),h=w,p=y),w>=u&&w<=f&&(s&&s===y.type&&(l=!0,o&&n.setNodeMarkup(w,void 0,{...y.attrs,...e})),i&&y.marks.length&&y.marks.forEach(k=>{if(i===k.type&&(l=!0,o)){const b=Math.max(w,u),S=Math.min(w+y.nodeSize,f);n.addMark(b,S,i.create({...k.attrs,...e}))}}))}),p&&(h!==void 0&&o&&n.setNodeMarkup(h,void 0,{...p.attrs,...e}),i&&p.marks.length&&p.marks.forEach(y=>{i===y.type&&o&&n.addMark(m,g,i.create({...y.attrs,...e}))}))}),l},ER=(t,e={})=>({state:n,dispatch:r})=>{const o=kt(t,n.schema);return JP(o,e)(n,r)},CR=(t,e={})=>({state:n,dispatch:r})=>{const o=kt(t,n.schema);return QP(o,e)(n,r)},xR=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(r=>r.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(r=>r!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},TR=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},MR=(t,e)=>{if(ff(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function Ql(t){var e;const{editor:n,from:r,to:o,text:s,rules:i,plugin:a}=t,{view:l}=n;if(l.composing)return!1;const c=l.state.doc.resolve(r);if(c.parent.type.spec.code||(e=c.nodeBefore||c.nodeAfter)!=null&&e.marks.find(h=>h.type.spec.code))return!1;let u=!1;const f=Q3(c)+s;return i.forEach(h=>{if(u)return;const p=MR(f,h.find);if(!p)return;const m=l.state.tr,g=Fl({state:l.state,transaction:m}),y={from:r-(p[0].length-s.length),to:o},{commands:w,chain:k,can:b}=new Wl({editor:n,state:g});h.handler({state:g,range:y,match:p,commands:w,chain:k,can:b})===null||!m.steps.length||(h.undoable&&m.setMeta(a,{transform:m,from:r,to:o,text:s}),l.dispatch(m),u=!0)}),u}function AR(t){const{editor:e,rules:n}=t,r=new ct({state:{init(){return null},apply(o,s,i){const a=o.getMeta(r);if(a)return a;const l=o.getMeta("applyInputRules");return!!l&&setTimeout(()=>{let{text:u}=l;typeof u=="string"?u=u:u=Zl(D.from(u),i.schema);const{from:f}=l,h=f+u.length;Ql({editor:e,from:f,to:h,text:u,rules:n,plugin:r})}),o.selectionSet||o.docChanged?null:s}},props:{handleTextInput(o,s,i,a){return Ql({editor:e,from:s,to:i,text:a,rules:n,plugin:r})},handleDOMEvents:{compositionend:o=>(setTimeout(()=>{const{$cursor:s}=o.state.selection;s&&Ql({editor:e,from:s.pos,to:s.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(o,s){if(s.key!=="Enter")return!1;const{$cursor:i}=o.state.selection;return i?Ql({editor:e,from:i.pos,to:i.pos,text:`
81
+ `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function _R(t){return Object.prototype.toString.call(t).slice(8,-1)}function ec(t){return _R(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function U1(t,e){const n={...t};return ec(t)&&ec(e)&&Object.keys(e).forEach(r=>{ec(e[r])&&ec(t[r])?n[r]=U1(t[r],e[r]):n[r]=e[r]}),n}var bf=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...Pe(ne(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Pe(ne(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>U1(this.options,t)});return e.name=this.name,e.parent=this.parent,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},na=class $v extends bf{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new $v(n)}static handleExit({editor:e,mark:n}){const{tr:r}=e.state,o=e.state.selection.$from;if(o.pos===o.end()){const i=o.marks();if(!!!i.find(c=>(c==null?void 0:c.type.name)===n.name))return!1;const l=i.find(c=>(c==null?void 0:c.type.name)===n.name);return l&&r.removeStoredMark(l),r.insertText(" ",o.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function IR(t){return typeof t=="number"}var BR=class{constructor(t){this.find=t.find,this.handler=t.handler}},NR=(t,e,n)=>{if(ff(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(o=>{const s=[o.text];return s.index=o.index,s.input=t,s.data=o.data,o.replaceWith&&(o.text.includes(o.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(o.replaceWith)),s}):[]};function PR(t){const{editor:e,state:n,from:r,to:o,rule:s,pasteEvent:i,dropEvent:a}=t,{commands:l,chain:c,can:u}=new Wl({editor:e,state:n}),f=[];return n.doc.nodesBetween(r,o,(p,m)=>{var g,y,w,k,b;if((y=(g=p.type)==null?void 0:g.spec)!=null&&y.code||!(p.isText||p.isTextblock||p.isInline))return;const S=(b=(k=(w=p.content)==null?void 0:w.size)!=null?k:p.nodeSize)!=null?b:0,v=Math.max(r,m),E=Math.min(o,m+S);if(v>=E)return;const T=p.isText?p.text||"":p.textBetween(v-m,E-m,void 0,"");NR(T,s.find,i).forEach(I=>{if(I.index===void 0)return;const z=v+I.index+1,F=z+I[0].length,j={from:n.tr.mapping.map(z),to:n.tr.mapping.map(F)},M=s.handler({state:n,range:j,match:I,commands:l,chain:c,can:u,pasteEvent:i,dropEvent:a});f.push(M)})}),f.every(p=>p!==null)}var tc=null,DR=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function OR(t){const{editor:e,rules:n}=t;let r=null,o=!1,s=!1,i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,a;try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}const l=({state:u,from:f,to:h,rule:p,pasteEvt:m})=>{const g=u.tr,y=Fl({state:u,transaction:g});if(!(!PR({editor:e,state:y,from:Math.max(f-1,0),to:h.b-1,rule:p,pasteEvent:m,dropEvent:a})||!g.steps.length)){try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}return i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,g}};return n.map(u=>new ct({view(f){const h=m=>{var g;r=(g=f.dom.parentElement)!=null&&g.contains(m.target)?f.dom.parentElement:null,r&&(tc=e)},p=()=>{tc&&(tc=null)};return window.addEventListener("dragstart",h),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",h),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(f,h)=>{if(s=r===f.dom.parentElement,a=h,!s){const p=tc;p!=null&&p.isEditable&&setTimeout(()=>{const m=p.state.selection;m&&p.commands.deleteRange({from:m.from,to:m.to})},10)}return!1},paste:(f,h)=>{var p;const m=(p=h.clipboardData)==null?void 0:p.getData("text/html");return i=h,o=!!(m!=null&&m.includes("data-pm-slice")),!1}}},appendTransaction:(f,h,p)=>{const m=f[0],g=m.getMeta("uiEvent")==="paste"&&!o,y=m.getMeta("uiEvent")==="drop"&&!s,w=m.getMeta("applyPasteRules"),k=!!w;if(!g&&!y&&!k)return;if(k){let{text:v}=w;typeof v=="string"?v=v:v=Zl(D.from(v),p.schema);const{from:E}=w,T=E+v.length,_=DR(v);return l({rule:u,state:p,from:E,to:{b:T},pasteEvt:_})}const b=h.doc.content.findDiffStart(p.doc.content),S=h.doc.content.findDiffEnd(p.doc.content);if(!(!IR(b)||!S||b===S.b))return l({rule:u,state:p,from:b,to:S,pasteEvt:i})}}))}var nc=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=yf(t),this.schema=D1(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Xl(e.name,this.schema)},r=ne(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return Yl([...this.extensions].reverse()).flatMap(r=>{const o={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:Xl(r.name,this.schema)},s=[],i=ne(r,"addKeyboardShortcuts",o);let a={};if(r.type==="mark"&&ne(r,"exitable",o)&&(a.ArrowRight=()=>na.handleExit({editor:t,mark:r})),i){const h=Object.fromEntries(Object.entries(i()).map(([p,m])=>[p,()=>m({editor:t})]));a={...a,...h}}const l=qO(a);s.push(l);const c=ne(r,"addInputRules",o);if(L1(r,t.options.enableInputRules)&&c){const h=c();if(h&&h.length){const p=AR({editor:t,rules:h}),m=Array.isArray(p)?p:[p];s.push(...m)}}const u=ne(r,"addPasteRules",o);if(L1(r,t.options.enablePasteRules)&&u){const h=u();if(h&&h.length){const p=OR({editor:t,rules:h});s.push(...p)}}const f=ne(r,"addProseMirrorPlugins",o);if(f){const h=f();s.push(...h)}return s})}get attributes(){return I1(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Js(this.extensions);return Object.fromEntries(e.filter(n=>!!ne(n,"addNodeView")).map(n=>{const r=this.attributes.filter(l=>l.type===n.name),o={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:kt(n.name,this.schema)},s=ne(n,"addNodeView",o);if(!s)return[];const i=s();if(!i)return[];const a=(l,c,u,f,h)=>{const p=Kl(l,r);return i({node:l,view:c,getPos:u,decorations:f,innerDecorations:h,editor:t,extension:n,HTMLAttributes:p})};return[n.name,a]}))}dispatchTransaction(t){const{editor:e}=this;return Yl([...this.extensions].reverse()).reduceRight((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:Xl(o.name,this.schema)},i=ne(o,"dispatchTransaction",s);return i?a=>{i.call(s,{transaction:a,next:r})}:r},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=Js(this.extensions);return Object.fromEntries(e.filter(n=>!!ne(n,"addMarkView")).map(n=>{const r=this.attributes.filter(a=>a.type===n.name),o={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:Dr(n.name,this.schema)},s=ne(n,"addMarkView",o);if(!s)return[];const i=(a,l,c)=>{const u=Kl(a,r);return s()({mark:a,view:l,inline:c,editor:t,extension:n,HTMLAttributes:u,updateAttributes:f=>{qR(a,t,f)}})};return[n.name,i]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Xl(e.name,this.schema)};e.type==="mark"&&((n=Pe(ne(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const o=ne(e,"onBeforeCreate",r),s=ne(e,"onCreate",r),i=ne(e,"onUpdate",r),a=ne(e,"onSelectionUpdate",r),l=ne(e,"onTransaction",r),c=ne(e,"onFocus",r),u=ne(e,"onBlur",r),f=ne(e,"onDestroy",r);o&&this.editor.on("beforeCreate",o),s&&this.editor.on("create",s),i&&this.editor.on("update",i),a&&this.editor.on("selectionUpdate",a),l&&this.editor.on("transaction",l),c&&this.editor.on("focus",c),u&&this.editor.on("blur",u),f&&this.editor.on("destroy",f)})}};nc.resolve=yf,nc.sort=Yl,nc.flatten=gf;var RR={};df(RR,{ClipboardTextSerializer:()=>H1,Commands:()=>j1,Delete:()=>Z1,Drop:()=>K1,Editable:()=>Y1,FocusEvents:()=>X1,Keymap:()=>G1,Paste:()=>J1,Tabindex:()=>Q1,TextDirection:()=>ek,focusEventsPluginKey:()=>q1});var Le=class Lv extends bf{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new Lv(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},H1=Le.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new ct({key:new Wt("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:o}=e,{ranges:s}=o,i=Math.min(...s.map(u=>u.$from.pos)),a=Math.max(...s.map(u=>u.$to.pos)),l=z1(n);return R1(r,{from:i,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:l})}}})]}}),j1=Le.create({name:"commands",addCommands(){return{...k1}}}),Z1=Le.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,o;const s=()=>{var i,a,l,c;if((c=(l=(a=(i=this.editor.options.coreExtensionOptions)==null?void 0:i.delete)==null?void 0:a.filterTransaction)==null?void 0:l.call(a,t))!=null?c:t.getMeta("y-sync$"))return;const u=F3(t.before,[t,...e]);J3(u).forEach(p=>{u.mapping.mapResult(p.oldRange.from).deletedAfter&&u.mapping.mapResult(p.oldRange.to).deletedBefore&&u.before.nodesBetween(p.oldRange.from,p.oldRange.to,(m,g)=>{const y=g+m.nodeSize-2,w=p.oldRange.from<=g&&y<=p.oldRange.to;this.editor.emit("delete",{type:"node",node:m,from:g,to:y,newFrom:u.mapping.map(g),newTo:u.mapping.map(y),deletedRange:p.oldRange,newRange:p.newRange,partial:!w,editor:this.editor,transaction:t,combinedTransform:u})})});const h=u.mapping;u.steps.forEach((p,m)=>{var g,y;if(p instanceof Un){const w=h.slice(m).map(p.from,-1),k=h.slice(m).map(p.to),b=h.invert().map(w,-1),S=h.invert().map(k),v=(g=u.doc.nodeAt(w-1))==null?void 0:g.marks.some(T=>T.eq(p.mark)),E=(y=u.doc.nodeAt(k))==null?void 0:y.marks.some(T=>T.eq(p.mark));this.editor.emit("delete",{type:"mark",mark:p.mark,from:p.from,to:p.to,deletedRange:{from:b,to:S},newRange:{from:w,to:k},partial:!!(E||v),editor:this.editor,transaction:t,combinedTransform:u})}})};(o=(r=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:r.async)==null||o?setTimeout(s,0):s()}}),K1=Le.create({name:"drop",addProseMirrorPlugins(){return[new ct({key:new Wt("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),Y1=Le.create({name:"editable",addProseMirrorPlugins(){return[new ct({key:new Wt("editable"),props:{editable:()=>this.editor.options.editable}})]}}),q1=new Wt("focusEvents"),X1=Le.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new ct({key:q1,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),G1=Le.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:i})=>[()=>i.undoInputRule(),()=>i.command(({tr:a})=>{const{selection:l,doc:c}=a,{empty:u,$anchor:f}=l,{pos:h,parent:p}=f,m=f.parent.isTextblock&&h>0?a.doc.resolve(h-1):f,g=m.parent.type.spec.isolating,y=f.pos-f.parentOffset,w=g&&m.parent.childCount===1?y===f.pos:fe.atStart(c).from===h;return!u||!p.type.isTextblock||p.textContent.length||!w||w&&f.parent.type.name==="paragraph"?!1:i.clearNodes()}),()=>i.deleteSelection(),()=>i.joinBackward(),()=>i.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:i})=>[()=>i.deleteSelection(),()=>i.deleteCurrentNode(),()=>i.joinForward(),()=>i.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:i})=>[()=>i.newlineInCode(),()=>i.createParagraphNear(),()=>i.liftEmptyBlock(),()=>i.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},o={...r},s={...r,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Hl()||T1()?s:o},addProseMirrorPlugins(){return[new ct({key:new Wt("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(g=>g.getMeta("composition")))return;const r=t.some(g=>g.docChanged)&&!e.doc.eq(n.doc),o=t.some(g=>g.getMeta("preventClearDocument"));if(!r||o)return;const{empty:s,from:i,to:a}=e.selection,l=fe.atStart(e.doc).from,c=fe.atEnd(e.doc).to;if(s||!(i===l&&a===c)||!Jl(n.doc))return;const h=n.tr,p=Fl({state:n,transaction:h}),{commands:m}=new Wl({editor:this.editor,state:p});if(m.clearNodes(),!!h.steps.length)return h}})]}}),J1=Le.create({name:"paste",addProseMirrorPlugins(){return[new ct({key:new Wt("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),Q1=Le.create({name:"tabindex",addProseMirrorPlugins(){return[new ct({key:new Wt("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),ek=Le.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Js(this.extensions);return[{types:t.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const n=e.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new ct({key:new Wt("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),zR=class ii{constructor(e,n,r=!1,o=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=n,this.currentNode=o}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new ii(n,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new ii(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new ii(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const o=n.isBlock&&!n.isTextblock,s=n.isAtom&&!n.isText,i=this.pos+r+(s?0:1);if(i<0||i>this.resolvedPos.doc.nodeSize-2)return;const a=this.resolvedPos.doc.resolve(i);if(!o&&a.depth<=this.depth)return;const l=new ii(a,this.editor,o,o?n:null);o&&(l.actualDepth=this.depth+1),e.push(new ii(a,this.editor,o,o?n:null))}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let r=null,o=this.parent;for(;o&&!r;){if(o.node.type.name===e)if(Object.keys(n).length>0){const s=o.node.attrs,i=Object.keys(n);for(let a=0;a<i.length;a+=1){const l=i[a];if(s[l]!==n[l])break}}else r=o;o=o.parent}return r}querySelector(e,n={}){return this.querySelectorAll(e,n,!0)[0]||null}querySelectorAll(e,n={},r=!1){let o=[];if(!this.children||this.children.length===0)return o;const s=Object.keys(n);return this.children.forEach(i=>{r&&o.length>0||(i.node.type.name===e&&s.every(l=>n[l]===i.node.attrs[l])&&o.push(i),!(r&&o.length>0)&&(o=o.concat(i.querySelectorAll(e,n,r))))}),o}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},$R=`.ProseMirror {
82
82
  position: relative;
83
83
  }
84
84
 
@@ -148,23 +148,24 @@ img.ProseMirror-separator {
148
148
 
149
149
  .ProseMirror-focused .ProseMirror-gapcursor {
150
150
  display: block;
151
- }`;function BR(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const o=document.createElement("style");return e&&o.setAttribute("nonce",e),o.setAttribute("data-tiptap-style",""),o.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(o),o}var PR=class extends yR{constructor(e={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:o})=>{throw o},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:Y3,createMappablePosition:q3},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:o,slice:s,moved:i})=>this.options.onDrop(o,s,i)),this.on("paste",({event:o,slice:s})=>this.options.onPaste(o,s)),this.on("delete",this.options.onDelete);const n=this.createDoc(),r=u1(n,this.options.autofocus);this.editorState=zs.create({doc:n,schema:this.schema,selection:r||void 0}),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(e),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const e=this.editorView.dom;e!=null&&e.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn("Failed to remove CSS element:",e)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=BR(IR,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(e,n=!0){this.setOptions({editable:e}),n&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,n)=>{if(this.editorView)return this.editorView[n];if(n==="state")return this.editorState;if(n in e)return Reflect.get(e,n);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${n}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,n){const r=g1(n)?n(e,[...this.state.plugins]):[...this.state.plugins,e],o=this.state.reconfigure({plugins:r});return this.view.updateState(o),o}unregisterPlugin(e){if(this.isDestroyed)return;const n=this.state.plugins;let r=n;if([].concat(e).forEach(s=>{const i=typeof s=="string"?`${s}$`:s.key;r=r.filter(a=>!a.key.startsWith(i))}),n.length===r.length)return;const o=this.state.reconfigure({plugins:r});return this.view.updateState(o),o}createExtensionManager(){var e,n;const o=[...this.options.enableCoreExtensions?[O1,B1.configure({blockSeparator:(n=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:n.blockSeparator}),P1,z1,$1,F1,D1,L1,N1,V1.configure({direction:this.options.textDirection})].filter(s=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[s.name]!==!1:!0):[],...this.options.extensions].filter(s=>["extension","node","mark"].includes(s==null?void 0:s.type));this.extensionManager=new ql(o,this)}createCommandManager(){this.commandManager=new Ol({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=nf(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(n){if(!(n instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(n.message))throw n;this.emit("contentError",{editor:this,error:n,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(r=>r.name!=="collaboration"),this.createExtensionManager()}}),e=nf(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return e}createView(e){const{editorProps:n,enableExtensionDispatchTransaction:r}=this.options,o=n.dispatchTransaction||this.dispatchTransaction.bind(this),s=r?this.extensionManager.dispatchTransaction(o):o;this.editorView=new Qw(e,{...n,attributes:{role:"textbox",...n==null?void 0:n.attributes},dispatchTransaction:s,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const i=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(i),this.prependClass(),this.injectCSS();const a=this.view.dom;a.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(e){this.isCapturingTransaction=!0,e(),this.isCapturingTransaction=!1;const n=this.capturedTransaction;return this.capturedTransaction=null,n}dispatchTransaction(e){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=e;return}e.steps.forEach(u=>{var d;return(d=this.capturedTransaction)==null?void 0:d.step(u)});return}const{state:n,transactions:r}=this.state.applyTransaction(e),o=!this.state.selection.eq(n.selection),s=r.includes(e),i=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:e,nextState:n}),!s)return;this.view.updateState(n),this.emit("transaction",{editor:this,transaction:e,appendedTransactions:r.slice(1)}),o&&this.emit("selectionUpdate",{editor:this,transaction:e});const a=r.findLast(u=>u.getMeta("focus")||u.getMeta("blur")),l=a==null?void 0:a.getMeta("focus"),c=a==null?void 0:a.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:a}),c&&this.emit("blur",{editor:this,event:c.event,transaction:a}),!(e.getMeta("preventUpdate")||!r.some(u=>u.docChanged)||i.doc.eq(n.doc))&&this.emit("update",{editor:this,transaction:e,appendedTransactions:r.slice(1)})}getAttributes(e){return V3(this.state,e)}isActive(e,n){const r=typeof e=="string"?e:null,o=typeof e=="string"?n:e;return Z3(this.state,r,o)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Ll(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:n=`
151
+ }`;function LR(t,e,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const o=document.createElement("style");return e&&o.setAttribute("nonce",e),o.setAttribute("data-tiptap-style",""),o.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(o),o}var VR=class extends xR{constructor(e={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:o})=>{throw o},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:nR,createMappablePosition:rR},this.setOptions(e),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:o,slice:s,moved:i})=>this.options.onDrop(o,s,i)),this.on("paste",({event:o,slice:s})=>this.options.onPaste(o,s)),this.on("delete",this.options.onDelete);const n=this.createDoc(),r=E1(n,this.options.autofocus);this.editorState=Hs.create({doc:n,schema:this.schema,selection:r||void 0}),this.options.element&&this.mount(this.options.element)}mount(e){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(e),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const e=this.editorView.dom;e!=null&&e.editor&&delete e.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(e){console.warn("Failed to remove CSS element:",e)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=LR($R,this.options.injectNonce))}setOptions(e={}){this.options={...this.options,...e},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(e,n=!0){this.setOptions({editable:e}),n&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:e=>{this.editorState=e},dispatch:e=>{this.dispatchTransaction(e)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(e,n)=>{if(this.editorView)return this.editorView[n];if(n==="state")return this.editorState;if(n in e)return Reflect.get(e,n);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${n}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(e,n){const r=_1(n)?n(e,[...this.state.plugins]):[...this.state.plugins,e],o=this.state.reconfigure({plugins:r});return this.view.updateState(o),o}unregisterPlugin(e){if(this.isDestroyed)return;const n=this.state.plugins;let r=n;if([].concat(e).forEach(s=>{const i=typeof s=="string"?`${s}$`:s.key;r=r.filter(a=>!a.key.startsWith(i))}),n.length===r.length)return;const o=this.state.reconfigure({plugins:r});return this.view.updateState(o),o}createExtensionManager(){var e,n;const o=[...this.options.enableCoreExtensions?[Y1,H1.configure({blockSeparator:(n=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:n.blockSeparator}),j1,X1,G1,Q1,K1,J1,Z1,ek.configure({direction:this.options.textDirection})].filter(s=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[s.name]!==!1:!0):[],...this.options.extensions].filter(s=>["extension","node","mark"].includes(s==null?void 0:s.type));this.extensionManager=new nc(o,this)}createCommandManager(){this.commandManager=new Wl({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=pf(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(n){if(!(n instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(n.message))throw n;this.emit("contentError",{editor:this,error:n,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(r=>r.name!=="collaboration"),this.createExtensionManager()}}),e=pf(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return e}createView(e){const{editorProps:n,enableExtensionDispatchTransaction:r}=this.options,o=n.dispatchTransaction||this.dispatchTransaction.bind(this),s=r?this.extensionManager.dispatchTransaction(o):o;this.editorView=new f1(e,{...n,attributes:{role:"textbox",...n==null?void 0:n.attributes},dispatchTransaction:s,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const i=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(i),this.prependClass(),this.injectCSS();const a=this.view.dom;a.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(e){this.isCapturingTransaction=!0,e(),this.isCapturingTransaction=!1;const n=this.capturedTransaction;return this.capturedTransaction=null,n}dispatchTransaction(e){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=e;return}e.steps.forEach(u=>{var f;return(f=this.capturedTransaction)==null?void 0:f.step(u)});return}const{state:n,transactions:r}=this.state.applyTransaction(e),o=!this.state.selection.eq(n.selection),s=r.includes(e),i=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:e,nextState:n}),!s)return;this.view.updateState(n),this.emit("transaction",{editor:this,transaction:e,appendedTransactions:r.slice(1)}),o&&this.emit("selectionUpdate",{editor:this,transaction:e});const a=r.findLast(u=>u.getMeta("focus")||u.getMeta("blur")),l=a==null?void 0:a.getMeta("focus"),c=a==null?void 0:a.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:a}),c&&this.emit("blur",{editor:this,event:c.event,transaction:a}),!(e.getMeta("preventUpdate")||!r.some(u=>u.docChanged)||i.doc.eq(n.doc))&&this.emit("update",{editor:this,transaction:e,appendedTransactions:r.slice(1)})}getAttributes(e){return q3(this.state,e)}isActive(e,n){const r=typeof e=="string"?e:null,o=typeof e=="string"?n:e;return eR(this.state,r,o)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Zl(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:n=`
152
152
 
153
- `,textSerializers:r={}}=e||{};return L3(this.state.doc,{blockSeparator:n,textSerializers:{...C1(this.schema),...r}})}get isEmpty(){return jl(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var e,n;return(n=(e=this.editorView)==null?void 0:e.isDestroyed)!=null?n:!0}$node(e,n){var r;return((r=this.$doc)==null?void 0:r.querySelector(e,n))||null}$nodes(e,n){var r;return((r=this.$doc)==null?void 0:r.querySelectorAll(e,n))||null}$pos(e){const n=this.state.doc.resolve(e);return new AR(n,this)}get $doc(){return this.$pos(0)}};function Jl(t){return new wR({find:t.find,handler:({state:e,range:n,match:r})=>{const o=Pe(t.getAttributes,void 0,r);if(o===!1||o===null)return null;const{tr:s}=e,i=r[r.length-1],a=r[0];if(i){const l=a.search(/\S/),c=n.from+a.indexOf(i),u=c+i.length;if(x1(n.from,n.to,e.doc).filter(p=>p.mark.type.excluded.find(g=>g===t.type&&g!==p.mark.type)).filter(p=>p.to>c).length)return null;u<n.to&&s.delete(u,n.to),c>n.from&&s.delete(n.from+l,c);const h=n.from+l+i.length;s.addMark(n.from+l,h,t.type.create(o||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}var NR={};Qd(NR,{createAtomBlockMarkdownSpec:()=>DR,createBlockMarkdownSpec:()=>OR,createInlineMarkdownSpec:()=>$R,parseAttributes:()=>df,parseIndentedBlocks:()=>LR,renderNestedMarkdownContent:()=>FR,serializeAttributes:()=>ff});function df(t){if(!(t!=null&&t.trim()))return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,c=>(n.push(c),`__QUOTED_${n.length-1}__`)),o=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(o){const c=o.map(u=>u.trim().slice(1));e.class=c.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const i=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(i)).forEach(([,c,u])=>{var d;const h=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),p=n[h];p&&(e[c]=p.slice(1,-1))});const l=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return l&&l.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function ff(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function DR(t){const{nodeName:e,name:n,parseAttributes:r=df,serializeAttributes:o=ff,defaultAttributes:s={},requiredAttributes:i=[],allowedAttributes:a}=t,l=n||e,c=u=>{if(!a)return u;const d={};return a.forEach(h=>{h in u&&(d[h]=u[h])}),d};return{parseMarkdown:(u,d)=>{const h={...s,...u.attributes};return d.createNode(e,h,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;const h=new RegExp(`^:::${l}(?:\\s|$)`,"m"),p=(d=u.match(h))==null?void 0:d.index;return p!==void 0?p:-1},tokenize(u,d,h){const p=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),m=u.match(p);if(!m)return;const g=m[1]||"",y=r(g);if(!i.find(k=>!(k in y)))return{type:e,raw:m[0],attributes:y}}},renderMarkdown:u=>{const d=c(u.attrs||{}),h=o(d),p=h?` {${h}}`:"";return`:::${l}${p} :::`}}}function OR(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=df,serializeAttributes:s=ff,defaultAttributes:i={},content:a="block",allowedAttributes:l}=t,c=n||e,u=d=>{if(!l)return d;const h={};return l.forEach(p=>{p in d&&(h[p]=d[p])}),h};return{parseMarkdown:(d,h)=>{let p;if(r){const g=r(d);p=typeof g=="string"?[{type:"text",text:g}]:g}else a==="block"?p=h.parseChildren(d.tokens||[]):p=h.parseInline(d.tokens||[]);const m={...i,...d.attributes};return h.createNode(e,m,p)},markdownTokenizer:{name:e,level:"block",start(d){var h;const p=new RegExp(`^:::${c}`,"m"),m=(h=d.match(p))==null?void 0:h.index;return m!==void 0?m:-1},tokenize(d,h,p){var m;const g=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),y=d.match(g);if(!y)return;const[w,k=""]=y,b=o(k);let S=1;const v=w.length;let x="";const T=/^:::([\w-]*)(\s.*)?/gm,A=d.slice(v);for(T.lastIndex=0;;){const P=T.exec(A);if(P===null)break;const $=P.index,V=P[1];if(!((m=P[2])!=null&&m.endsWith(":::"))){if(V)S+=1;else if(S-=1,S===0){const U=A.slice(0,$);x=U.trim();const M=d.slice(0,v+$+P[0].length);let L=[];if(x)if(a==="block")for(L=p.blockTokens(U),L.forEach(q=>{q.text&&(!q.tokens||q.tokens.length===0)&&(q.tokens=p.inlineTokens(q.text))});L.length>0;){const q=L[L.length-1];if(q.type==="paragraph"&&(!q.text||q.text.trim()===""))L.pop();else break}else L=p.inlineTokens(x);return{type:e,raw:M,attributes:b,content:x,tokens:L}}}}}},renderMarkdown:(d,h)=>{const p=u(d.attrs||{}),m=s(p),g=m?` {${m}}`:"",y=h.renderChildren(d.content||[],`
153
+ `,textSerializers:r={}}=e||{};return K3(this.state.doc,{blockSeparator:n,textSerializers:{...z1(this.schema),...r}})}get isEmpty(){return Jl(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var e,n;return(n=(e=this.editorView)==null?void 0:e.isDestroyed)!=null?n:!0}$node(e,n){var r;return((r=this.$doc)==null?void 0:r.querySelector(e,n))||null}$nodes(e,n){var r;return((r=this.$doc)==null?void 0:r.querySelectorAll(e,n))||null}$pos(e){const n=this.state.doc.resolve(e);return new zR(n,this)}get $doc(){return this.$pos(0)}};function rc(t){return new TR({find:t.find,handler:({state:e,range:n,match:r})=>{const o=Pe(t.getAttributes,void 0,r);if(o===!1||o===null)return null;const{tr:s}=e,i=r[r.length-1],a=r[0];if(i){const l=a.search(/\S/),c=n.from+a.indexOf(i),u=c+i.length;if($1(n.from,n.to,e.doc).filter(p=>p.mark.type.excluded.find(g=>g===t.type&&g!==p.mark.type)).filter(p=>p.to>c).length)return null;u<n.to&&s.delete(u,n.to),c>n.from&&s.delete(n.from+l,c);const h=n.from+l+i.length;s.addMark(n.from+l,h,t.type.create(o||{})),s.removeStoredMark(t.type)}},undoable:t.undoable})}var FR={};df(FR,{createAtomBlockMarkdownSpec:()=>WR,createBlockMarkdownSpec:()=>UR,createInlineMarkdownSpec:()=>ZR,parseAttributes:()=>Sf,parseIndentedBlocks:()=>KR,renderNestedMarkdownContent:()=>YR,serializeAttributes:()=>Ef});function Sf(t){if(!(t!=null&&t.trim()))return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,c=>(n.push(c),`__QUOTED_${n.length-1}__`)),o=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(o){const c=o.map(u=>u.trim().slice(1));e.class=c.join(" ")}const s=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);s&&(e.id=s[1]);const i=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(i)).forEach(([,c,u])=>{var f;const h=parseInt(((f=u.match(/__QUOTED_(\d+)__/))==null?void 0:f[1])||"0",10),p=n[h];p&&(e[c]=p.slice(1,-1))});const l=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return l&&l.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function Ef(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,r])=>{n==="class"||n==="id"||(r===!0?e.push(n):r!==!1&&r!=null&&e.push(`${n}="${String(r)}"`))}),e.join(" ")}function WR(t){const{nodeName:e,name:n,parseAttributes:r=Sf,serializeAttributes:o=Ef,defaultAttributes:s={},requiredAttributes:i=[],allowedAttributes:a}=t,l=n||e,c=u=>{if(!a)return u;const f={};return a.forEach(h=>{h in u&&(f[h]=u[h])}),f};return{parseMarkdown:(u,f)=>{const h={...s,...u.attributes};return f.createNode(e,h,[])},markdownTokenizer:{name:e,level:"block",start(u){var f;const h=new RegExp(`^:::${l}(?:\\s|$)`,"m"),p=(f=u.match(h))==null?void 0:f.index;return p!==void 0?p:-1},tokenize(u,f,h){const p=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),m=u.match(p);if(!m)return;const g=m[1]||"",y=r(g);if(!i.find(k=>!(k in y)))return{type:e,raw:m[0],attributes:y}}},renderMarkdown:u=>{const f=c(u.attrs||{}),h=o(f),p=h?` {${h}}`:"";return`:::${l}${p} :::`}}}function UR(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=Sf,serializeAttributes:s=Ef,defaultAttributes:i={},content:a="block",allowedAttributes:l}=t,c=n||e,u=f=>{if(!l)return f;const h={};return l.forEach(p=>{p in f&&(h[p]=f[p])}),h};return{parseMarkdown:(f,h)=>{let p;if(r){const g=r(f);p=typeof g=="string"?[{type:"text",text:g}]:g}else a==="block"?p=h.parseChildren(f.tokens||[]):p=h.parseInline(f.tokens||[]);const m={...i,...f.attributes};return h.createNode(e,m,p)},markdownTokenizer:{name:e,level:"block",start(f){var h;const p=new RegExp(`^:::${c}`,"m"),m=(h=f.match(p))==null?void 0:h.index;return m!==void 0?m:-1},tokenize(f,h,p){var m;const g=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),y=f.match(g);if(!y)return;const[w,k=""]=y,b=o(k);let S=1;const v=w.length;let E="";const T=/^:::([\w-]*)(\s.*)?/gm,_=f.slice(v);for(T.lastIndex=0;;){const I=T.exec(_);if(I===null)break;const z=I.index,F=I[1];if(!((m=I[2])!=null&&m.endsWith(":::"))){if(F)S+=1;else if(S-=1,S===0){const j=_.slice(0,z);E=j.trim();const M=f.slice(0,v+z+I[0].length);let V=[];if(E)if(a==="block")for(V=p.blockTokens(j),V.forEach(K=>{K.text&&(!K.tokens||K.tokens.length===0)&&(K.tokens=p.inlineTokens(K.text))});V.length>0;){const K=V[V.length-1];if(K.type==="paragraph"&&(!K.text||K.text.trim()===""))V.pop();else break}else V=p.inlineTokens(E);return{type:e,raw:M,attributes:b,content:E,tokens:V}}}}}},renderMarkdown:(f,h)=>{const p=u(f.attrs||{}),m=s(p),g=m?` {${m}}`:"",y=h.renderChildren(f.content||[],`
154
154
 
155
155
  `);return`:::${c}${g}
156
156
 
157
157
  ${y}
158
158
 
159
- :::`}}}function RR(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,o,s,i]=r;e[o]=s||i,r=n.exec(t)}return e}function zR(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function $R(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=RR,serializeAttributes:s=zR,defaultAttributes:i={},selfClosing:a=!1,allowedAttributes:l}=t,c=n||e,u=h=>{if(!l)return h;const p={};return l.forEach(m=>{const g=typeof m=="string"?m:m.name,y=typeof m=="string"?void 0:m.skipIfDefault;if(g in h){const w=h[g];if(y!==void 0&&w===y)return;p[g]=w}}),p},d=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,p)=>{const m={...i,...h.attributes};if(a)return p.createNode(e,m);const g=r?r(h):h.content||"";return g?p.createNode(e,m,[p.createTextNode(g)]):p.createNode(e,m,[])},markdownTokenizer:{name:e,level:"inline",start(h){const p=a?new RegExp(`\\[${d}\\s*[^\\]]*\\]`):new RegExp(`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),m=h.match(p),g=m==null?void 0:m.index;return g!==void 0?g:-1},tokenize(h,p,m){const g=a?new RegExp(`^\\[${d}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),y=h.match(g);if(!y)return;let w="",k="";if(a){const[,S]=y;k=S}else{const[,S,v]=y;k=S,w=v||""}const b=o(k.trim());return{type:e,raw:y[0],content:w.trim(),attributes:b}}},renderMarkdown:h=>{let p="";r?p=r(h):h.content&&h.content.length>0&&(p=h.content.filter(w=>w.type==="text").map(w=>w.text).join(""));const m=u(h.attrs||{}),g=s(m),y=g?` ${g}`:"";return a?`[${c}${y}]`:`[${c}${y}]${p}[/${c}]`}}}function LR(t,e,n){var r,o,s,i;const a=t.split(`
160
- `),l=[];let c="",u=0;const d=e.baseIndentSize||2;for(;u<a.length;){const h=a[u],p=h.match(e.itemPattern);if(!p){if(l.length>0)break;if(h.trim()===""){u+=1,c=`${c}${h}
159
+ :::`}}}function HR(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;r!==null;){const[,o,s,i]=r;e[o]=s||i,r=n.exec(t)}return e}function jR(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function ZR(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=HR,serializeAttributes:s=jR,defaultAttributes:i={},selfClosing:a=!1,allowedAttributes:l}=t,c=n||e,u=h=>{if(!l)return h;const p={};return l.forEach(m=>{const g=typeof m=="string"?m:m.name,y=typeof m=="string"?void 0:m.skipIfDefault;if(g in h){const w=h[g];if(y!==void 0&&w===y)return;p[g]=w}}),p},f=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,p)=>{const m={...i,...h.attributes};if(a)return p.createNode(e,m);const g=r?r(h):h.content||"";return g?p.createNode(e,m,[p.createTextNode(g)]):p.createNode(e,m,[])},markdownTokenizer:{name:e,level:"inline",start(h){const p=a?new RegExp(`\\[${f}\\s*[^\\]]*\\]`):new RegExp(`\\[${f}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${f}\\]`),m=h.match(p),g=m==null?void 0:m.index;return g!==void 0?g:-1},tokenize(h,p,m){const g=a?new RegExp(`^\\[${f}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${f}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${f}\\]`),y=h.match(g);if(!y)return;let w="",k="";if(a){const[,S]=y;k=S}else{const[,S,v]=y;k=S,w=v||""}const b=o(k.trim());return{type:e,raw:y[0],content:w.trim(),attributes:b}}},renderMarkdown:h=>{let p="";r?p=r(h):h.content&&h.content.length>0&&(p=h.content.filter(w=>w.type==="text").map(w=>w.text).join(""));const m=u(h.attrs||{}),g=s(m),y=g?` ${g}`:"";return a?`[${c}${y}]`:`[${c}${y}]${p}[/${c}]`}}}function KR(t,e,n){var r,o,s,i;const a=t.split(`
160
+ `),l=[];let c="",u=0;const f=e.baseIndentSize||2;for(;u<a.length;){const h=a[u],p=h.match(e.itemPattern);if(!p){if(l.length>0)break;if(h.trim()===""){u+=1,c=`${c}${h}
161
161
  `;continue}else return}const m=e.extractItemData(p),{indentLevel:g,mainContent:y}=m;c=`${c}${h}
162
- `;const w=[y];for(u+=1;u<a.length;){const v=a[u];if(v.trim()===""){const T=a.slice(u+1).findIndex($=>$.trim()!=="");if(T===-1)break;if((((o=(r=a[u+1+T].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:o.length)||0)>g){w.push(v),c=`${c}${v}
162
+ `;const w=[y];for(u+=1;u<a.length;){const v=a[u];if(v.trim()===""){const T=a.slice(u+1).findIndex(z=>z.trim()!=="");if(T===-1)break;if((((o=(r=a[u+1+T].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:o.length)||0)>g){w.push(v),c=`${c}${v}
163
163
  `,u+=1;continue}else break}if((((i=(s=v.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:i.length)||0)>g)w.push(v),c=`${c}${v}
164
- `,u+=1;else break}let k;const b=w.slice(1);if(b.length>0){const v=b.map(x=>x.slice(g+d)).join(`
165
- `);v.trim()&&(e.customNestedParser?k=e.customNestedParser(v):k=n.blockTokens(v))}const S=e.createToken(m,k);l.push(S)}if(l.length!==0)return{items:l,raw:c}}function FR(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const o=typeof n=="function"?n(r):n,[s,...i]=t.content,a=e.renderChildren([s]),l=[`${o}${a}`];return i&&i.length>0&&i.forEach(c=>{const u=e.renderChildren([c]);if(u){const d=u.split(`
164
+ `,u+=1;else break}let k;const b=w.slice(1);if(b.length>0){const v=b.map(E=>E.slice(g+f)).join(`
165
+ `);v.trim()&&(e.customNestedParser?k=e.customNestedParser(v):k=n.blockTokens(v))}const S=e.createToken(m,k);l.push(S)}if(l.length!==0)return{items:l,raw:c}}function YR(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const o=typeof n=="function"?n(r):n,[s,...i]=t.content,a=e.renderChildren([s]),l=[`${o}${a}`];return i&&i.length>0&&i.forEach(c=>{const u=e.renderChildren([c]);if(u){const f=u.split(`
166
166
  `).map(h=>h?e.indent(h):"").join(`
167
- `);l.push(d)}}),l.join(`
168
- `)}function VR(t,e,n={}){const{state:r}=e,{doc:o,tr:s}=r,i=t;o.descendants((a,l)=>{const c=s.mapping.map(l),u=s.mapping.map(l)+a.nodeSize;let d=null;if(a.marks.forEach(p=>{if(p!==i)return!1;d=p}),!d)return;let h=!1;if(Object.keys(n).forEach(p=>{n[p]!==d.attrs[p]&&(h=!0)}),h){const p=t.type.create({...t.attrs,...n});s.removeMark(c,u,t.type),s.addMark(c,u,p)}}),s.docChanged&&e.view.dispatch(s)}var hf=class Bv extends uf{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Bv(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function Xl(t){return new ER({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:o})=>{const s=Pe(t.getAttributes,void 0,r,o);if(s===!1||s===null)return null;const{tr:i}=e,a=r[r.length-1],l=r[0];let c=n.to;if(a){const u=l.search(/\S/),d=n.from+l.indexOf(a),h=d+a.length;if(x1(n.from,n.to,e.doc).filter(m=>m.mark.type.excluded.find(y=>y===t.type&&y!==m.mark.type)).filter(m=>m.to>d).length)return null;h<n.to&&i.delete(h,n.to),d>n.from&&i.delete(n.from+u,d),c=n.from+u+a.length,i.addMark(n.from+u,c,t.type.create(s||{})),i.removeStoredMark(t.type)}}})}function W1(t){return f.customRef((e,n)=>({get(){return e(),t},set(r){t=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{n()})})}}))}var WR=class extends PR{constructor(t={}){return super(t),this.contentComponent=null,this.appContext=null,this.reactiveState=W1(this.view.state),this.reactiveExtensionStorage=W1(this.extensionStorage),this.on("beforeTransaction",({nextState:e})=>{this.reactiveState.value=e,this.reactiveExtensionStorage.value=this.extensionStorage}),f.markRaw(this)}get state(){return this.reactiveState?this.reactiveState.value:this.view.state}get storage(){return this.reactiveExtensionStorage?this.reactiveExtensionStorage.value:super.storage}registerPlugin(t,e){const n=super.registerPlugin(t,e);return this.reactiveState&&(this.reactiveState.value=n),n}unregisterPlugin(t){const e=super.unregisterPlugin(t);return this.reactiveState&&e&&(this.reactiveState.value=e),e}},UR=f.defineComponent({name:"EditorContent",props:{editor:{default:null,type:Object}},setup(t){const e=f.ref(),n=f.getCurrentInstance();return f.watchEffect(()=>{const r=t.editor;r&&r.options.element&&e.value&&f.nextTick(()=>{var o;if(!e.value||!((o=r.view.dom)!=null&&o.parentNode))return;const s=f.unref(e.value);e.value.append(...r.view.dom.parentNode.childNodes),r.contentComponent=n.ctx._,n&&(r.appContext={...n.appContext,provides:n.provides}),r.setOptions({element:s}),r.createNodeViews()})}),f.onBeforeUnmount(()=>{const r=t.editor;r&&(r.contentComponent=null,r.appContext=null)}),{rootEl:e}},render(){return f.h("div",{ref:t=>{this.rootEl=t}})}});f.defineComponent({name:"NodeViewContent",props:{as:{type:String,default:"div"}},render(){return f.h(this.as,{style:{whiteSpace:"pre-wrap"},"data-node-view-content":""})}}),f.defineComponent({name:"NodeViewWrapper",props:{as:{type:String,default:"div"}},inject:["onDragStart","decorationClasses"],render(){var t,e;return f.h(this.as,{class:this.decorationClasses,style:{whiteSpace:"normal"},"data-node-view-wrapper":"",onDragstart:this.onDragStart},(e=(t=this.$slots).default)==null?void 0:e.call(t))}}),f.defineComponent({name:"MarkViewContent",props:{as:{type:String,default:"span"}},render(){return f.h(this.as,{style:{whiteSpace:"inherit"},"data-mark-view-content":""})}});var HR=hf.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
167
+ `);l.push(f)}}),l.join(`
168
+ `)}function qR(t,e,n={}){const{state:r}=e,{doc:o,tr:s}=r,i=t;o.descendants((a,l)=>{const c=s.mapping.map(l),u=s.mapping.map(l)+a.nodeSize;let f=null;if(a.marks.forEach(p=>{if(p!==i)return!1;f=p}),!f)return;let h=!1;if(Object.keys(n).forEach(p=>{n[p]!==f.attrs[p]&&(h=!0)}),h){const p=t.type.create({...t.attrs,...n});s.removeMark(c,u,t.type),s.addMark(c,u,p)}}),s.docChanged&&e.view.dispatch(s)}var Cf=class Vv extends bf{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new Vv(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function oc(t){return new BR({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:o})=>{const s=Pe(t.getAttributes,void 0,r,o);if(s===!1||s===null)return null;const{tr:i}=e,a=r[r.length-1],l=r[0];let c=n.to;if(a){const u=l.search(/\S/),f=n.from+l.indexOf(a),h=f+a.length;if($1(n.from,n.to,e.doc).filter(m=>m.mark.type.excluded.find(y=>y===t.type&&y!==m.mark.type)).filter(m=>m.to>f).length)return null;h<n.to&&i.delete(h,n.to),f>n.from&&i.delete(n.from+u,f),c=n.from+u+a.length,i.addMark(n.from+u,c,t.type.create(s||{})),i.removeStoredMark(t.type)}}})}function tk(t){return d.customRef((e,n)=>({get(){return e(),t},set(r){t=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{n()})})}}))}var XR=class extends VR{constructor(t={}){return super(t),this.contentComponent=null,this.appContext=null,this.reactiveState=tk(this.view.state),this.reactiveExtensionStorage=tk(this.extensionStorage),this.on("beforeTransaction",({nextState:e})=>{this.reactiveState.value=e,this.reactiveExtensionStorage.value=this.extensionStorage}),d.markRaw(this)}get state(){return this.reactiveState?this.reactiveState.value:this.view.state}get storage(){return this.reactiveExtensionStorage?this.reactiveExtensionStorage.value:super.storage}registerPlugin(t,e){const n=super.registerPlugin(t,e);return this.reactiveState&&(this.reactiveState.value=n),n}unregisterPlugin(t){const e=super.unregisterPlugin(t);return this.reactiveState&&e&&(this.reactiveState.value=e),e}},GR=d.defineComponent({name:"EditorContent",props:{editor:{default:null,type:Object}},setup(t){const e=d.ref(),n=d.getCurrentInstance();return d.watchEffect(()=>{const r=t.editor;r&&r.options.element&&e.value&&d.nextTick(()=>{var o;if(!e.value||!((o=r.view.dom)!=null&&o.parentNode))return;const s=d.unref(e.value);e.value.append(...r.view.dom.parentNode.childNodes),r.contentComponent=n.ctx._,n&&(r.appContext={...n.appContext,provides:n.provides}),r.setOptions({element:s}),r.createNodeViews()})}),d.onBeforeUnmount(()=>{const r=t.editor;r&&(r.contentComponent=null,r.appContext=null)}),{rootEl:e}},render(){return d.h("div",{ref:t=>{this.rootEl=t}})}});d.defineComponent({name:"NodeViewContent",props:{as:{type:String,default:"div"}},render(){return d.h(this.as,{style:{whiteSpace:"pre-wrap"},"data-node-view-content":""})}}),d.defineComponent({name:"NodeViewWrapper",props:{as:{type:String,default:"div"}},inject:["onDragStart","decorationClasses"],render(){var t,e;return d.h(this.as,{class:this.decorationClasses,style:{whiteSpace:"normal"},"data-node-view-wrapper":"",onDragstart:this.onDragStart},(e=(t=this.$slots).default)==null?void 0:e.call(t))}}),d.defineComponent({name:"MarkViewContent",props:{as:{type:String,default:"span"}},render(){return d.h(this.as,{style:{whiteSpace:"inherit"},"data-mark-view-content":""})}});var JR=Cf.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
169
169
 
170
- `):""}),U1=HR,jR=hf.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Zs(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];return n.length===1&&n[0].type==="image"?e.parseChildren([n[0]]):e.createNode("paragraph",void 0,e.parseInline(n))},renderMarkdown:(t,e)=>!t||!Array.isArray(t.content)?"":e.renderChildren(t.content),addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),H1=jR,ZR=hf.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),j1=ZR,Z1=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},KR=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,YR=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,qR=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,JR=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,XR=Yi.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return Z1("strong",{...Zs(this.options.HTMLAttributes,t),children:Z1("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Jl({find:KR,type:this.type}),Jl({find:qR,type:this.type})]},addPasteRules(){return[Xl({find:YR,type:this.type}),Xl({find:JR,type:this.type})]}}),K1=XR,GR=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,QR=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,ez=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,tz=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,nz=Yi.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",Zs(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Jl({find:GR,type:this.type}),Jl({find:ez,type:this.type})]},addPasteRules(){return[Xl({find:QR,type:this.type}),Xl({find:tz,type:this.type})]}}),Y1=nz,rz=Yi.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",Zs(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown(t,e){return`++${e.renderChildren(t)}++`},markdownTokenizer:{name:"underline",level:"inline",start(t){return t.indexOf("++")},tokenize(t,e,n){const o=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!o)return;const s=o[2].trim();return{type:"underline",raw:o[0],text:s,tokens:n.inlineTokens(s)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),q1=rz,oz=$e.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),J1=oz,sz=20,X1=(t,e=0)=>{const n=[];return!t.children.length||e>sz||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...X1(r,e+1))}),n},iz=t=>{if(!t.children.length)return;const e=X1(t);e&&e.forEach(n=>{var r,o;const s=n.getAttribute("style"),i=(o=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:o.getAttribute("style");n.setAttribute("style",`${i};${s}`)})},pf=Yi.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&iz(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Zs(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(o=>o.type===this.type).some(o=>Object.values(o.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),az=$e.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(o=>o.trim()).filter(Boolean);for(let o=r.length-1;o>=0;o-=1){const s=r[o].split(":");if(s.length>=2){const i=s[0].trim().toLowerCase(),a=s.slice(1).join(":").trim();if(i==="background-color")return a.replace(/['"]+/g,"")}}}return(e=t.style.backgroundColor)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),G1=$e.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(o=>o.trim()).filter(Boolean);for(let o=r.length-1;o>=0;o-=1){const s=r[o].split(":");if(s.length>=2){const i=s[0].trim().toLowerCase(),a=s.slice(1).join(":").trim();if(i==="color")return a.replace(/['"]+/g,"")}}}return(e=t.style.color)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),lz=$e.create({name:"fontFamily",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>t.style.fontFamily,renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands(){return{setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()}}}),cz=$e.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>t.style.fontSize,renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),uz=$e.create({name:"lineHeight",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>t.style.lineHeight,renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands(){return{setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()}}});$e.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(az.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(G1.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(lz.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(cz.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(uz.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(pf.configure(this.options.textStyle)),t}});var Q1=G1;function dz(t={}){return new at({view(e){return new fz(e,t)}})}class fz{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(o=>{let s=i=>{this[o](i)};return e.dom.addEventListener(o,s),{name:o,handler:s}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,o=this.editorView.dom,s=o.getBoundingClientRect(),i=s.width/o.offsetWidth,a=s.height/o.offsetHeight;if(n){let d=e.nodeBefore,h=e.nodeAfter;if(d||h){let p=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(p){let m=p.getBoundingClientRect(),g=d?m.bottom:m.top;d&&h&&(g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*a;r={left:m.left,right:m.right,top:g-y,bottom:g+y}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*i;r={left:d.left-h,right:d.left+h,top:d.top,bottom:d.bottom}}let l=this.editorView.dom.offsetParent;this.element||(this.element=l.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,u;if(!l||l==document.body&&getComputedStyle(l).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=l.getBoundingClientRect(),h=d.width/l.offsetWidth,p=d.height/l.offsetHeight;c=d.left-l.scrollLeft*h,u=d.top-l.scrollTop*p}this.element.style.left=(r.left-c)/i+"px",this.element.style.top=(r.top-u)/a+"px",this.element.style.width=(r.right-r.left)/i+"px",this.element.style.height=(r.bottom-r.top)/a+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),o=r&&r.type.spec.disableDropCursor,s=typeof o=="function"?o(this.editorView,n,e):o;if(n&&!s){let i=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let a=w0(this.editorView.state.doc,i,this.editorView.dragging.slice);a!=null&&(i=a)}this.setCursor(i),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class Ze extends fe{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return Ze.valid(r)?new Ze(r):fe.near(r)}content(){return j.empty}eq(e){return e instanceof Ze&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Ze(e.resolve(n.pos))}getBookmark(){return new mf(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!hz(e)||!pz(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let o=n.contentMatchAt(e.index()).defaultType;return o&&o.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&Ze.valid(e))return e;let o=e.pos,s=null;for(let i=e.depth;;i--){let a=e.node(i);if(n>0?e.indexAfter(i)<a.childCount:e.index(i)>0){s=a.child(n>0?e.indexAfter(i):e.index(i)-1);break}else if(i==0)return null;o+=n;let l=e.doc.resolve(o);if(Ze.valid(l))return l}for(;;){let i=n>0?s.firstChild:s.lastChild;if(!i){if(s.isAtom&&!s.isText&&!re.isSelectable(s)){e=e.doc.resolve(o+s.nodeSize*n),r=!1;continue e}break}s=i,o+=n;let a=e.doc.resolve(o);if(Ze.valid(a))return a}return null}}}Ze.prototype.visible=!1,Ze.findFrom=Ze.findGapCursorFrom,fe.jsonID("gapcursor",Ze);class mf{constructor(e){this.pos=e}map(e){return new mf(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return Ze.valid(n)?new Ze(n):fe.near(n)}}function ek(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function hz(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n-1);;o=o.lastChild){if(o.childCount==0&&!o.inlineContent||ek(o.type))return!0;if(o.inlineContent)return!1}}return!0}function pz(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n);;o=o.firstChild){if(o.childCount==0&&!o.inlineContent||ek(o.type))return!0;if(o.inlineContent)return!1}}return!0}function mz(){return new at({props:{decorations:kz,createSelectionBetween(t,e,n){return e.pos==n.pos&&Ze.valid(n)?new Ze(n):null},handleClick:yz,handleKeyDown:gz,handleDOMEvents:{beforeinput:wz}}})}const gz=s1({ArrowLeft:Gl("horiz",-1),ArrowRight:Gl("horiz",1),ArrowUp:Gl("vert",-1),ArrowDown:Gl("vert",1)});function Gl(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,o,s){let i=r.selection,a=e>0?i.$to:i.$from,l=i.empty;if(i instanceof ue){if(!s.endOfTextblock(n)||a.depth==0)return!1;l=!1,a=r.doc.resolve(e>0?a.after():a.before())}let c=Ze.findGapCursorFrom(a,e,l);return c?(o&&o(r.tr.setSelection(new Ze(c))),!0):!1}}function yz(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!Ze.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&re.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new Ze(r))),!0)}function wz(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof Ze))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=D.empty;for(let i=r.length-1;i>=0;i--)o=D.from(r[i].createAndFill(null,o));let s=t.state.tr.replace(n.pos,n.pos,new j(o,0,0));return s.setSelection(ue.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function kz(t){if(!(t.selection instanceof Ze))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Ue.create(t.doc,[jt.widget(t.selection.head,e,{key:"gapcursor"})])}var Ql=200,kt=function(){};kt.prototype.append=function(e){return e.length?(e=kt.from(e),!this.length&&e||e.length<Ql&&this.leafAppend(e)||this.length<Ql&&e.leafPrepend(this)||this.appendInner(e)):this},kt.prototype.prepend=function(e){return e.length?kt.from(e).append(this):this},kt.prototype.appendInner=function(e){return new vz(this,e)},kt.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?kt.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))},kt.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},kt.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)},kt.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var o=[];return this.forEach(function(s,i){return o.push(e(s,i))},n,r),o},kt.from=function(e){return e instanceof kt?e:e&&e.length?new tk(e):kt.empty};var tk=function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(o,s){return o==0&&s==this.length?this:new e(this.values.slice(o,s))},e.prototype.getInner=function(o){return this.values[o]},e.prototype.forEachInner=function(o,s,i,a){for(var l=s;l<i;l++)if(o(this.values[l],a+l)===!1)return!1},e.prototype.forEachInvertedInner=function(o,s,i,a){for(var l=s-1;l>=i;l--)if(o(this.values[l],a+l)===!1)return!1},e.prototype.leafAppend=function(o){if(this.length+o.length<=Ql)return new e(this.values.concat(o.flatten()))},e.prototype.leafPrepend=function(o){if(this.length+o.length<=Ql)return new e(o.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e}(kt);kt.empty=new tk([]);var vz=function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,o,s,i){var a=this.left.length;if(o<a&&this.left.forEachInner(r,o,Math.min(s,a),i)===!1||s>a&&this.right.forEachInner(r,Math.max(o-a,0),Math.min(this.length,s)-a,i+a)===!1)return!1},e.prototype.forEachInvertedInner=function(r,o,s,i){var a=this.left.length;if(o>a&&this.right.forEachInvertedInner(r,o-a,Math.max(s,a)-a,i+a)===!1||s<a&&this.left.forEachInvertedInner(r,Math.min(o,a),s,i)===!1)return!1},e.prototype.sliceInner=function(r,o){if(r==0&&o==this.length)return this;var s=this.left.length;return o<=s?this.left.slice(r,o):r>=s?this.right.slice(r-s,o-s):this.left.slice(r,s).append(this.right.slice(0,o-s))},e.prototype.leafAppend=function(r){var o=this.right.leafAppend(r);if(o)return new e(this.left,o)},e.prototype.leafPrepend=function(r){var o=this.left.leafPrepend(r);if(o)return new e(o,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e}(kt);const bz=500;class Vn{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let o,s;n&&(o=this.remapping(r,this.items.length),s=o.maps.length);let i=e.tr,a,l,c=[],u=[];return this.items.forEach((d,h)=>{if(!d.step){o||(o=this.remapping(r,h+1),s=o.maps.length),s--,u.push(d);return}if(o){u.push(new or(d.map));let p=d.step.map(o.slice(s)),m;p&&i.maybeStep(p).doc&&(m=i.mapping.maps[i.mapping.maps.length-1],c.push(new or(m,void 0,void 0,c.length+u.length))),s--,m&&o.appendMap(m,s)}else i.maybeStep(d.step);if(d.selection)return a=o?d.selection.map(o.slice(s)):d.selection,l=new Vn(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:l,transform:i,selection:a}}addTransform(e,n,r,o){let s=[],i=this.eventCount,a=this.items,l=!o&&a.length?a.get(a.length-1):null;for(let u=0;u<e.steps.length;u++){let d=e.steps[u].invert(e.docs[u]),h=new or(e.mapping.maps[u],d,n),p;(p=l&&l.merge(h))&&(h=p,u?s.pop():a=a.slice(0,a.length-1)),s.push(h),n&&(i++,n=void 0),o||(l=h)}let c=i-r.depth;return c>Ez&&(a=Sz(a,c),i-=c),new Vn(a.append(s),i)}remapping(e,n){let r=new Bi;return this.items.forEach((o,s)=>{let i=o.mirrorOffset!=null&&s-o.mirrorOffset>=e?r.maps.length-o.mirrorOffset:void 0;r.appendMap(o.map,i)},e,n),r}addMaps(e){return this.eventCount==0?this:new Vn(this.items.append(e.map(n=>new or(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],o=Math.max(0,this.items.length-n),s=e.mapping,i=e.steps.length,a=this.eventCount;this.items.forEach(h=>{h.selection&&a--},o);let l=n;this.items.forEach(h=>{let p=s.getMirror(--l);if(p==null)return;i=Math.min(i,p);let m=s.maps[p];if(h.step){let g=e.steps[p].invert(e.docs[p]),y=h.selection&&h.selection.map(s.slice(l+1,p));y&&a++,r.push(new or(m,g,y))}else r.push(new or(m))},o);let c=[];for(let h=n;h<i;h++)c.push(new or(s.maps[h]));let u=this.items.slice(0,o).append(c).append(r),d=new Vn(u,a);return d.emptyItemCount()>bz&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,o=[],s=0;return this.items.forEach((i,a)=>{if(a>=e)o.push(i),i.selection&&s++;else if(i.step){let l=i.step.map(n.slice(r)),c=l&&l.getMap();if(r--,c&&n.appendMap(c,r),l){let u=i.selection&&i.selection.map(n.slice(r));u&&s++;let d=new or(c.invert(),l,u),h,p=o.length-1;(h=o.length&&o[p].merge(d))?o[p]=h:o.push(d)}}else i.map&&r--},this.items.length,0),new Vn(kt.from(o.reverse()),s)}}Vn.empty=new Vn(kt.empty,0);function Sz(t,e){let n;return t.forEach((r,o)=>{if(r.selection&&e--==0)return n=o,!1}),t.slice(n)}class or{constructor(e,n,r,o){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=o}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new or(n.getMap().invert(),n,this.selection)}}}class ho{constructor(e,n,r,o,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=o,this.prevComposition=s}}const Ez=20;function Cz(t,e,n,r){let o=n.getMeta(qo),s;if(o)return o.historyState;n.getMeta(Mz)&&(t=new ho(t.done,t.undone,null,0,-1));let i=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(i&&i.getMeta(qo))return i.getMeta(qo).redo?new ho(t.done.addTransform(n,void 0,r,ec(e)),t.undone,nk(n.mapping.maps),t.prevTime,t.prevComposition):new ho(t.done,t.undone.addTransform(n,void 0,r,ec(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(i&&i.getMeta("addToHistory")===!1)){let a=n.getMeta("composition"),l=t.prevTime==0||!i&&t.prevComposition!=a&&(t.prevTime<(n.time||0)-r.newGroupDelay||!xz(n,t.prevRanges)),c=i?gf(t.prevRanges,n.mapping):nk(n.mapping.maps);return new ho(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,ec(e)),Vn.empty,c,n.time,a??t.prevComposition)}else return(s=n.getMeta("rebased"))?new ho(t.done.rebased(n,s),t.undone.rebased(n,s),gf(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new ho(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),gf(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function xz(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,o)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&o>=e[s]&&(n=!0)}),n}function nk(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,o,s,i)=>e.push(s,i));return e}function gf(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let o=e.map(t[r],1),s=e.map(t[r+1],-1);o<=s&&n.push(o,s)}return n}function Tz(t,e,n){let r=ec(e),o=qo.get(e).spec.config,s=(n?t.undone:t.done).popEvent(e,r);if(!s)return null;let i=s.selection.resolve(s.transform.doc),a=(n?t.done:t.undone).addTransform(s.transform,e.selection.getBookmark(),o,r),l=new ho(n?a:s.remaining,n?s.remaining:a,null,0,-1);return s.transform.setSelection(i).setMeta(qo,{redo:n,historyState:l})}let yf=!1,rk=null;function ec(t){let e=t.plugins;if(rk!=e){yf=!1,rk=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){yf=!0;break}}return yf}const qo=new Wt("history"),Mz=new Wt("closeHistory");function _z(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new at({key:qo,state:{init(){return new ho(Vn.empty,Vn.empty,null,0,-1)},apply(e,n,r){return Cz(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,o=r=="historyUndo"?sk:r=="historyRedo"?ik:null;return!o||!e.editable?!1:(n.preventDefault(),o(e.state,e.dispatch))}}}})}function ok(t,e){return(n,r)=>{let o=qo.getState(n);if(!o||(t?o.undone:o.done).eventCount==0)return!1;if(r){let s=Tz(o,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const sk=ok(!1,!0),ik=ok(!0,!0);$e.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=(t==null?void 0:t.node)||this.editor.state.doc;if(((t==null?void 0:t.mode)||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=t=>{const e=(t==null?void 0:t.node)||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new at({key:new Wt("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const o=this.options.limit;if(o==null||o===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>o){const i=s-o,a=0,l=i;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);const c=r.tr.deleteRange(a,l);return t=!0,c}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const o=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||o>r&&s>r&&s<=o)return!0;if(o>r&&s>r&&s>o||!e.getMeta("paste"))return!1;const a=e.selection.$head.pos,l=s-r,c=a-l,u=a;return e.deleteRange(c,u),!(this.storage.characters({node:e.doc})>r)}})]}}),$e.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[dz(this.options)]}}),$e.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new at({key:new Wt("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,s=[];if(!n||!r)return Ue.create(t,[]);let i=0;this.options.mode==="deepest"&&t.descendants((l,c)=>{if(l.isText)return;if(!(o>=c&&o<=c+l.nodeSize-1))return!1;i+=1});let a=0;return t.descendants((l,c)=>{if(l.isText||!(o>=c&&o<=c+l.nodeSize-1))return!1;if(a+=1,this.options.mode==="deepest"&&i-a>0||this.options.mode==="shallowest"&&a>1)return this.options.mode==="deepest";s.push(jt.node(c,c+l.nodeSize,{class:this.options.className}))}),Ue.create(t,s)}}})]}}),$e.create({name:"gapCursor",addProseMirrorPlugins(){return[mz()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Pe(te(t,"allowGapCursor",n)))!=null?e:null}}}),$e.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[new at({key:new Wt("placeholder"),props:{decorations:({doc:t,selection:e})=>{const n=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:r}=e,o=[];if(!n)return null;const s=this.editor.isEmpty;return t.descendants((i,a)=>{const l=r>=a&&r<=a+i.nodeSize,c=!i.isLeaf&&jl(i);if((l||!this.options.showOnlyCurrent)&&c){const u=[this.options.emptyNodeClass];s&&u.push(this.options.emptyEditorClass);const d=jt.node(a,a+i.nodeSize,{class:u.join(" "),"data-placeholder":typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:i,pos:a,hasAnchor:l}):this.options.placeholder});o.push(d)}return this.options.includeChildren}),Ue.create(t,o)}}})]}}),$e.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new at({key:new Wt("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||K3(n.selection)||t.view.dragging?null:Ue.create(n.doc,[jt.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function ak({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(e==null?void 0:e.type)===t}$e.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Wt(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,o])=>o).filter(o=>(this.options.notAfter||[]).concat(n).includes(o.name));return[new at({key:e,appendTransaction:(o,s,i)=>{const{doc:a,tr:l,schema:c}=i,u=e.getState(i),d=a.content.size,h=c.nodes[n];if(u)return l.insert(d,h.create())},state:{init:(o,s)=>{const i=s.tr.doc.lastChild;return!ak({node:i,types:r})},apply:(o,s)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return s;const i=o.doc.lastChild;return!ak({node:i,types:r})}}})]}});var Az=$e.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>sk(t,e),redo:()=>({state:t,dispatch:e})=>ik(t,e)}},addProseMirrorPlugins(){return[_z(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}});function po(t,e){const n=f.inject(Rn);if(!n)throw new Error("useComponents must be used within a WovenCanvas component");const r=f.shallowRef(new Map),o=new Map;function s(a){if(o.has(a))return;const l=n.getEditor();if(l){const u=l._getContext();if(O(u,a,e)){const d=new Map(r.value);d.set(a,e.snapshot(u,a)),r.value=d}else{const d=new Map(r.value);d.set(a,null),r.value=d}}const c=n.subscribeComponent(a,e.name,u=>{const d=new Map(r.value);d.set(a,u),r.value=d});o.set(a,c)}function i(a){const l=o.get(a);if(l){l(),o.delete(a);const c=new Map(r.value);c.delete(a),r.value=c}}return f.watch(()=>f.toValue(t),(a,l)=>{const c=new Set(a),u=new Set(l??[]);for(const d of u)c.has(d)||i(d);for(const d of c)u.has(d)||s(d)},{immediate:!0}),f.onUnmounted(()=>{for(const a of o.values())a();o.clear()}),r}function lk(t){const e=f.inject(Rn);if(!e)throw new Error("useQuery must be used within a WovenCanvas component");const n=f.shallowRef([]),r=ne(d=>d.with(...t)),o=new Map;let s=!1;function i(d){const h=e.getEditor();if(!h)return{refs:{},unsubscribes:[]};const p=h._getContext(),m={},g=[];for(const y of t){const w=f.shallowRef(y.snapshot(p,d));m[y.name]=w;const k=e.subscribeComponent(d,y.name,b=>{w.value=b});g.push(k)}return{refs:m,unsubscribes:g}}function a(d){const h=o.get(d);if(h){for(const p of h.unsubscribes)p();o.delete(d)}}function l(){const d=[];for(const[h,p]of o)d.push({entityId:h,...p.refs});return d}function c(d){if(!s){const g=r.current(d);for(const y of g)o.set(y,i(y));n.value=l(),s=!0;return}const h=r.added(d),p=r.removed(d);let m=!1;for(const g of p)a(g),m=!0;for(const g of h)o.has(g)||(o.set(g,i(g)),m=!0);m&&(n.value=l())}const u=e.registerTickCallback(c);return f.onUnmounted(()=>{u();for(const d of o.keys())a(d)}),n}function zt(t){const e=f.inject(Rn);if(!e)throw new Error("useSingleton must be used within a WovenCanvas component");const n=f.shallowRef(t.default()),r=e.getEditor();if(r){const i=r._getContext();n.value=t.snapshot(i)}const o=e.subscribeSingleton(t.name,i=>{n.value=i??{}});let s=null;return r||(s=e.registerTickCallback(()=>{const i=e.getEditor();if(i){const a=i._getContext();n.value=t.snapshot(a),s==null||s(),s=null}})),f.onUnmounted(()=>{o(),s==null||s()}),n}function Iz(t,e,n){if(n===0)return{width:t,height:e};if(Math.abs(n-Math.PI/2)<1e-4)return{width:e,height:t};const r=Math.abs(Math.cos(n)),o=Math.abs(Math.sin(n)),s=(e-o/r*t)/(r-o*o/r);return{width:t/r-s*o/r,height:s}}function wf(t,e,n){const r=t.closest(".wov-block");if(!r){const x=t.getBoundingClientRect();return{width:x.width,height:x.height,left:0,top:0}}const o=window.getComputedStyle(r).transform,s=new DOMMatrix(o),i=Math.atan2(s.b,s.a),a=t.getBoundingClientRect(),l=new DOMPoint(a.left+a.width/2,a.top+a.height/2),c=e.value.left,u=e.value.top,d=e.value.zoom,h=new DOMMatrix;h.translateSelf(-c*d,-u*d),h.scaleSelf(d,d),h.invertSelf();const p=h.transformPoint(l),m=h.transformPoint(new DOMPoint(a.left,a.top)),g=h.transformPoint(new DOMPoint(a.right,a.bottom)),y=g.x-m.x,w=g.y-m.y,{width:k,height:b}=Iz(y,w,-i),S=n.value.left,v=n.value.top;return{width:k,height:b,left:p.x-k/2-S,top:p.y-b/2-v}}function ck(t){if(t.startsWith("#"))return t.toUpperCase();const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1],10).toString(16).padStart(2,"0"),r=parseInt(e[2],10).toString(16).padStart(2,"0"),o=parseInt(e[3],10).toString(16).padStart(2,"0");return`#${n}${r}${o}`.toUpperCase()}return t}function qi(t){const e=Math.round(t.red),n=Math.round(t.green),r=Math.round(t.blue),o=Math.round(t.alpha);return o<255?"#"+[e,n,r,o].map(s=>{const i=s.toString(16);return i.length===1?`0${i}`:i}).join(""):"#"+[e,n,r].map(s=>{const i=s.toString(16);return i.length===1?`0${i}`:i}).join("")}function kf(t){t=t.replace(/^#/,"");let e,n,r,o=255;if(t.length===6)e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);else if(t.length===8)e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),o=parseInt(t.slice(6,8),16);else return null;return{red:e,green:n,blue:r,alpha:o}}function uk(t){const e=kf(t);if(!e)return{h:0,s:100,v:100,a:255};const n=e.red/255,r=e.green/255,o=e.blue/255,s=Math.max(n,r,o),i=Math.min(n,r,o),a=s-i;let l=0;const c=s===0?0:a/s*100,u=s*100;if(a!==0)switch(s){case n:l=((r-o)/a+(r<o?6:0))*60;break;case r:l=((o-n)/a+2)*60;break;case o:l=((n-r)/a+4)*60;break}return{h:l,s:c,v:u,a:e.alpha}}function dk(t){const e=t.h/360,n=t.s/100,r=t.v/100;let o=0,s=0,i=0;const a=Math.floor(e*6),l=e*6-a,c=r*(1-n),u=r*(1-l*n),d=r*(1-(1-l)*n);switch(a%6){case 0:o=r,s=d,i=c;break;case 1:o=u,s=r,i=c;break;case 2:o=c,s=r,i=d;break;case 3:o=c,s=u,i=r;break;case 4:o=d,s=c,i=r;break;case 5:o=r,s=c,i=u;break}const h=p=>Math.round(p*255).toString(16).padStart(2,"0");return`#${h(o)}${h(s)}${h(i)}`}function fk(t){const e=t.h/360,n=t.s/100,r=t.v/100;let o=0,s=0,i=0;const a=Math.floor(e*6),l=e*6-a,c=r*(1-n),u=r*(1-l*n),d=r*(1-(1-l)*n);switch(a%6){case 0:o=r,s=d,i=c;break;case 1:o=u,s=r,i=c;break;case 2:o=c,s=r,i=d;break;case 3:o=c,s=u,i=r;break;case 4:o=d,s=c,i=r;break;case 5:o=r,s=c,i=u;break}const h=m=>Math.round(m*255).toString(16).padStart(2,"0"),p=Math.round(t.a).toString(16).padStart(2,"0");return t.a<255?`#${h(o)}${h(s)}${h(i)}${p}`:`#${h(o)}${h(s)}${h(i)}`}const en=f.shallowRef(null),vf=f.shallowRef(null),bf=f.shallowRef(null),mo=f.ref(0);function Ji(){const t={hasEditor:f.computed(()=>en.value!==null),isBold:f.computed(()=>{var o;return mo.value,((o=en.value)==null?void 0:o.isActive("bold"))??!1}),isItalic:f.computed(()=>{var o;return mo.value,((o=en.value)==null?void 0:o.isActive("italic"))??!1}),isUnderline:f.computed(()=>{var o;return mo.value,((o=en.value)==null?void 0:o.isActive("underline"))??!1}),alignment:f.computed(()=>{mo.value;const o=en.value;return o?o.isActive({textAlign:"center"})?"center":o.isActive({textAlign:"right"})?"right":o.isActive({textAlign:"justify"})?"justify":"left":"left"}),color:f.computed(()=>{mo.value;const o=en.value;if(!o)return null;const i=o.getAttributes("textStyle").color??null;return i?ck(i):null})},e={toggleBold(){const o=en.value;if(!o)return;const{from:s,to:i}=o.state.selection,a=s===i;let l=o.chain().focus();a&&(l=l.selectAll()),l=l.toggleBold(),a&&(l=l.setTextSelection(i)),l.run()},toggleItalic(){const o=en.value;if(!o)return;const{from:s,to:i}=o.state.selection,a=s===i;let l=o.chain().focus();a&&(l=l.selectAll()),l=l.toggleItalic(),a&&(l=l.setTextSelection(i)),l.run()},toggleUnderline(){const o=en.value;if(!o)return;const{from:s,to:i}=o.state.selection,a=s===i;let l=o.chain().focus();a&&(l=l.selectAll()),l=l.toggleUnderline(),a&&(l=l.setTextSelection(i)),l.run()},setAlignment(o){const s=en.value;s&&s.chain().selectAll().setTextAlign(o).run()},setColor(o){const s=en.value;if(!s)return;const{from:i,to:a}=s.state.selection;i===a?s.chain().focus().selectAll().setColor(o).setTextSelection(a).run():s.chain().focus().setColor(o).run()}};function n(o,s,i){en.value=o,bf.value=s,vf.value=i,o.on("selectionUpdate",()=>{mo.value++}),o.on("transaction",()=>{mo.value++})}function r(){en.value=null,bf.value=null,vf.value=null}return{editor:en,blockElement:vf,textElement:bf,state:t,commands:e,updateCounter:mo,register:n,unregister:r}}const Tn=[U1,H1,j1,pf,Q1,K1,Y1,q1,J1.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})];function Bz(t){return t.type==="text"&&typeof t.text=="string"}function Jo(t,e){if(Bz(t)){e(t);return}if(t.content)for(const n of t.content)Jo(n,e)}function Sf(t,e){if(t.type==="paragraph"){e(t);return}if(t.content)for(const n of t.content)Sf(n,e)}function Pz(t,e){var n;return((n=t.marks)==null?void 0:n.some(r=>r.type===e))??!1}function Nz(t){var r,o;const e=(r=t.marks)==null?void 0:r.find(s=>s.type==="textStyle"),n=((o=e==null?void 0:e.attrs)==null?void 0:o.color)??null;return n?ck(n):null}function Dz(t,e){if(!t.trim())return!1;const n=fo(t,Tn);let r=!1,o=!0,s=0;return Jo(n,i=>{s++,Pz(i,e)?r=!0:o=!1}),s===0?!1:o?!0:r?null:!1}function Oz(t){if(!t.trim())return"left";const e=fo(t,Tn);let n="left";return Sf(e,r=>{var s;const o=(s=r.attrs)==null?void 0:s.textAlign;o&&(n=o)}),n}function Rz(t){if(!t.trim())return null;const e=fo(t,Tn);let n=null;return Jo(e,r=>{n===null&&(n=Nz(r))}),n}function Ef(t,e){if(!t.trim())return t;const n=fo(t,Tn);return Jo(n,r=>{const o=r.marks??[];o.findIndex(i=>i.type===e)===-1&&(r.marks=[...o,{type:e}])}),Wl(n,Tn)}function Cf(t,e){if(!t.trim())return t;const n=fo(t,Tn);return Jo(n,r=>{const o=r.marks??[];r.marks=o.filter(s=>s.type!==e)}),Wl(n,Tn)}function zz(t,e){if(!t.trim())return t;const n=fo(t,Tn);return Sf(n,r=>{r.attrs={...r.attrs,textAlign:e}}),Wl(n,Tn)}function $z(t,e){if(!t.trim())return t;const n=fo(t,Tn);return Jo(n,r=>{const o=r.marks??[],s=o.findIndex(i=>i.type==="textStyle");s!==-1?(o[s]={...o[s],attrs:{...o[s].attrs,color:e}},r.marks=o):r.marks=[...o,{type:"textStyle",attrs:{color:e}}]}),Wl(n,Tn)}function hk(t){const e=document.querySelector(`[data-entity-id="${t}"]`);return e?e.querySelector(".wov-editable-text"):null}function pk(t,e,n,r){var a;const o=t.cloneNode(!0);o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.top="0",o.style.left="0",o.style.fontSize=`${r.fontSizePx}px`,o.style.fontFamily=r.fontFamily;const s=o.querySelector(".ProseMirror, .tiptap");s?s.innerHTML=r.content:o.innerHTML=r.content,(a=t.parentElement)==null||a.appendChild(o);const i=wf(o,e,n);return o.remove(),i}function mk(t){const{nextEditorTick:e}=Tt(),n=po(t,ft),r=zt(he),o=zt(Nt),s=Ji(),i={hasTextEntities:f.computed(()=>{for(const h of n.value.values())if(h)return!0;return!1}),hasTextContent:f.computed(()=>{for(const h of n.value.values()){if(!h)continue;const p=h.content?fo(h.content,Tn):null;if(p){let m=!1;if(Jo(p,g=>{var y;(y=g.text)!=null&&y.trim()&&(m=!0)}),m)return!0}}return!1}),isBold:f.computed(()=>a("bold")),isItalic:f.computed(()=>a("italic")),isUnderline:f.computed(()=>a("underline")),alignment:f.computed(()=>{let h=null;for(const p of n.value.values()){if(!p)continue;const m=Oz(p.content);if(h===null)h=m;else if(h!==m)return null}return h??"left"}),color:f.computed(()=>{let h=null,p=!1;for(const m of n.value.values()){if(!m)continue;const g=Rz(m.content);if(!p)h=g,p=!0;else if(h!==g)return null}return h}),fontSize:f.computed(()=>{let h=null,p=!1;for(const m of n.value.values())if(m){if(!p)h=m.fontSizePx,p=!0;else if(h!==m.fontSizePx)return null}return h}),fontFamily:f.computed(()=>{let h=null,p=!1;for(const m of n.value.values())if(m){if(!p)h=m.fontFamily,p=!0;else if(h!==m.fontFamily)return null}return h})};function a(h){let p=null,m=!1;for(const g of n.value.values()){if(!g)continue;const y=Dz(g.content,h);if(!m)p=y,m=!0;else if(p!==y)return null}return p}const l={toggleBold(){u(h=>i.isBold.value?Cf(h,"bold"):Ef(h,"bold"))},toggleItalic(){u(h=>i.isItalic.value?Cf(h,"italic"):Ef(h,"italic"))},toggleUnderline(){u(h=>i.isUnderline.value?Cf(h,"underline"):Ef(h,"underline"))},setAlignment(h){d(p=>zz(p,h))},setColor(h){d(p=>$z(p,h))},setFontSize(h){c(p=>({...p,fontSizePx:h}),p=>{p.fontSizePx=h})},setFontFamily(h){c(p=>({...p,fontFamily:h}),p=>{p.fontFamily=h})}};function c(h,p){const m=f.toValue(t),g=[];for(const y of m){const w=n.value.get(y);if(!w)continue;const k=hk(y);if(k){const b=pk(k,r,o,h(w));g.push({entityId:y,...b})}}e(y=>{for(const w of m)p(ft.write(y,w));for(const{entityId:w,width:k,height:b,left:S,top:v}of g){const x=_.write(y,w);x.size=[k,b],x.position=[S,v]}f.nextTick(()=>{s.updateCounter.value++})})}function u(h){const p=f.toValue(t),m=[];for(const g of p){const y=n.value.get(g);if(!y)continue;const w=h(y.content),k=hk(g);if(k){const b=pk(k,r,o,{...y,content:w});m.push({entityId:g,content:w,...b})}else m.push({entityId:g,content:w,width:0,height:0,left:0,top:0})}e(g=>{for(const{entityId:y,content:w,width:k,height:b,left:S,top:v}of m){const x=ft.write(g,y);if(x.content=w,k>0&&b>0){const T=_.write(g,y);T.size=[k,b],T.position=[S,v]}}})}function d(h){const p=f.toValue(t);e(m=>{for(const g of p){const y=ft.write(m,g);y.content=h(y.content)}})}return{state:i,commands:l}}function Br(t){const e=Ji(),n=mk(t),r=e.state.hasEditor;return{state:f.reactive({hasTextToFormat:f.computed(()=>r.value||n.state.hasTextEntities.value),hasEditor:r,hasTextContent:f.computed(()=>n.state.hasTextContent.value),showTextMenuButtons:f.computed(()=>r.value||n.state.hasTextContent.value),isBold:f.computed(()=>r.value?e.state.isBold.value:n.state.isBold.value===!0),isItalic:f.computed(()=>r.value?e.state.isItalic.value:n.state.isItalic.value===!0),isUnderline:f.computed(()=>r.value?e.state.isUnderline.value:n.state.isUnderline.value===!0),alignment:f.computed(()=>r.value?e.state.alignment.value:n.state.alignment.value??"left"),color:f.computed(()=>r.value?e.state.color.value:n.state.color.value),fontSize:f.computed(()=>n.state.fontSize.value),fontFamily:f.computed(()=>n.state.fontFamily.value)}),commands:{toggleBold(){r.value?e.commands.toggleBold():n.commands.toggleBold()},toggleItalic(){r.value?e.commands.toggleItalic():n.commands.toggleItalic()},toggleUnderline(){r.value?e.commands.toggleUnderline():n.commands.toggleUnderline()},setAlignment(i){r.value?e.commands.setAlignment(i):n.commands.setAlignment(i)},setColor(i){r.value?e.commands.setColor(i):n.commands.setColor(i)},setFontSize(i){n.commands.setFontSize(i)},setFontFamily(i){n.commands.setFontFamily(i)}}}}function xf(t){const e=zt(he),n=zt(Nt),r=zt(Ru),o=zt(Nn),{nextEditorTick:s}=Tt();let i=!1,a=null;function l(u,d){const{entityId:h}=f.toValue(t.blockData),p=f.toValue(t.minWidth)??0,m=f.toValue(t.minHeight)??0,g=Math.max(d.width,p),y=Math.max(d.height,m),w=_.read(u,h),k=Math.abs(w.size[0]-g)>.5,b=Math.abs(w.size[1]-y)>.5;if(!k&&!b)return;const S=_.write(u,h);S.size=[g,y],S.position=[d.left,d.top],r.value.transformBoxId!==null&&Pu.spawn(u,{transformBoxId:r.value.transformBoxId})}f.watch(()=>o.value,()=>{const u=t.containerRef.value;u&&i&&(a=wf(u,e,n)),s(d=>{const h=Lz(d);i&&!h&&a&&(l(d,a),a=null),i=h})},{flush:"sync"});function c(u){const{content:d,...h}=u;s(p=>{const{entityId:m}=f.toValue(t.blockData);if(ft.read(p,m).content!==d){const y=ft.write(p,m);y.content=d}l(p,h)})}return{handleEditEnd:c}}function Lz(t){const e=Nn.read(t);return e.state===me.Dragging&&e.draggedEntity!==null&&O(t,e.draggedEntity,ze)&&ze.read(t,e.draggedEntity).kind===Pn.Stretch}function Tf(){const t=f.inject(ed);if(!t)throw new Error("useToolbar must be used within a Toolbar component");return{activeTool:t.activeTool,heldTool:t.heldTool,setTool:t.setTool,dragOutTool:t.dragOutTool,onToolPointerDown:t.onToolPointerDown,onToolPointerUp:t.onToolPointerUp,isActive:e=>f.computed(()=>t.activeTool.value===e)}}const Fz=500,Vz=1500;function gk(){const t=f.ref(null),e=f.ref(!1),n=f.ref(!1);let r=null,o=null;function s(){r&&(clearTimeout(r),r=null),o&&(clearTimeout(o),o=null)}function i(c,u){s(),t.value={text:c,anchor:u},n.value?e.value=!0:r=setTimeout(()=>{e.value=!0,n.value=!0,r=null},Fz)}function a(){s(),e.value=!1,t.value=null,n.value&&(o=setTimeout(()=>{n.value=!1,o=null},Vz))}function l(){s(),e.value=!1,t.value=null,n.value=!1}return{activeTooltip:f.readonly(t),isVisible:f.readonly(e),isWarmedUp:f.readonly(n),show:i,hide:a,reset:l}}function go(){const t=f.inject(ny);if(!t)throw new Error("useTooltipSingleton must be used within a WovenCanvas component");return t}const Wz={key:1},Uz=["innerHTML"],tc=f.defineComponent({__name:"EditableText",props:{blockElement:{},measureElement:{},entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},emits:["editEnd"],setup(t,{expose:e,emit:n}){var S;const r=t,o=n,s=pt(r.entityId,ft),i=zt(he),a=zt(Nt),l=Ji(),{nextEditorTick:c}=Tt(),u=f.ref(null);e({editableTextRef:u});const d=f.ref(((S=s.value)==null?void 0:S.content)??""),h=f.shallowRef(null);function p(){var v,x;return new WR({extensions:[U1,H1,j1,pf,Q1,K1,Y1,q1,J1.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:((v=s.value)==null?void 0:v.defaultAlignment)??"left"}),Az],content:((x=s.value)==null?void 0:x.content)??"",editable:!0,parseOptions:{preserveWhitespace:!0}})}function m(v){if(!h.value)return;const x=h.value.view.posAtCoords({left:v.clientX,top:v.clientY});h.value.chain().focus().setTextSelection((x==null?void 0:x.pos)??0).run()}f.watch(()=>r.edited,async v=>{if(v&&u.value){if(h.value=p(),await g(h.value),!r.blockElement)return;l.register(h.value,u.value,r.blockElement)}else h.value&&(l.unregister(),y(h.value),h.value.destroy(),h.value=null)},{immediate:!0});async function g(v){await f.nextTick();const x=u.value;if(x){const T=A=>m(A);x.addEventListener("pointerenter",T,{once:!0}),setTimeout(()=>{x.removeEventListener("pointerenter",T)},50)}v.commands.focus("start")}function y(v){let x=v.getHTML();const A=x.replace(/<[^>]*>/g,"").trim().length>0;A||(x=""),d.value=x,c(P=>{var M;const $=Ft(P,r.block.tag);if(!A&&((M=$.editOptions)!=null&&M.removeWhenTextEmpty)){Ye(P,r.entityId);return}const V=r.measureElement??u.value;if(!V){console.warn("EditableText: no element to measure");return}const U=wf(V,i,a);o("editEnd",{content:x,...U})})}f.watch(()=>{var v;return(v=s.value)==null?void 0:v.content},v=>{v!==void 0&&(h.value?h.value.getHTML()!==v&&h.value.commands.setContent(v,{emitUpdate:!1}):d.value=v)});const w=f.computed(()=>{const v=s.value;return v?{fontFamily:v.fontFamily,fontSize:`${v.fontSizePx}px`,lineHeight:v.lineHeight,letterSpacing:`${v.letterSpacingEm}em`,width:v.constrainWidth?"100%":"fit-content",whiteSpace:v.constrainWidth?"pre-wrap":"pre",minWidth:"2px",wordBreak:"break-word",pointerEvents:r.edited?"auto":"none",userSelect:r.edited?"auto":"none"}:{}});function k(v){v.key==="Control"||v.key==="Meta"||v.stopPropagation()}function b(v){r.edited&&v.stopPropagation()}return f.onUnmounted(()=>{h.value&&(l.unregister(),h.value.destroy(),h.value=null)}),(v,x)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"editableTextRef",ref:u,class:"wov-editable-text",style:f.normalizeStyle(w.value),onKeydown:k,onPointerdown:b,onPointermove:b,onPointerup:b},[h.value?(f.openBlock(),f.createBlock(f.unref(UR),{key:0,editor:h.value},null,8,["editor"])):(f.openBlock(),f.createElementBlock("div",Wz,[f.createElementVNode("div",{class:"tiptap ProseMirror",innerHTML:d.value},null,8,Uz)]))],36))}}),Hz={class:"wov-shape-svg",viewBox:"0 0 100 100",preserveAspectRatio:"none"},jz=["d","fill","stroke","stroke-width","stroke-dasharray"],yk=f.defineComponent({__name:"ShapeBlock",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=pt(e.entityId,yn),r=pt(e.entityId,Ao),o=f.ref(null),s={[st.Top]:"flex-start",[st.Center]:"center",[st.Bottom]:"flex-end"},i=f.computed(()=>n.value?`rgba(${n.value.fillRed}, ${n.value.fillGreen}, ${n.value.fillBlue}, ${(n.value.fillAlpha??255)/255})`:"rgba(0, 0, 0, 0)"),a=f.computed(()=>n.value?n.value.strokeKind===dt.None?"none":`rgba(${n.value.strokeRed}, ${n.value.strokeGreen}, ${n.value.strokeBlue}, ${n.value.strokeAlpha/255})`:"rgba(0, 0, 0, 1)"),l=f.computed(()=>{var g;return((g=n.value)==null?void 0:g.strokeWidth)??2}),c=f.computed(()=>{var g;return((g=n.value)==null?void 0:g.strokeKind)??dt.Solid}),u=f.computed(()=>{var g;return Ti[((g=n.value)==null?void 0:g.kind)??"rectangle"]??Ti.rectangle}),d=f.computed(()=>{const g=l.value;switch(c.value){case dt.Dashed:return`${g*3} ${g*3}`;case dt.None:return"";case dt.Solid:default:return""}}),h=f.computed(()=>{var g;return{overflow:e.edited?"visible":"hidden",alignItems:s[((g=r.value)==null?void 0:g.value)??st.Top]}}),{nextEditorTick:p}=Tt();function m(g){p(y=>{if(ft.read(y,e.entityId).content===g.content)return;const k=ft.write(y,e.entityId);k.content=g.content})}return(g,y)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"containerRef",ref:o,class:"wov-shape-block"},[(f.openBlock(),f.createElementBlock("svg",Hz,[f.createElementVNode("path",{d:u.value,fill:i.value,stroke:a.value,"stroke-width":l.value,"stroke-dasharray":d.value,"stroke-linecap":"round","stroke-linejoin":"round","vector-effect":"non-scaling-stroke"},null,8,jz)])),f.createElementVNode("div",{class:"wov-shape-content",style:f.normalizeStyle(h.value)},[f.createVNode(tc,f.mergeProps(e,{"block-element":o.value,"measure-element":o.value,onEditEnd:m}),null,16,["block-element","measure-element"])],4)],512))}}),Zz=["data-text-empty"],wk=f.defineComponent({__name:"TextBlock",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=f.ref(null),r=pt(e.entityId,ft),o=f.computed(()=>{var l;return(((l=r.value)==null?void 0:l.content)??"").replace(/<[^>]*>/g,"").trim().length===0}),{handleEditEnd:s}=xf({blockData:e,containerRef:n});return(i,a)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-text-block","data-text-empty":o.value||void 0},[f.createVNode(tc,f.mergeProps(e,{"block-element":n.value,onEditEnd:f.unref(s)}),null,16,["block-element","onEditEnd"])],8,Zz))}}),nc=Math.min,Xo=Math.max,rc=Math.round,oc=Math.floor,sr=t=>({x:t,y:t}),Kz={left:"right",right:"left",bottom:"top",top:"bottom"},Yz={start:"end",end:"start"};function kk(t,e,n){return Xo(t,nc(e,n))}function sc(t,e){return typeof t=="function"?t(e):t}function Go(t){return t.split("-")[0]}function ic(t){return t.split("-")[1]}function vk(t){return t==="x"?"y":"x"}function bk(t){return t==="y"?"height":"width"}const qz=new Set(["top","bottom"]);function yo(t){return qz.has(Go(t))?"y":"x"}function Sk(t){return vk(yo(t))}function Jz(t,e,n){n===void 0&&(n=!1);const r=ic(t),o=Sk(t),s=bk(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=ac(i)),[i,ac(i)]}function Xz(t){const e=ac(t);return[Mf(t),e,Mf(e)]}function Mf(t){return t.replace(/start|end/g,e=>Yz[e])}const Ek=["left","right"],Ck=["right","left"],Gz=["top","bottom"],Qz=["bottom","top"];function e$(t,e,n){switch(t){case"top":case"bottom":return n?e?Ck:Ek:e?Ek:Ck;case"left":case"right":return e?Gz:Qz;default:return[]}}function t$(t,e,n,r){const o=ic(t);let s=e$(Go(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map(Mf)))),s}function ac(t){return t.replace(/left|right|bottom|top/g,e=>Kz[e])}function n$(t){return{top:0,right:0,bottom:0,left:0,...t}}function r$(t){return typeof t!="number"?n$(t):{top:t,right:t,bottom:t,left:t}}function lc(t){const{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}function xk(t,e,n){let{reference:r,floating:o}=t;const s=yo(e),i=Sk(e),a=bk(i),l=Go(e),c=s==="y",u=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:u,y:r.y-o.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:d};break;case"left":p={x:r.x-o.width,y:d};break;default:p={x:r.x,y:r.y}}switch(ic(e)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const o$=async(t,e,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(e));let c=await i.getElementRects({reference:t,floating:e,strategy:o}),{x:u,y:d}=xk(c,r,l),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:y,fn:w}=a[g],{x:k,y:b,data:S,reset:v}=await w({x:u,y:d,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:t,floating:e}});u=k??u,d=b??d,p={...p,[y]:{...p[y],...S}},v&&m<=50&&(m++,typeof v=="object"&&(v.placement&&(h=v.placement),v.rects&&(c=v.rects===!0?await i.getElementRects({reference:t,floating:e,strategy:o}):v.rects),{x:u,y:d}=xk(c,h,l)),g=-1)}return{x:u,y:d,placement:h,strategy:o,middlewareData:p}};async function Tk(t,e){var n;e===void 0&&(e={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:h=!1,padding:p=0}=sc(e,t),m=r$(p),y=a[h?d==="floating"?"reference":"floating":d],w=lc(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),k=d==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),S=await(s.isElement==null?void 0:s.isElement(b))?await(s.getScale==null?void 0:s.getScale(b))||{x:1,y:1}:{x:1,y:1},v=lc(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:k,offsetParent:b,strategy:l}):k);return{top:(w.top-v.top+m.top)/S.y,bottom:(v.bottom-w.bottom+m.bottom)/S.y,left:(w.left-v.left+m.left)/S.x,right:(v.right-w.right+m.right)/S.x}}const s$=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=sc(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const w=Go(o),k=yo(a),b=Go(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),v=h||(b||!g?[ac(a)]:Xz(a)),x=m!=="none";!h&&x&&v.push(...t$(a,g,m,S));const T=[a,...v],A=await Tk(e,y),P=[];let $=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&P.push(A[w]),d){const L=Jz(o,i,S);P.push(A[L[0]],A[L[1]])}if($=[...$,{placement:o,overflows:P}],!P.every(L=>L<=0)){var V,U;const L=(((V=s.flip)==null?void 0:V.index)||0)+1,q=T[L];if(q&&(!(d==="alignment"?k!==yo(q):!1)||$.every(H=>yo(H.placement)===k?H.overflows[0]>0:!0)))return{data:{index:L,overflows:$},reset:{placement:q}};let se=(U=$.filter(Z=>Z.overflows[0]<=0).sort((Z,H)=>Z.overflows[1]-H.overflows[1])[0])==null?void 0:U.placement;if(!se)switch(p){case"bestFit":{var M;const Z=(M=$.filter(H=>{if(x){const J=yo(H.placement);return J===k||J==="y"}return!0}).map(H=>[H.placement,H.overflows.filter(J=>J>0).reduce((J,ce)=>J+ce,0)]).sort((H,J)=>H[1]-J[1])[0])==null?void 0:M[0];Z&&(se=Z);break}case"initialPlacement":se=a;break}if(o!==se)return{reset:{placement:se}}}return{}}}},i$=new Set(["left","top"]);async function a$(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Go(n),a=ic(n),l=yo(n)==="y",c=i$.has(i)?-1:1,u=s&&l?-1:1,d=sc(e,t);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*u,y:h*c}:{x:h*c,y:p*u}}const l$=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=e,l=await a$(e,t);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},c$=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:o}=e,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x:w,y:k}=y;return{x:w,y:k}}},...l}=sc(t,e),c={x:n,y:r},u=await Tk(e,l),d=yo(Go(o)),h=vk(d);let p=c[h],m=c[d];if(s){const y=h==="y"?"top":"left",w=h==="y"?"bottom":"right",k=p+u[y],b=p-u[w];p=kk(k,p,b)}if(i){const y=d==="y"?"top":"left",w=d==="y"?"bottom":"right",k=m+u[y],b=m-u[w];m=kk(k,m,b)}const g=a.fn({...e,[h]:p,[d]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[d]:i}}}}}};function cc(){return typeof window<"u"}function Qo(t){return _f(t)?(t.nodeName||"").toLowerCase():"#document"}function fn(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function ir(t){var e;return(e=(_f(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function _f(t){return cc()?t instanceof Node||t instanceof fn(t).Node:!1}function Wn(t){return cc()?t instanceof Element||t instanceof fn(t).Element:!1}function ar(t){return cc()?t instanceof HTMLElement||t instanceof fn(t).HTMLElement:!1}function Mk(t){return!cc()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof fn(t).ShadowRoot}const u$=new Set(["inline","contents"]);function Xi(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=Un(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!u$.has(o)}const d$=new Set(["table","td","th"]);function f$(t){return d$.has(Qo(t))}const h$=[":popover-open",":modal"];function uc(t){return h$.some(e=>{try{return t.matches(e)}catch{return!1}})}const p$=["transform","translate","scale","rotate","perspective"],m$=["transform","translate","scale","rotate","perspective","filter"],g$=["paint","layout","strict","content"];function Af(t){const e=If(),n=Wn(t)?Un(t):t;return p$.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||m$.some(r=>(n.willChange||"").includes(r))||g$.some(r=>(n.contain||"").includes(r))}function y$(t){let e=wo(t);for(;ar(e)&&!Ks(e);){if(Af(e))return e;if(uc(e))return null;e=wo(e)}return null}function If(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const w$=new Set(["html","body","#document"]);function Ks(t){return w$.has(Qo(t))}function Un(t){return fn(t).getComputedStyle(t)}function dc(t){return Wn(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function wo(t){if(Qo(t)==="html")return t;const e=t.assignedSlot||t.parentNode||Mk(t)&&t.host||ir(t);return Mk(e)?e.host:e}function _k(t){const e=wo(t);return Ks(e)?t.ownerDocument?t.ownerDocument.body:t.body:ar(e)&&Xi(e)?e:_k(e)}function Gi(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=_k(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=fn(o);if(s){const a=Bf(i);return e.concat(i,i.visualViewport||[],Xi(o)?o:[],a&&n?Gi(a):[])}return e.concat(o,Gi(o,[],n))}function Bf(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Ak(t){const e=Un(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=ar(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=rc(n)!==s||rc(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Pf(t){return Wn(t)?t:t.contextElement}function Ys(t){const e=Pf(t);if(!ar(e))return sr(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=Ak(e);let i=(s?rc(n.width):n.width)/r,a=(s?rc(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const k$=sr(0);function Ik(t){const e=fn(t);return!If()||!e.visualViewport?k$:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function v$(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==fn(t)?!1:e}function es(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=Pf(t);let i=sr(1);e&&(r?Wn(r)&&(i=Ys(r)):i=Ys(t));const a=v$(s,n,r)?Ik(s):sr(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,u=o.width/i.x,d=o.height/i.y;if(s){const h=fn(s),p=r&&Wn(r)?fn(r):r;let m=h,g=Bf(m);for(;g&&r&&p!==m;){const y=Ys(g),w=g.getBoundingClientRect(),k=Un(g),b=w.left+(g.clientLeft+parseFloat(k.paddingLeft))*y.x,S=w.top+(g.clientTop+parseFloat(k.paddingTop))*y.y;l*=y.x,c*=y.y,u*=y.x,d*=y.y,l+=b,c+=S,m=fn(g),g=Bf(m)}}return lc({width:u,height:d,x:l,y:c})}function fc(t,e){const n=dc(t).scrollLeft;return e?e.left+n:es(ir(t)).left+n}function Bk(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-fc(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function b$(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=ir(r),a=e?uc(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=sr(1);const u=sr(0),d=ar(r);if((d||!d&&!s)&&((Qo(r)!=="body"||Xi(i))&&(l=dc(r)),ar(r))){const p=es(r);c=Ys(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const h=i&&!d&&!s?Bk(i,l):sr(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+h.x,y:n.y*c.y-l.scrollTop*c.y+u.y+h.y}}function S$(t){return Array.from(t.getClientRects())}function E$(t){const e=ir(t),n=dc(t),r=t.ownerDocument.body,o=Xo(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=Xo(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+fc(t);const a=-n.scrollTop;return Un(r).direction==="rtl"&&(i+=Xo(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Pk=25;function C$(t,e){const n=fn(t),r=ir(t),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const u=If();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=fc(r);if(c<=0){const u=r.ownerDocument,d=u.body,h=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-d.clientWidth-p);m<=Pk&&(s-=m)}else c<=Pk&&(s+=c);return{width:s,height:i,x:a,y:l}}const x$=new Set(["absolute","fixed"]);function T$(t,e){const n=es(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=ar(t)?Ys(t):sr(1),i=t.clientWidth*s.x,a=t.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Nk(t,e,n){let r;if(e==="viewport")r=C$(t,n);else if(e==="document")r=E$(ir(t));else if(Wn(e))r=T$(e,n);else{const o=Ik(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return lc(r)}function Dk(t,e){const n=wo(t);return n===e||!Wn(n)||Ks(n)?!1:Un(n).position==="fixed"||Dk(n,e)}function M$(t,e){const n=e.get(t);if(n)return n;let r=Gi(t,[],!1).filter(a=>Wn(a)&&Qo(a)!=="body"),o=null;const s=Un(t).position==="fixed";let i=s?wo(t):t;for(;Wn(i)&&!Ks(i);){const a=Un(i),l=Af(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&x$.has(o.position)||Xi(i)&&!l&&Dk(t,i))?r=r.filter(u=>u!==i):o=a,i=wo(i)}return e.set(t,r),r}function _$(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?uc(e)?[]:M$(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const d=Nk(e,u,o);return c.top=Xo(d.top,c.top),c.right=nc(d.right,c.right),c.bottom=nc(d.bottom,c.bottom),c.left=Xo(d.left,c.left),c},Nk(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function A$(t){const{width:e,height:n}=Ak(t);return{width:e,height:n}}function I$(t,e,n){const r=ar(e),o=ir(e),s=n==="fixed",i=es(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=sr(0);function c(){l.x=fc(o)}if(r||!r&&!s)if((Qo(e)!=="body"||Xi(o))&&(a=dc(e)),r){const p=es(e,!0,s,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else o&&c();s&&!r&&o&&c();const u=o&&!r&&!s?Bk(o,a):sr(0),d=i.left+a.scrollLeft-l.x-u.x,h=i.top+a.scrollTop-l.y-u.y;return{x:d,y:h,width:i.width,height:i.height}}function Nf(t){return Un(t).position==="static"}function Ok(t,e){if(!ar(t)||Un(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return ir(t)===n&&(n=n.ownerDocument.body),n}function Rk(t,e){const n=fn(t);if(uc(t))return n;if(!ar(t)){let o=wo(t);for(;o&&!Ks(o);){if(Wn(o)&&!Nf(o))return o;o=wo(o)}return n}let r=Ok(t,e);for(;r&&f$(r)&&Nf(r);)r=Ok(r,e);return r&&Ks(r)&&Nf(r)&&!Af(r)?n:r||y$(t)||n}const B$=async function(t){const e=this.getOffsetParent||Rk,n=this.getDimensions,r=await n(t.floating);return{reference:I$(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function P$(t){return Un(t).direction==="rtl"}const N$={convertOffsetParentRelativeRectToViewportRelativeRect:b$,getDocumentElement:ir,getClippingRect:_$,getOffsetParent:Rk,getElementRects:B$,getClientRects:S$,getDimensions:A$,getScale:Ys,isElement:Wn,isRTL:P$};function zk(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function D$(t,e){let n=null,r;const o=ir(t);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=t.getBoundingClientRect(),{left:u,top:d,width:h,height:p}=c;if(a||e(),!h||!p)return;const m=oc(d),g=oc(o.clientWidth-(u+h)),y=oc(o.clientHeight-(d+p)),w=oc(u),b={rootMargin:-m+"px "+-g+"px "+-y+"px "+-w+"px",threshold:Xo(0,nc(1,l))||1};let S=!0;function v(x){const T=x[0].intersectionRatio;if(T!==l){if(!S)return i();T?i(!1,T):r=setTimeout(()=>{i(!1,1e-7)},1e3)}T===1&&!zk(c,t.getBoundingClientRect())&&i(),S=!1}try{n=new IntersectionObserver(v,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(v,b)}n.observe(t)}return i(!0),s}function O$(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Pf(t),u=o||s?[...c?Gi(c):[],...Gi(e)]:[];u.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),s&&w.addEventListener("resize",n)});const d=c&&a?D$(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(w=>{let[k]=w;k&&k.target===c&&p&&(p.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var b;(b=p)==null||b.observe(e)})),n()}),c&&!l&&p.observe(c),p.observe(e));let m,g=l?es(t):null;l&&y();function y(){const w=es(t);g&&!zk(g,w)&&n(),g=w,m=requestAnimationFrame(y)}return n(),()=>{var w;u.forEach(k=>{o&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),d==null||d(),(w=p)==null||w.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const Df=l$,Of=c$,Rf=s$,R$=(t,e,n)=>{const r=new Map,o={platform:N$,...n},s={...o.platform,_c:r};return o$(t,e,{...o,platform:s})};function z$(t){return t!=null&&typeof t=="object"&&"$el"in t}function $k(t){if(z$(t)){const e=t.$el;return _f(e)&&Qo(e)==="#comment"?null:e}return t}function Qi(t){return typeof t=="function"?t():f.unref(t)}function Lk(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function Fk(t,e){const n=Lk(t);return Math.round(e*n)/n}function zf(t,e,n){n===void 0&&(n={});const r=n.whileElementsMounted,o=f.computed(()=>{var T;return(T=Qi(n.open))!=null?T:!0}),s=f.computed(()=>Qi(n.middleware)),i=f.computed(()=>{var T;return(T=Qi(n.placement))!=null?T:"bottom"}),a=f.computed(()=>{var T;return(T=Qi(n.strategy))!=null?T:"absolute"}),l=f.computed(()=>{var T;return(T=Qi(n.transform))!=null?T:!0}),c=f.computed(()=>$k(t.value)),u=f.computed(()=>$k(e.value)),d=f.ref(0),h=f.ref(0),p=f.ref(a.value),m=f.ref(i.value),g=f.shallowRef({}),y=f.ref(!1),w=f.computed(()=>{const T={position:p.value,left:"0",top:"0"};if(!u.value)return T;const A=Fk(u.value,d.value),P=Fk(u.value,h.value);return l.value?{...T,transform:"translate("+A+"px, "+P+"px)",...Lk(u.value)>=1.5&&{willChange:"transform"}}:{position:p.value,left:A+"px",top:P+"px"}});let k;function b(){if(c.value==null||u.value==null)return;const T=o.value;R$(c.value,u.value,{middleware:s.value,placement:i.value,strategy:a.value}).then(A=>{d.value=A.x,h.value=A.y,p.value=A.strategy,m.value=A.placement,g.value=A.middlewareData,y.value=T!==!1})}function S(){typeof k=="function"&&(k(),k=void 0)}function v(){if(S(),r===void 0){b();return}if(c.value!=null&&u.value!=null){k=r(c.value,u.value,b);return}}function x(){o.value||(y.value=!1)}return f.watch([s,i,a,o],b,{flush:"sync"}),f.watch([c,u],v,{flush:"sync"}),f.watch(o,x,{flush:"sync"}),f.getCurrentScope()&&f.onScopeDispose(S),{x:f.shallowReadonly(d),y:f.shallowReadonly(h),strategy:f.shallowReadonly(p),placement:f.shallowReadonly(m),middlewareData:f.shallowReadonly(g),isPositioned:f.shallowReadonly(y),floatingStyles:w,update:b}}const $$=["menu-open"],Hn=f.defineComponent({__name:"MenuDropdown",props:{title:{},disabled:{type:Boolean},placement:{default:"top"},offsetPx:{default:8}},emits:["open","close"],setup(t,{emit:e}){const n=t,r=e,o=f.inject("containerRef"),{show:s,hide:i}=go(),a=f.ref(!1),l=f.ref(null),c=f.ref(null),{floatingStyles:u}=zf(l,c,{placement:n.placement,middleware:[Df(n.offsetPx),Rf(),Of({padding:8})],whileElementsMounted:O$});function d(){n.disabled||(a.value=!a.value)}function h(){a.value=!1}function p(y){const w=y.target;l.value&&!l.value.contains(w)&&c.value&&!c.value.contains(w)&&h()}function m(){n.title&&l.value&&!a.value&&s(n.title,l.value)}function g(){i()}return f.watch(a,y=>{y?(i(),document.addEventListener("click",p,!0),r("open")):(document.removeEventListener("click",p,!0),r("close"))}),f.onUnmounted(()=>{document.removeEventListener("click",p,!0)}),(y,w)=>(f.openBlock(),f.createElementBlock(f.Fragment,null,[f.createElementVNode("div",{ref_key:"buttonRef",ref:l,class:f.normalizeClass(["wov-menu-dropdown-trigger",{"is-open":a.value}]),"menu-open":a.value||void 0,onMousedown:w[0]||(w[0]=f.withModifiers(()=>{},["prevent"])),onClick:d,onMouseenter:m,onMouseleave:g},[f.renderSlot(y.$slots,"button",{isOpen:a.value})],42,$$),f.unref(o)?(f.openBlock(),f.createBlock(f.Teleport,{key:0,to:f.unref(o)},[a.value?(f.openBlock(),f.createElementBlock("div",{key:0,ref_key:"dropdownRef",ref:c,class:"wov-menu-dropdown",style:f.normalizeStyle(f.unref(u))},[f.renderSlot(y.$slots,"dropdown",{close:h})],4)):f.createCommentVNode("",!0)],8,["to"])):f.createCommentVNode("",!0)],64))}}),L$={},F$={viewBox:"0 0 512 320",fill:"currentColor",style:{width:"7px",color:"var(--wov-gray-300)"}};function V$(t,e){return f.openBlock(),f.createElementBlock("svg",F$,[...e[0]||(e[0]=[f.createElementVNode("path",{d:"M233.4 278.6c12.5 12.5 32.8 12.5 45.3 0l192-192c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L256 210.7 86.6 41.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l192 192z"},null,-1)])])}const jn=Bo(L$,[["render",V$]]),W$={class:"wov-menu-button"},U$=["innerHTML"],H$=["onClick"],j$=["innerHTML"],$f=f.defineComponent({__name:"ArrowHeadButton",props:{entityIds:{},side:{}},setup(t){const e=t,{nextEditorTick:n}=Tt(),r=f.shallowRef(null),o=f.computed(()=>{const a=r.value??(e.side==="start"?Ce.None:Ce.V);return Is(a)});n(a=>{let l=null;for(const c of e.entityIds){if(O(a,c,Se)){const u=Se.read(a,c),d=e.side==="start"?u.startArrowHead:u.endArrowHead;if(l===null)l=d;else if(d!==l){r.value=e.side==="start"?Ce.None:Ce.V;return}}if(O(a,c,ge)){const u=ge.read(a,c),d=e.side==="start"?u.startArrowHead:u.endArrowHead;if(l===null)l=d;else if(d!==l){r.value=e.side==="start"?Ce.None:Ce.V;return}}}r.value=l});function s(a){r.value=a,n(l=>{for(const c of e.entityIds){if(O(l,c,Se)){const u=Se.write(l,c);e.side==="start"?u.startArrowHead=a:u.endArrowHead=a}if(O(l,c,ge)){const u=ge.write(l,c);e.side==="start"?u.startArrowHead=a:u.endArrowHead=a}}})}function i(a){if(!a)return"";const l=e.side==="start";return`<line x1="${l?8:4}" y1="12" x2="${l?20:16}" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" /><g transform="${`translate(${l?4:20}, 12) scale(${l?"-0.8, 0.8":"0.8"})`}">${a.svg}</g>`}return(a,l)=>(f.openBlock(),f.createBlock(Hn,{title:t.side==="start"?"Start Arrow Head":"End Arrow Head"},{button:f.withCtx(()=>[f.createElementVNode("div",W$,[(f.openBlock(),f.createElementBlock("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",innerHTML:i(o.value)},null,8,U$)),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(f.unref(Qu),c=>(f.openBlock(),f.createElementBlock("button",{key:c.kind,class:f.normalizeClass(["wov-menu-option",{"is-active":r.value===c.kind}]),onClick:u=>s(c.kind)},[(f.openBlock(),f.createElementBlock("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",innerHTML:i(c)},null,8,j$))],10,H$))),128))]),_:1},8,["title"]))}}),Z$={class:"wov-menu-button"},K$=["onClick"],Vk=f.defineComponent({__name:"ArrowThicknessButton",props:{entityIds:{}},setup(t){const e=[{label:"S",value:2},{label:"M",value:4},{label:"L",value:8}],n=t,{nextEditorTick:r}=Tt(),o=f.shallowRef(null);r(i=>{let a=null;for(const l of n.entityIds){if(O(i,l,Se)){const c=Se.read(i,l);if(a===null)a=c.thickness;else if(c.thickness!==a){o.value=null;return}}if(O(i,l,ge)){const c=ge.getThickness(i,l);if(a===null)a=c;else if(c!==a){o.value=null;return}}}o.value=a});function s(i){o.value=i,r(a=>{for(const l of n.entityIds){if(O(a,l,Se)){const c=Se.write(a,l);c.thickness=i}O(a,l,ge)&&ge.setThickness(a,l,i)}})}return(i,a)=>(f.openBlock(),f.createBlock(Hn,{title:"Thickness"},{button:f.withCtx(()=>[f.createElementVNode("div",Z$,[a[0]||(a[0]=f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-linecap":"round"},[f.createElementVNode("line",{x1:"4",y1:"5",x2:"20",y2:"5","stroke-width":"1"}),f.createElementVNode("line",{x1:"4",y1:"11",x2:"20",y2:"11","stroke-width":"2.5"}),f.createElementVNode("line",{x1:"4",y1:"19",x2:"20",y2:"19","stroke-width":"4"})],-1)),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[(f.openBlock(),f.createElementBlock(f.Fragment,null,f.renderList(e,l=>f.createElementVNode("button",{key:l.value,class:f.normalizeClass(["wov-menu-option wov-arrow-thickness-option",{"is-active":o.value===l.value}]),onClick:c=>s(l.value)},f.toDisplayString(l.label),11,K$)),64))]),_:1}))}}),Y$=["value"],q$=f.defineComponent({__name:"ColorInput",props:{modelValue:{}},emits:["update:modelValue"],setup(t,{emit:e}){const n=t,r=e,o=f.ref(n.modelValue??"");f.watch(()=>n.modelValue,u=>{u&&u!==o.value&&(o.value=u)});function s(u){const d=u.startsWith("#")?u:`#${u}`;return/^#[0-9A-Fa-f]{6}$/.test(d)}function i(u){return(u.startsWith("#")?u:`#${u}`).toLowerCase()}function a(u){let h=u.target.value;if((h.length===6||h.length===7)&&s(h)){const p=i(h);o.value=p,r("update:modelValue",p)}}function l(u){const h=u.target.value;if(h&&s(h)){const p=i(h);o.value=p,r("update:modelValue",p)}else n.modelValue&&(o.value=n.modelValue)}function c(u){if(u.stopPropagation(),u.key==="Enter"){const d=u.target,h=d.value;if(h&&s(h)){const p=i(h);o.value=p,r("update:modelValue",p),setTimeout(()=>d.select())}}}return(u,d)=>(f.openBlock(),f.createElementBlock("input",{id:"wov-color-input",class:"wov-color-input",type:"text",size:"1","aria-label":"Hex color value",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false",value:o.value,onInput:a,onChange:l,onKeydown:c},null,40,Y$))}}),Wk=f.defineComponent({__name:"ColorSlider",props:{modelValue:{},thumbColor:{},background:{}},emits:["update:modelValue"],setup(t,{expose:e,emit:n}){const r=n,o=f.ref(null),s=f.ref(!1);function i(c){s.value=!0,a(c),window.addEventListener("pointermove",a),window.addEventListener("pointerup",l)}function a(c){if(!o.value)return;const u=o.value.getBoundingClientRect(),d=Math.max(0,Math.min(100,(c.clientY-u.top)/u.height*100));r("update:modelValue",d)}function l(){s.value=!1,window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",l)}return e({isDragging:s}),(c,u)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"sliderRef",ref:o,class:"wov-color-slider",onPointerdown:f.withModifiers(i,["prevent"])},[t.background?(f.openBlock(),f.createElementBlock("div",{key:0,class:"wov-color-slider-gradient",style:f.normalizeStyle({background:t.background})},null,4)):f.createCommentVNode("",!0),f.createElementVNode("div",{class:"wov-color-slider-thumb",style:f.normalizeStyle({top:`${t.modelValue}%`,backgroundColor:t.thumbColor})},null,4)],544))}}),J$={class:"wov-color-picker"},X$={class:"wov-color-picker-area"},G$={class:"wov-color-picker-selector-gradient"},Q$="linear-gradient(to bottom, red 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red 100%)",Uk=f.defineComponent({__name:"ColorPicker",props:{modelValue:{},withOpacity:{type:Boolean}},emits:["update:modelValue"],setup(t,{emit:e}){const n=t,r=e,o=f.ref(null),s=f.ref(null),i=f.ref(null),a=f.ref({x:100,y:0}),l=f.ref(0),c=f.ref(0),u=f.ref(!1),d=f.computed(()=>{var x,T;return u.value||((x=o.value)==null?void 0:x.isDragging)||((T=s.value)==null?void 0:T.isDragging)}),h=f.computed(()=>({h:l.value/100*360,s:a.value.x,v:100-a.value.y,a:(100-c.value)/100*255})),p=f.computed(()=>dk({h:h.value.h,s:100,v:100})),m=f.computed(()=>dk({h:h.value.h,s:h.value.s,v:h.value.v})),g=f.computed(()=>n.withOpacity?fk(h.value):m.value),y=f.computed(()=>`linear-gradient(to top, transparent 0%, ${m.value} 100%)`);function w(x){if(x){const T=uk(x);a.value={x:T.s,y:100-T.v},l.value=T.h/360*100,c.value=100-T.a/255*100}}function k(x){w(x),r("update:modelValue",n.withOpacity?fk(uk(x)):x)}w(n.modelValue),f.watch(()=>n.modelValue,x=>{d.value||w(x)}),f.watch([a,l,c],()=>{d.value&&r("update:modelValue",g.value)});function b(x){u.value=!0,S(x),window.addEventListener("pointermove",S),window.addEventListener("pointerup",v)}function S(x){if(!i.value)return;const T=i.value.getBoundingClientRect(),A=Math.max(0,Math.min(100,(x.clientX-T.left)/T.width*100)),P=Math.max(0,Math.min(100,(x.clientY-T.top)/T.height*100));a.value={x:A,y:P}}function v(){u.value=!1,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",v)}return(x,T)=>(f.openBlock(),f.createElementBlock("div",J$,[f.createVNode(q$,{modelValue:g.value,"onUpdate:modelValue":k},null,8,["modelValue"]),f.createElementVNode("div",X$,[f.createElementVNode("div",{ref_key:"selectorRef",ref:i,class:"wov-color-picker-selector",style:f.normalizeStyle({backgroundColor:p.value}),onPointerdown:f.withModifiers(b,["prevent"])},[f.createElementVNode("div",G$,[f.createElementVNode("div",{class:"wov-color-picker-selector-thumb",style:f.normalizeStyle({left:`${a.value.x}%`,top:`${a.value.y}%`,backgroundColor:m.value})},null,4)])],36),f.createVNode(Wk,{ref_key:"hueSliderRef",ref:o,modelValue:l.value,"onUpdate:modelValue":T[0]||(T[0]=A=>l.value=A),thumbColor:p.value,background:Q$},null,8,["modelValue","thumbColor"]),t.withOpacity?(f.openBlock(),f.createBlock(Wk,{key:0,ref_key:"opacitySliderRef",ref:s,modelValue:c.value,"onUpdate:modelValue":T[1]||(T[1]=A=>c.value=A),thumbColor:m.value,background:y.value,class:"wov-color-picker-opacity"},null,8,["modelValue","thumbColor","background"])):f.createCommentVNode("",!0)])]))}}),e4={class:"wov-color-bubbles-container"},t4={key:1,class:"wov-color-bubbles"},n4=["onClick"],hc=f.defineComponent({__name:"ColorBubbles",props:{currentColor:{},palette:{},hideHighlight:{type:Boolean},withPicker:{type:Boolean},withOpacity:{type:Boolean}},emits:["change","picker-open"],setup(t,{emit:e}){const n=t,r=e,o=["#000000","#374151","#6B7280","#9CA3AF","#D1D5DB","#FFFFFF","#EF4444","#F97316","#EAB308","#22C55E","#14B8A6","#3B82F6","#8B5CF6","#EC4899"],s=f.computed(()=>{const m=n.palette??o,g=n.withPicker,y=m.length%2===1;return g&&!y||!g&&y?m.slice(0,-1):m}),i=f.ref(!1),a=f.ref(n.currentColor??"#ff0000");function l(m,g){const y=w=>{const k=w.replace(/^#/,"").toLowerCase();return k.length===6?k+"ff":k};return y(m)===y(g)}function c(m){return n.hideHighlight||!n.currentColor?!1:l(n.currentColor,m)}function u(){return n.hideHighlight||!n.currentColor?!1:!s.value.some(m=>l(n.currentColor,m))}function d(m){const g=kf(m);g&&r("change",g)}function h(){!i.value&&n.currentColor&&(a.value=n.currentColor),i.value=!i.value,r("picker-open",i.value)}function p(m){a.value=m;const g=kf(m);g&&r("change",g)}return(m,g)=>(f.openBlock(),f.createElementBlock("div",e4,[i.value?(f.openBlock(),f.createBlock(Uk,{key:0,modelValue:a.value,"onUpdate:modelValue":[g[0]||(g[0]=y=>a.value=y),p],withOpacity:t.withOpacity},null,8,["modelValue","withOpacity"])):(f.openBlock(),f.createElementBlock("div",t4,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(s.value,y=>(f.openBlock(),f.createElementBlock("div",{key:y,class:f.normalizeClass(["wov-color-bubble",{selected:c(y)}]),style:f.normalizeStyle({backgroundColor:y}),onMousedown:g[1]||(g[1]=f.withModifiers(()=>{},["prevent"])),onClick:w=>d(y)},null,46,n4))),128)),t.withPicker?(f.openBlock(),f.createElementBlock("div",{key:0,class:f.normalizeClass(["wov-color-bubble wov-rainbow-bubble",{selected:u()}]),onMousedown:g[2]||(g[2]=f.withModifiers(()=>{},["prevent"])),onClick:h},null,34)):f.createCommentVNode("",!0)]))]))}}),r4={class:"wov-color-button"},Hk=f.defineComponent({__name:"ColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Tt(),r=po(()=>e.entityIds,gn),o=f.computed(()=>{const c=new Set;for(const u of r.value.values())if(u){const d=qi(u);c.add(d)}return Array.from(c)}),s=f.computed(()=>o.value.length>1),i=f.computed(()=>o.value[0]??null),a=f.computed(()=>{if(o.value.length===0)return{backgroundColor:"#000"};if(o.value.length>=2){const c=o.value[0],u=o.value[1];return{background:`linear-gradient(45deg, ${c} 0%, ${c} 50%, ${u} 50%, ${u} 100%)`}}return{backgroundColor:o.value[0]}});function l(c){const u=qi(c);n(d=>{for(const h of e.entityIds)gn.fromHex(d,h,u)})}return(c,u)=>(f.openBlock(),f.createBlock(Hn,{title:"Color"},{button:f.withCtx(()=>[f.createElementVNode("div",r4,[f.createElementVNode("div",{class:"wov-color-swatch",style:f.normalizeStyle(a.value)},null,4),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createVNode(hc,{currentColor:i.value??void 0,hideHighlight:s.value,withPicker:!0,onChange:l},null,8,["currentColor","hideHighlight"])]),_:1}))}}),qs=f.defineComponent({__name:"MenuButton",props:{title:{}},emits:["click"],setup(t,{emit:e}){const n=t,r=e,o=f.ref(null),{show:s,hide:i}=go();function a(u){r("click",u)}function l(){n.title&&o.value&&s(n.title,o.value)}function c(){i()}return(u,d)=>(f.openBlock(),f.createElementBlock("button",{ref_key:"buttonRef",ref:o,class:"wov-menu-button",onClick:a,onMouseenter:l,onMouseleave:c},[f.renderSlot(u.$slots,"default")],544))}}),Lf=f.defineComponent({__name:"MenuTooltip",setup(t){const{activeTooltip:e,isVisible:n}=go(),r=f.inject("containerRef"),o=f.ref(null),s=f.computed(()=>{var l;return((l=e.value)==null?void 0:l.anchor)??null}),{floatingStyles:i}=zf(s,o,{placement:"top",middleware:[Df(8),Rf({fallbackPlacements:["bottom"]}),Of({padding:8})]}),a=f.computed(()=>{var l;return n.value&&((l=e.value)==null?void 0:l.text)});return(l,c)=>f.unref(r)?(f.openBlock(),f.createBlock(f.Teleport,{key:0,to:f.unref(r)},[f.createVNode(f.Transition,{name:"wov-tooltip-fade"},{default:f.withCtx(()=>{var u;return[a.value?(f.openBlock(),f.createElementBlock("div",{key:0,ref_key:"tooltipRef",ref:o,class:"wov-menu-tooltip",style:f.normalizeStyle(f.unref(i))},f.toDisplayString((u=f.unref(e))==null?void 0:u.text),5)):f.createCommentVNode("",!0)]}),_:1})],8,["to"])):f.createCommentVNode("",!0)}}),o4={class:"wov-menu-button"},s4=["onClick"],jk=f.defineComponent({__name:"PenStrokeThicknessButton",props:{entityIds:{}},setup(t){const e=[{label:"S",value:4},{label:"M",value:8},{label:"L",value:16}],n=t,{nextEditorTick:r}=Tt(),o=po(()=>n.entityIds,Ln),s=f.computed(()=>{let a=null;for(const l of o.value.values())if(l){if(a===null)a=l.thickness;else if(l.thickness!==a)return null}return a});function i(a){r(l=>{for(const c of n.entityIds){const u=Ln.write(l,c);u.thickness=a}})}return(a,l)=>(f.openBlock(),f.createBlock(Hn,{title:"Thickness"},{button:f.withCtx(()=>[f.createElementVNode("div",o4,[l[0]||(l[0]=f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-linecap":"round"},[f.createElementVNode("line",{x1:"4",y1:"5",x2:"20",y2:"5","stroke-width":"1"}),f.createElementVNode("line",{x1:"4",y1:"11",x2:"20",y2:"11","stroke-width":"2.5"}),f.createElementVNode("line",{x1:"4",y1:"19",x2:"20",y2:"19","stroke-width":"4"})],-1)),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[(f.openBlock(),f.createElementBlock(f.Fragment,null,f.renderList(e,c=>f.createElementVNode("button",{key:c.value,class:f.normalizeClass(["wov-menu-option wov-pen-thickness-option",{"is-active":s.value===c.value}]),onClick:u=>i(c.value)},f.toDisplayString(c.label),11,s4)),64))]),_:1}))}}),i4={class:"wov-fill-color-button"},a4={class:"wov-fill-dropdown"},l4={key:0,class:"wov-fill-mode-section"},c4=["title","onClick"],u4={viewBox:"0 0 24 24",fill:"none"},d4=["fill","fill-opacity","stroke","stroke-width","stroke-dasharray"],Zk=f.defineComponent({__name:"ShapeFillColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Tt(),r=po(()=>e.entityIds,yn),o=[{mode:"solid",label:"Solid",alpha:255},{mode:"faded",label:"Faded",alpha:128},{mode:"none",label:"None",alpha:0}],s=f.computed(()=>{const p=r.value.values().next().value,m=(p==null?void 0:p.fillAlpha)??255;return m===0?"none":m<200?"faded":"solid"}),i=f.computed(()=>{const p=new Set;for(const m of r.value.values())if(m){const g=m.fillAlpha??255;g===0?p.add("none"):g<200?p.add("faded"):p.add("solid")}return p.size>1});function a(p){n(m=>{for(const g of e.entityIds){const y=yn.write(m,g);y.fillAlpha=p}})}const l=f.computed(()=>{const p=new Set;for(const m of r.value.values())if(m){const g=qi({red:m.fillRed,green:m.fillGreen,blue:m.fillBlue,alpha:m.fillAlpha??255});p.add(g)}return Array.from(p)}),c=f.computed(()=>l.value.length>1),u=f.computed(()=>l.value[0]??"#4a90d9");function d(p){n(m=>{for(const g of e.entityIds){const y=yn.write(m,g);y.fillRed=p.red,y.fillGreen=p.green,y.fillBlue=p.blue,y.fillAlpha=p.alpha}})}const h=f.ref(!1);return(p,m)=>(f.openBlock(),f.createBlock(Hn,{title:"Fill Color"},{button:f.withCtx(()=>[f.createElementVNode("div",i4,[m[1]||(m[1]=f.createElementVNode("svg",{viewBox:"0 0 20 20",class:"wov-fill-color-icon",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},[f.createElementVNode("path",{d:"M5.879,2.625L14.121,2.625C15.906,2.625 17.375,4.094 17.375,5.879L17.375,14.121C17.375,15.906 15.906,17.375 14.121,17.375L5.88,17.375C4.095,17.375 2.626,15.906 2.626,14.121L2.626,5.88C2.626,4.095 4.095,2.626 5.88,2.626L5.879,2.625Z","stroke-width":"1.25"}),f.createElementVNode("path",{d:"M2.779,14.655L14.543,2.871M10.238,17.308L17.318,10.229M2.876,9.577L9.853,2.6M5.397,17.239L17.16,5.476","stroke-width":"1.25"})],-1)),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createElementVNode("div",a4,[h.value?f.createCommentVNode("",!0):(f.openBlock(),f.createElementBlock("div",l4,[(f.openBlock(),f.createElementBlock(f.Fragment,null,f.renderList(o,g=>f.createElementVNode("button",{key:g.mode,class:f.normalizeClass(["wov-fill-mode-option",{"is-active":!i.value&&g.mode===s.value}]),title:g.label,onClick:y=>a(g.alpha)},[(f.openBlock(),f.createElementBlock("svg",u4,[f.createElementVNode("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",fill:g.mode==="none"?"none":"currentColor","fill-opacity":g.mode==="faded"?.4:1,stroke:g.mode==="none"?"currentColor":"none","stroke-width":g.mode==="none"?1.5:0,"stroke-dasharray":g.mode==="none"?"3 3":""},null,8,d4)])),f.createElementVNode("span",null,f.toDisplayString(g.label),1)],10,c4)),64))])),f.createVNode(hc,{currentColor:u.value,hideHighlight:c.value,withPicker:!0,withOpacity:!0,onChange:d,onPickerOpen:m[0]||(m[0]=g=>h.value=g)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),f4={class:"wov-shape-kind-button"},h4={class:"wov-shape-kind-dropdown"},p4=["onClick"],m4={viewBox:"0 0 20 20",class:"wov-shape-option-icon",fill:"none",stroke:"currentColor","stroke-width":"4"},g4=["d"],Kk=f.defineComponent({__name:"ShapeKindButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Tt(),r=po(()=>e.entityIds,yn),o=f.computed(()=>{const l=r.value.values().next().value;return(l==null?void 0:l.kind)??"rectangle"}),s=f.computed(()=>{const l=new Set;for(const c of r.value.values())c&&l.add(c.kind);return l.size>1}),i=f.computed(()=>Object.keys(Ti).map(l=>({kind:l,label:l.charAt(0).toUpperCase()+l.slice(1)})));function a(l){n(c=>{for(const u of e.entityIds){const d=yn.write(c,u);d.kind=l}})}return(l,c)=>(f.openBlock(),f.createBlock(Hn,{title:"Shape Type"},{button:f.withCtx(()=>[f.createElementVNode("div",f4,[c[0]||(c[0]=f.createElementVNode("svg",{viewBox:"0 0 20 20",class:"wov-shape-kind-icon",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[f.createElementVNode("circle",{cx:"6",cy:"6",r:"5"}),f.createElementVNode("rect",{x:"6",y:"6",width:"10",height:"10",fill:"var(--wov-gray-600)"})],-1)),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createElementVNode("div",h4,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(i.value,u=>(f.openBlock(),f.createElementBlock("button",{key:u.kind,class:f.normalizeClass(["wov-shape-kind-option",{"is-selected":!s.value&&u.kind===o.value}]),onClick:d=>a(u.kind)},[(f.openBlock(),f.createElementBlock("svg",m4,[f.createElementVNode("path",{d:f.unref(Ti)[u.kind],transform:"translate(2, 2) scale(0.16)"},null,8,g4)])),f.createElementVNode("span",null,f.toDisplayString(u.label),1)],10,p4))),128))])]),_:1}))}}),y4={class:"wov-stroke-style-section"},w4=["title","onClick"],k4={viewBox:"0 0 24 8",fill:"none",stroke:"currentColor","stroke-width":"2"},v4=["stroke-dasharray","stroke-opacity"],b4=f.defineComponent({__name:"StrokeStyleOptions",props:{currentStyle:{},hasMultipleStyles:{type:Boolean}},emits:["change"],setup(t,{emit:e}){const n=e,r=[{kind:dt.Solid,label:"Solid"},{kind:dt.Dashed,label:"Dashed"},{kind:dt.None,label:"None"}];function o(i){switch(i){case dt.Dashed:return"6 6";case dt.None:return"";case dt.Solid:default:return""}}function s(i){n("change",i)}return(i,a)=>(f.openBlock(),f.createElementBlock("div",y4,[(f.openBlock(),f.createElementBlock(f.Fragment,null,f.renderList(r,l=>f.createElementVNode("button",{key:l.kind,class:f.normalizeClass(["wov-stroke-style-option",{"is-active":!t.hasMultipleStyles&&l.kind===t.currentStyle}]),title:l.label,onClick:c=>s(l.kind)},[(f.openBlock(),f.createElementBlock("svg",k4,[f.createElementVNode("line",{x1:"2",y1:"4",x2:"22",y2:"4","stroke-linecap":"round","stroke-dasharray":o(l.kind),"stroke-opacity":l.kind===f.unref(dt).None?.3:1},null,8,v4)])),f.createElementVNode("span",null,f.toDisplayString(l.label),1)],10,w4)),64))]))}}),S4={class:"wov-stroke-color-button"},E4={class:"wov-stroke-dropdown"},C4={key:1,class:"wov-stroke-divider"},Yk=f.defineComponent({__name:"ShapeStrokeColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Tt(),r=po(()=>e.entityIds,yn),o=f.ref(!1),s=f.computed(()=>{const h=new Set;for(const p of r.value.values())if(p){const m=qi({red:p.strokeRed,green:p.strokeGreen,blue:p.strokeBlue,alpha:255});h.add(m)}return Array.from(h)}),i=f.computed(()=>s.value.length>1),a=f.computed(()=>s.value[0]??"#000000"),l=f.computed(()=>{const h=r.value.values().next().value;return(h==null?void 0:h.strokeKind)??dt.Solid}),c=f.computed(()=>{const h=new Set;for(const p of r.value.values())p&&h.add(p.strokeKind);return h.size>1});function u(h){n(p=>{for(const m of e.entityIds){const g=yn.write(p,m);g.strokeRed=h.red,g.strokeGreen=h.green,g.strokeBlue=h.blue}})}function d(h){n(p=>{for(const m of e.entityIds){const g=yn.write(p,m);g.strokeKind=h}})}return(h,p)=>(f.openBlock(),f.createBlock(Hn,{title:"Stroke Color"},{button:f.withCtx(()=>[f.createElementVNode("div",S4,[p[1]||(p[1]=f.createElementVNode("svg",{viewBox:"0 0 20 20",class:"wov-stroke-color-icon",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round"},[f.createElementVNode("path",{d:"M2.5 12.563c1.655-.886 5.9-3.293 8.568-4.355 2.668-1.062.101 2.822 1.32 3.105 1.218.283 5.112-1.814 5.112-1.814m-13.469 2.23c2.963-1.586 6.13-5.62 7.468-4.998 1.338.623-1.153 4.11-.132 5.595 1.02 1.487 6.133-1.43 6.133-1.43","stroke-width":"1.25"})],-1)),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createElementVNode("div",E4,[o.value?f.createCommentVNode("",!0):(f.openBlock(),f.createBlock(b4,{key:0,currentStyle:l.value,hasMultipleStyles:c.value,onChange:d},null,8,["currentStyle","hasMultipleStyles"])),o.value?f.createCommentVNode("",!0):(f.openBlock(),f.createElementBlock("div",C4)),f.createVNode(hc,{currentColor:a.value,hideHighlight:i.value,withPicker:!0,onChange:u,onPickerOpen:p[0]||(p[0]=m=>o.value=m)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),x4={key:0,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},T4={key:1,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},M4={key:2,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},_4={key:3,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},qk=f.defineComponent({__name:"TextAlignmentButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds),o=[wn.Left,wn.Center,wn.Right,wn.Justify];function s(){const i=o.indexOf(n.alignment),a=o[(i+1)%o.length];r.setAlignment(a)}return(i,a)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(qs,{key:0,title:"Text Align",onClick:s},{default:f.withCtx(()=>[f.unref(n).alignment===f.unref(wn).Left?(f.openBlock(),f.createElementBlock("svg",x4,[...a[0]||(a[0]=[f.createElementVNode("path",{d:"M288 64c0 17.7-14.3 32-32 32L32 96C14.3 96 0 81.7 0 64S14.3 32 32 32l224 0c17.7 0 32 14.3 32 32zm0 256c0 17.7-14.3 32-32 32L32 352c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zM0 192c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 224c-17.7 0-32-14.3-32-32zM448 448c0 17.7-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z"},null,-1)])])):f.unref(n).alignment===f.unref(wn).Center?(f.openBlock(),f.createElementBlock("svg",T4,[...a[1]||(a[1]=[f.createElementVNode("path",{d:"M352 64c0-17.7-14.3-32-32-32L128 32c-17.7 0-32 14.3-32 32s14.3 32 32 32l192 0c17.7 0 32-14.3 32-32zm96 128c0-17.7-14.3-32-32-32L32 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l384 0c17.7 0 32-14.3 32-32zM0 448c0 17.7 14.3 32 32 32l384 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L32 416c-17.7 0-32 14.3-32 32zM352 320c0-17.7-14.3-32-32-32l-192 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l192 0c17.7 0 32-14.3 32-32z"},null,-1)])])):f.unref(n).alignment===f.unref(wn).Right?(f.openBlock(),f.createElementBlock("svg",M4,[...a[2]||(a[2]=[f.createElementVNode("path",{d:"M448 64c0 17.7-14.3 32-32 32L192 96c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zm0 256c0 17.7-14.3 32-32 32l-224 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zM0 192c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 224c-17.7 0-32-14.3-32-32zM448 448c0 17.7-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z"},null,-1)])])):(f.openBlock(),f.createElementBlock("svg",_4,[...a[3]||(a[3]=[f.createElementVNode("path",{d:"M448 64c0-17.7-14.3-32-32-32L32 32C14.3 32 0 46.3 0 64S14.3 96 32 96l384 0c17.7 0 32-14.3 32-32zm0 256c0-17.7-14.3-32-32-32L32 288c-17.7 0-32 14.3-32 32s14.3 32 32 32l384 0c17.7 0 32-14.3 32-32zM0 192c0 17.7 14.3 32 32 32l384 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L32 160c-17.7 0-32 14.3-32 32zM448 448c0-17.7-14.3-32-32-32L32 416c-17.7 0-32 14.3-32 32s14.3 32 32 32l384 0c17.7 0 32-14.3 32-32z"},null,-1)])]))]),_:1})):f.createCommentVNode("",!0)}}),Jk=f.defineComponent({__name:"TextBoldButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds);return(o,s)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(qs,{key:0,title:"Bold",class:f.normalizeClass({"wov-active":f.unref(n).isBold}),onClick:f.unref(r).toggleBold},{default:f.withCtx(()=>[...s[0]||(s[0]=[f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",fill:"currentColor"},[f.createElementVNode("path",{d:"M0 64C0 46.3 14.3 32 32 32l48 0 16 0 128 0c70.7 0 128 57.3 128 128c0 31.3-11.3 60.1-30 82.3c37.1 22.4 62 63.1 62 109.7c0 70.7-57.3 128-128 128L96 480l-16 0-48 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l16 0 0-160L48 96 32 96C14.3 96 0 81.7 0 64zM224 224c35.3 0 64-28.7 64-64s-28.7-64-64-64L112 96l0 128 112 0zM112 288l0 128 144 0c35.3 0 64-28.7 64-64s-28.7-64-64-64l-32 0-112 0z"})],-1)])]),_:1},8,["class","onClick"])):f.createCommentVNode("",!0)}}),A4={class:"wov-text-color-button"},I4={class:"wov-text-icon-container"},Xk=f.defineComponent({__name:"TextColorButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds),o=f.computed(()=>n.color??"#000000"),s=f.computed(()=>({backgroundColor:o.value}));function i(a){r.setColor(qi(a))}return(a,l)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(Hn,{key:0,title:"Text Color"},{button:f.withCtx(()=>[f.createElementVNode("div",A4,[f.createElementVNode("div",I4,[l[0]||(l[0]=f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 640",fill:"currentColor",class:"wov-text-icon"},[f.createElementVNode("path",{d:"M349.1 114.7C343.9 103.3 332.5 96 320 96C307.5 96 296.1 103.3 290.9 114.7L123.5 480L112 480C94.3 480 80 494.3 80 512C80 529.7 94.3 544 112 544L200 544C217.7 544 232 529.7 232 512C232 494.3 217.7 480 200 480L193.9 480L215.9 432L424.2 432L446.2 480L440.1 480C422.4 480 408.1 494.3 408.1 512C408.1 529.7 422.4 544 440.1 544L528.1 544C545.8 544 560.1 529.7 560.1 512C560.1 494.3 545.8 480 528.1 480L516.6 480L349.2 114.7zM394.8 368L245.2 368L320 204.8L394.8 368z"})],-1)),f.createElementVNode("div",{class:"wov-color-underline",style:f.normalizeStyle(s.value)},null,4)]),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createVNode(hc,{currentColor:o.value,withPicker:!0,onChange:i},null,8,["currentColor"])]),_:1})):f.createCommentVNode("",!0)}});function Gk(){const t=f.inject(Rn);if(!t)throw new Error("useFonts must be used within a WovenCanvas component");return f.computed(()=>{const e=t.getEditor();return e?e.fonts.filter(n=>n.selectable):[]})}const B4={class:"wov-font-family-button"},P4={class:"wov-font-family-label"},N4={class:"wov-font-list"},D4=["onClick"],O4=["src","alt"],Qk=f.defineComponent({__name:"TextFontFamilyButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds),o=Gk(),s=f.computed(()=>o.value.map(u=>({name:u.name,displayName:u.displayName,previewImage:u.previewImage}))),i=f.computed(()=>n.fontFamily),a=f.computed(()=>{const u=i.value;if(u===null)return"Mixed";const d=s.value.find(h=>h.name===u);return(d==null?void 0:d.displayName)??u});function l(u){r.setFontFamily(u)}function c(u){u.stopPropagation()}return(u,d)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(Hn,{key:0,title:"Font Family"},{button:f.withCtx(()=>[f.createElementVNode("div",B4,[f.createElementVNode("span",P4,f.toDisplayString(a.value),1),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createElementVNode("div",{class:"wov-font-family-menu",onWheel:c,onClick:d[0]||(d[0]=f.withModifiers(()=>{},["stop"]))},[f.createElementVNode("div",N4,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(s.value,h=>(f.openBlock(),f.createElementBlock("div",{key:h.name,class:f.normalizeClass(["wov-font-item",{active:i.value===h.name}]),onClick:p=>l(h.name)},[h.previewImage?(f.openBlock(),f.createElementBlock("img",{key:0,class:"wov-font-preview",src:h.previewImage,alt:h.name},null,8,O4)):(f.openBlock(),f.createElementBlock("span",{key:1,class:"wov-font-name",style:f.normalizeStyle({fontFamily:h.name})},f.toDisplayString(h.displayName),5))],10,D4))),128))])],32)]),_:1})):f.createCommentVNode("",!0)}}),R4={class:"wov-font-size-button"},z4={class:"wov-font-size-label"},$4=["onClick"],L4={key:0,class:"wov-check-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},F4={class:"wov-input-container"},V4=["value"],ev=f.defineComponent({__name:"TextFontSizeButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds),o=[{label:"Small",value:16,displayValue:10},{label:"Medium",value:24,displayValue:12},{label:"Large",value:40,displayValue:16},{label:"Huge",value:96,displayValue:20}],s=f.computed(()=>n.fontSize),i=f.computed(()=>{const h=s.value;if(h===null)return"Mixed";const p=o.find(m=>m.value===h);return p?p.label:`${+h.toFixed(1)} px`}),a=f.computed(()=>{const h=s.value;return h===null?"":String(+h.toFixed(1))});function l(h){r.setFontSize(h)}function c(h){const p=h.target,m=Number.parseFloat(p.value);!Number.isNaN(m)&&m>0&&l(m)}function u(h){h.key==="Enter"&&h.target.blur()}function d(h){h.stopPropagation()}return(h,p)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(Hn,{key:0,title:"Font Size"},{button:f.withCtx(()=>[f.createElementVNode("div",R4,[f.createElementVNode("span",z4,f.toDisplayString(i.value),1),f.createVNode(jn,{class:"wov-chevron-down"})])]),dropdown:f.withCtx(()=>[f.createElementVNode("div",{class:"wov-font-size-menu",onWheel:d,onClick:p[0]||(p[0]=f.withModifiers(()=>{},["stop"]))},[(f.openBlock(),f.createElementBlock(f.Fragment,null,f.renderList(o,m=>f.createElementVNode("div",{key:m.value,class:f.normalizeClass(["wov-font-size-option",{active:s.value===m.value}]),onClick:g=>l(m.value)},[s.value===m.value?(f.openBlock(),f.createElementBlock("svg",L4,[...p[1]||(p[1]=[f.createElementVNode("path",{d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"},null,-1)])])):f.createCommentVNode("",!0),f.createElementVNode("span",{class:"wov-option-label",style:f.normalizeStyle({fontSize:`${m.displayValue}px`})},f.toDisplayString(m.label),5)],10,$4)),64)),p[3]||(p[3]=f.createElementVNode("div",{class:"wov-separator"},null,-1)),f.createElementVNode("div",F4,[f.createElementVNode("input",{class:"wov-custom-input",value:a.value,onInput:c,onKeydown:u,placeholder:"Custom size"},null,40,V4),p[2]||(p[2]=f.createElementVNode("span",{class:"wov-px-suffix"},"px",-1))])],32)]),_:1})):f.createCommentVNode("",!0)}}),tv=f.defineComponent({__name:"TextItalicButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds);return(o,s)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(qs,{key:0,title:"Italic",class:f.normalizeClass({"wov-active":f.unref(n).isItalic}),onClick:f.unref(r).toggleItalic},{default:f.withCtx(()=>[...s[0]||(s[0]=[f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",fill:"currentColor"},[f.createElementVNode("path",{d:"M128 64c0-17.7 14.3-32 32-32l192 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-58.7 0L160 416l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l58.7 0L224 96l-64 0c-17.7 0-32-14.3-32-32z"})],-1)])]),_:1},8,["class","onClick"])):f.createCommentVNode("",!0)}}),nv=f.defineComponent({__name:"TextUnderlineButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Br(()=>e.entityIds);return(o,s)=>f.unref(n).showTextMenuButtons?(f.openBlock(),f.createBlock(qs,{key:0,title:"Underline",class:f.normalizeClass({"wov-active":f.unref(n).isUnderline}),onClick:f.unref(r).toggleUnderline},{default:f.withCtx(()=>[...s[0]||(s[0]=[f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},[f.createElementVNode("path",{d:"M16 64c0-17.7 14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 53 43 96 96 96s96-43 96-96l0-128-16 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 88.4-71.6 160-160 160s-160-71.6-160-160L64 96 48 96C30.3 96 16 81.7 16 64zM0 448c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32z"})],-1)])]),_:1},8,["class","onClick"])):f.createCommentVNode("",!0)}}),rv=f.defineComponent({__name:"CanvasBackground",props:{background:{}},setup(t){const e=t,n=zt(he),r=zt(Dt),o=f.inject("containerRef"),s=f.ref({width:0,height:0});let i=null;const a=f.ref(null);let l=null;typeof document<"u"&&(l=document.createElement("canvas"));function c(y,w,k,b){const S=b/2;y.beginPath(),y.arc(w,k,S,0,Math.PI*2),y.fill()}function u(y,w,k){if(!l)return null;const b=k.dotSize??2,S=y*k.subdivisionStep,v=w*k.subdivisionStep;l.width=S,l.height=v;const x=l.getContext("2d");if(!x)return null;if(x.clearRect(0,0,S,v),x.fillStyle=k.strokeColor,k.subdivisionStep===1)c(x,S/2,v/2,b);else for(let T=0;T<k.subdivisionStep;T++)for(let A=0;A<k.subdivisionStep;A++){const P=(T+.5)*(S/k.subdivisionStep),$=(A+.5)*(v/k.subdivisionStep),U=T===0&&A===0?2*b:b;c(x,P,$,U)}return x.createPattern(l,"repeat")}function d(y,w,k,b,S,v){y.lineWidth=v,y.beginPath(),y.moveTo(w,k),y.lineTo(b,S),y.stroke()}function h(y,w,k){if(!l)return null;const b=k.gridSize??1,S=y*k.subdivisionStep,v=w*k.subdivisionStep;l.width=S,l.height=v;const x=l.getContext("2d");if(!x)return null;if(x.clearRect(0,0,S,v),x.strokeStyle=k.strokeColor,k.subdivisionStep===1)d(x,0,0,S,0,b),d(x,0,0,0,v,b);else{const T=S/k.subdivisionStep,A=v/k.subdivisionStep;for(let P=0;P<=k.subdivisionStep;P++){const $=P*T,V=P%k.subdivisionStep===0;d(x,$,0,$,v,V?3*b:b)}for(let P=0;P<=k.subdivisionStep;P++){const $=P*A,V=P%k.subdivisionStep===0;d(x,0,$,S,$,V?3*b:b)}}return x.createPattern(l,"repeat")}function p(y){let w=r.value.colWidth,k=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,v=s.value.height,x=n.value.left,T=n.value.top,A=x+S/n.value.zoom,P=T+v/n.value.zoom;let $=w*b,V=k*b,U=0,M=0,L=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY;for(;;){$=b*w,V=b*k,U=Math.floor(x/$)*$,M=Math.floor(T/V)*V;const tt=Math.ceil(A/$)*$,ko=Math.ceil(P/V)*V;if(q=Math.round((tt-U)/w),L=Math.round((ko-M)/k),Math.max(q,L)>200)w*=2,k*=2;else break}const se=w*n.value.zoom,Z=k*n.value.zoom,H=Math.round(se),J=Math.round(Z),ce=u(H,J,e.background);if(!ce)return;ce.setTransform(new DOMMatrix().scale(se/H,Z/J));const Ke=(U-x-w/2)*n.value.zoom,Be=(M-T-k/2)*n.value.zoom;y.save(),y.translate(Ke,Be),y.fillStyle=ce,y.fillRect(0,0,S+$*n.value.zoom,v+V*n.value.zoom),y.restore()}function m(y){let w=r.value.colWidth,k=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,v=s.value.height,x=n.value.left,T=n.value.top,A=x+S/n.value.zoom,P=T+v/n.value.zoom;let $=w*b,V=k*b,U=0,M=0,L=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY;for(;;){$=b*w,V=b*k,U=Math.floor(x/$)*$,M=Math.floor(T/V)*V;const tt=Math.ceil(A/$)*$,ko=Math.ceil(P/V)*V;if(q=Math.round((tt-U)/w),L=Math.round((ko-M)/k),Math.max(q,L)>200)w*=2,k*=2;else break}const se=w*n.value.zoom,Z=k*n.value.zoom,H=Math.round(se),J=Math.round(Z),ce=h(H,J,e.background);if(!ce)return;ce.setTransform(new DOMMatrix().scale(se/H,Z/J));const Ke=(U-x)*n.value.zoom,Be=(M-T)*n.value.zoom;y.save(),y.translate(Ke,Be),y.fillStyle=ce,y.fillRect(0,0,S+$*n.value.zoom,v+V*n.value.zoom),y.restore()}function g(){const y=a.value;if(!y)return;const w=y.getContext("2d");if(!w)return;const{width:k,height:b}=s.value;k===0||b===0||(y.width=k,y.height=b,w.clearRect(0,0,k,b),w.fillStyle=e.background.color,w.fillRect(0,0,k,b),e.background.kind==="dots"?p(w):e.background.kind==="grid"&&m(w))}return f.watch(()=>[e.background,n.value,r.value,s.value],()=>{g()},{deep:!0}),f.onMounted(()=>{const y=o==null?void 0:o.value;if(y){const w=()=>{s.value={width:y.clientWidth,height:y.clientHeight}};w(),i=new ResizeObserver(w),i.observe(y)}g()}),f.onUnmounted(()=>{i==null||i.disconnect()}),(y,w)=>(f.openBlock(),f.createElementBlock("canvas",{ref_key:"canvasRef",ref:a,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none"}},null,512))}});function ov(t,e){if(e.length===0)return new Set;const n=e[0].tag,r=t.blockDefs[n];if(!r)return new Set;const o=new Set(r.components.map(s=>s.name));for(let s=1;s<e.length;s++){const i=e[s].tag,a=t.blockDefs[i];if(!a){o.clear();break}const l=new Set(a.components.map(c=>c.name));for(const c of o)l.has(c)||o.delete(c)}return o}const W4={key:0,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-align-vertical-justify-start-icon lucide-align-vertical-justify-start"},U4={key:1,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-align-vertical-justify-center-icon lucide-align-vertical-justify-center"},H4={key:2,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-align-vertical-justify-end-icon lucide-align-vertical-justify-end"},j4=f.defineComponent({__name:"VerticalAlignButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=Tt(),{state:r}=Br(()=>e.entityIds),o=[st.Top,st.Center,st.Bottom],s=po(()=>e.entityIds,Ao),i=f.computed(()=>{let l=null;for(const c of s.value.values()){const u=(c==null?void 0:c.value)??st.Top;if(l===null)l=u;else if(l!==u)return null}return l});function a(){const l=i.value??st.Top,c=o.indexOf(l),u=o[(c+1)%o.length];n(d=>{for(const h of e.entityIds){const p=Ao.write(d,h);p.value=u}})}return(l,c)=>f.unref(r).showTextMenuButtons?(f.openBlock(),f.createBlock(qs,{key:0,title:"Vertical Align",onClick:a},{default:f.withCtx(()=>[i.value===f.unref(st).Top||i.value===null?(f.openBlock(),f.createElementBlock("svg",W4,[...c[0]||(c[0]=[f.createElementVNode("rect",{width:"14",height:"6",x:"5",y:"16",rx:"2"},null,-1),f.createElementVNode("rect",{width:"10",height:"6",x:"7",y:"6",rx:"2"},null,-1),f.createElementVNode("path",{d:"M2 2h20"},null,-1)])])):i.value===f.unref(st).Center?(f.openBlock(),f.createElementBlock("svg",U4,[...c[1]||(c[1]=[f.createElementVNode("rect",{width:"14",height:"6",x:"5",y:"16",rx:"2"},null,-1),f.createElementVNode("rect",{width:"10",height:"6",x:"7",y:"2",rx:"2"},null,-1),f.createElementVNode("path",{d:"M2 12h20"},null,-1)])])):(f.openBlock(),f.createElementBlock("svg",H4,[...c[2]||(c[2]=[f.createElementVNode("rect",{width:"14",height:"6",x:"5",y:"12",rx:"2"},null,-1),f.createElementVNode("rect",{width:"10",height:"6",x:"7",y:"2",rx:"2"},null,-1),f.createElementVNode("path",{d:"M2 22h20"},null,-1)])]))]),_:1})):f.createCommentVNode("",!0)}}),sv=f.defineComponent({__name:"FloatingMenuBar",setup(t){const e=f.useSlots(),{reset:n}=go(),r=f.inject(ty),{selectedIds:o,commonComponents:s}=r,i=new Set(["color","text","verticalAlign","penStroke","elbowArrow","arcArrow","shape"]),a=f.computed(()=>{const c=[];for(const u of s.value){const d=`button:${u}`;!i.has(u)&&e[d]&&c.push(u)}return c});function l(){n()}return f.onUnmounted(()=>{n()}),(c,u)=>(f.openBlock(),f.createElementBlock("div",{class:"wov-floating-menu-bar",onMouseleave:l},[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(a.value,d=>f.renderSlot(c.$slots,`button:${d}`,{key:d,entityIds:f.unref(o)})),128)),f.renderSlot(c.$slots,"button:color",{entityIds:f.unref(o)},()=>[f.unref(s).has("color")?(f.openBlock(),f.createBlock(Hk,{key:0,entityIds:f.unref(o)},null,8,["entityIds"])):f.createCommentVNode("",!0)]),f.renderSlot(c.$slots,"button:shape",{entityIds:f.unref(o)},()=>[f.unref(s).has("shape")?(f.openBlock(),f.createElementBlock(f.Fragment,{key:0},[f.createVNode(Kk,{entityIds:f.unref(o)},null,8,["entityIds"]),f.createVNode(Zk,{entityIds:f.unref(o)},null,8,["entityIds"]),f.createVNode(Yk,{entityIds:f.unref(o)},null,8,["entityIds"])],64)):f.createCommentVNode("",!0)]),f.renderSlot(c.$slots,"button:penStroke",{entityIds:f.unref(o)},()=>[f.unref(s).has("penStroke")?(f.openBlock(),f.createBlock(jk,{key:0,entityIds:f.unref(o)},null,8,["entityIds"])):f.createCommentVNode("",!0)]),f.renderSlot(c.$slots,"button:arrowThickness",{entityIds:f.unref(o)},()=>[f.unref(s).has("elbowArrow")||f.unref(s).has("arcArrow")?(f.openBlock(),f.createBlock(Vk,{key:0,entityIds:f.unref(o)},null,8,["entityIds"])):f.createCommentVNode("",!0)]),f.renderSlot(c.$slots,"button:arrowHeadStart",{entityIds:f.unref(o)},()=>[f.unref(s).has("elbowArrow")||f.unref(s).has("arcArrow")?(f.openBlock(),f.createBlock($f,{key:0,entityIds:f.unref(o),side:"start"},null,8,["entityIds"])):f.createCommentVNode("",!0)]),f.renderSlot(c.$slots,"button:arrowHeadEnd",{entityIds:f.unref(o)},()=>[f.unref(s).has("elbowArrow")||f.unref(s).has("arcArrow")?(f.openBlock(),f.createBlock($f,{key:0,entityIds:f.unref(o),side:"end"},null,8,["entityIds"])):f.createCommentVNode("",!0)]),f.renderSlot(c.$slots,"button:text",{entityIds:f.unref(o)},()=>[f.unref(s).has("text")?(f.openBlock(),f.createElementBlock(f.Fragment,{key:0},[f.createVNode(Qk,{entityIds:f.unref(o)},null,8,["entityIds"]),f.createVNode(ev,{entityIds:f.unref(o)},null,8,["entityIds"]),u[0]||(u[0]=f.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),f.createVNode(Jk,{entityIds:f.unref(o)},null,8,["entityIds"]),f.createVNode(tv,{entityIds:f.unref(o)},null,8,["entityIds"]),f.createVNode(nv,{entityIds:f.unref(o)},null,8,["entityIds"]),u[1]||(u[1]=f.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),f.createVNode(Xk,{entityIds:f.unref(o)},null,8,["entityIds"]),f.createVNode(qk,{entityIds:f.unref(o)},null,8,["entityIds"]),f.unref(s).has("verticalAlign")?(f.openBlock(),f.createBlock(j4,{key:0,entityIds:f.unref(o)},null,8,["entityIds"])):f.createCommentVNode("",!0)],64)):f.createCommentVNode("",!0)]),f.createVNode(Lf)],32))}}),Z4={class:"wov-floating-menu-inner"},iv=f.defineComponent({__name:"FloatingMenu",setup(t){const e=f.inject(Rn),n=lk([_,ht]),r=zt(he),o=zt(Nt),s=zt(Nn),i=Ji(),a=f.computed(()=>n.value.map(b=>b.entityId)),l=f.computed(()=>{const b=e==null?void 0:e.getEditor();if(!b||n.value.length===0)return new Set;const S=n.value.map(v=>({tag:v.block.value.tag}));return ov(b,S)});f.provide(ty,{selectedIds:a,commonComponents:l});const c=[0,0,0,0];function u(...b){let S=1/0,v=1/0,x=-1/0,T=-1/0,A=!1;for(const P of b){if(!P)continue;const $=P.getBoundingClientRect();$.width<=0||(A=!0,S=Math.min(S,$.left),v=Math.min(v,$.top),x=Math.max(x,$.right),T=Math.max(T,$.bottom))}return A?{x:S,y:v,left:S,top:v,right:x,bottom:T,width:x-S,height:T-v,toJSON:()=>({})}:null}const d=f.computed(()=>{if(n.value.length===0)return null;const b=r.value;if(!b)return null;let S=null;for(const v of n.value){const x=v.block.value;ot.getAabb(x.position,x.size,x.rotateZ,c),Q.translate(c,[-b.left,-b.top]),Q.scale(c,b.zoom),S===null?S=Q.clone(c):Q.union(S,c)}return S}),h=f.inject("containerRef"),p=f.computed(()=>{const b=h==null?void 0:h.value;if(!b)return null;r.value,i.updateCounter.value;const S=i.blockElement.value,v=i.textElement.value,x=u(S,v);if(x)return{getBoundingClientRect:()=>x};const T=d.value;if(!T)return null;const A=b.getBoundingClientRect();return{getBoundingClientRect(){return{x:A.left+T[0],y:A.top+T[1],width:T[2]-T[0],height:T[3]-T[1],top:A.top+T[1],left:A.left+T[0],right:A.left+T[2],bottom:A.top+T[3]}}}}),m=f.ref(null),{floatingStyles:g}=zf(p,m,{placement:"top",middleware:[Df(12),Rf({fallbackPlacements:["bottom"]}),Of({padding:8})]}),y=f.computed(()=>{const b=d.value,S=o.value;return!b||!S?!0:b[2]<0||b[0]>S.width||b[3]<0||b[1]>S.height}),w=[me.Dragging,me.SelectionBoxDragging],k=f.computed(()=>n.value.length>0&&!y.value&&!w.includes(s.value.state));return(b,S)=>(f.openBlock(),f.createBlock(f.Transition,{name:"wov-fade"},{default:f.withCtx(()=>[k.value?(f.openBlock(),f.createElementBlock("div",{key:0,ref_key:"floatingRef",ref:m,class:"wov-floating-menu",style:f.normalizeStyle(f.unref(g))},[f.createElementVNode("div",Z4,[f.renderSlot(b.$slots,"default",{},()=>[f.createVNode(sv)])])],4)):f.createCommentVNode("",!0)]),_:3}))}}),K4={key:0,class:"wov-loading-overlay"},Y4={class:"wov-loading-spinner"},av=f.defineComponent({__name:"LoadingOverlay",props:{isLoading:{type:Boolean}},setup(t){const e=f.ref("|"),n=["|","/","-","\\"];let r=null;return f.onMounted(()=>{r=setInterval(()=>{const o=n.indexOf(e.value);e.value=n[(o+1)%n.length]},100)}),f.onUnmounted(()=>{r!==null&&clearInterval(r)}),(o,s)=>(f.openBlock(),f.createBlock(f.Transition,{name:"wov-loading-fade"},{default:f.withCtx(()=>[t.isLoading?(f.openBlock(),f.createElementBlock("div",K4,[f.createElementVNode("div",Y4,f.toDisplayString(e.value),1)])):f.createCommentVNode("",!0)]),_:1}))}}),lr=f.defineComponent({__name:"ToolbarButton",props:{name:{},tooltip:{},dragOutSnapshot:{},placementSnapshot:{},cursor:{default:"crosshair"}},setup(t){const e=t,n=f.inject(ed);if(!n)throw new Error("ToolbarButton must be used within a Toolbar component");const r=n,o=f.ref(null),{show:s,hide:i}=go(),a=f.computed(()=>r.activeTool.value===e.name);function l(){r.setTool(e.name,e.placementSnapshot,e.cursor)}function c(){r.onToolPointerDown(e.name,e.dragOutSnapshot)}function u(){r.onToolPointerUp()}function d(){e.tooltip&&o.value&&s(e.tooltip,o.value)}function h(){i()}return(p,m)=>(f.openBlock(),f.createElementBlock("button",{ref_key:"buttonRef",ref:o,class:f.normalizeClass(["wov-toolbar-button",{selected:a.value}]),onClick:l,onPointerdown:c,onPointerup:u,onMouseenter:d,onMouseleave:h},[f.renderSlot(p.$slots,"default")],34))}}),q4='<?xml version="1.0" encoding="UTF-8"?><svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4.35 4.75" width="20" height="20"><defs><style>.cls-1{stroke:#fff;stroke-miterlimit:10;stroke-width:.25px;}</style></defs><path class="cls-1" d="M2.39,2.88s-.04.01-.05.02c-.01,0-.02.01-.03.02,0,.01-.02.02-.03.05l-.77,1.44c-.07.13-.1.19-.14.2-.03.01-.07,0-.1-.01-.03-.02-.05-.09-.09-.23L.16.41c-.03-.13-.05-.19-.03-.23.02-.03.04-.05.08-.06.04,0,.1.02.21.08l3.59,1.94c.13.07.19.1.2.14.01.03,0,.07-.01.1-.02.03-.09.05-.23.09l-1.58.4Z"/></svg>',J4='<?xml version="1.0" encoding="UTF-8"?><svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4.08 4.75" width="24" height="24"><defs><style>.cls-1{fill:#fff;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:.25px;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;stroke-width:.51px;}</style></defs><path class="cls-1" d="M.89,2.25v.63M.89,2.25V.75c0-.21.17-.38.38-.38s.38.17.38.38M.89,2.25c0-.21-.17-.37-.38-.37s-.38.17-.38.37v.5c0,1.04.86,1.87,1.91,1.87s1.91-.84,1.91-1.87v-1.25c0-.21-.17-.38-.38-.38s-.38.17.38.38M1.66.75v1.38M1.66.75v-.25c0-.21.17-.38.38-.38s.38.17.38.38v.25M2.42.75v1.38M2.42.75c0-.21.17-.38.38-.38s.38.17.38.38v.75M3.19,1.5v.63"/><line class="cls-2" x1="2.8" y1=".77" x2="2.8" y2="2.03"/><line class="cls-2" x1="2.04" y1=".64" x2="2.04" y2="2.02"/><line class="cls-2" x1="1.27" y1=".84" x2="1.27" y2="2.29"/></svg>',X4='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 8v-2a2 2 0 0 1 2 -2h2" /><path d="M4 16v2a2 2 0 0 0 2 2h2" /><path d="M16 4h2a2 2 0 0 1 2 2v2" /><path d="M16 20h2a2 2 0 0 0 2 -2v-2" /><path d="M9 12l6 0" /><path d="M12 9l0 6" /></svg>',ts={Select:"select",Hand:"hand",Crosshair:"crosshair"},lv={[ts.Select]:{makeSvg:()=>q4,hotspot:[1,0],rotationOffset:0},[ts.Hand]:{makeSvg:()=>J4,hotspot:[12,12],rotationOffset:0},[ts.Crosshair]:{makeSvg:()=>X4,hotspot:[12,12],rotationOffset:0}},G4={viewBox:"0 0 20 20",style:{"fill-rule":"evenodd","clip-rule":"evenodd","stroke-miterlimit":"10"}},cv=f.defineComponent({__name:"SelectTool",setup(t){const{nextEditorTick:e}=Tt(),{activeTool:n}=Tf();return f.watch(n,(r,o)=>{o==="select"&&e(s=>{mi.spawn(s)})}),(r,o)=>(f.openBlock(),f.createBlock(lr,{name:"select",tooltip:"Select",cursor:f.unref(ts).Select},{default:f.withCtx(()=>[(f.openBlock(),f.createElementBlock("svg",G4,[...o[0]||(o[0]=[f.createElementVNode("g",{transform:"matrix(4.21053,0,0,4.21053,0.842105,0)"},[f.createElementVNode("path",{fill:"none",stroke:"currentColor","stroke-width":"0.5",d:"M2.39,2.88C2.38,2.885 2.34,2.9 2.33,2.91C2.32,2.91 2.298,2.939 2.28,2.97L1.51,4.41C1.44,4.54 1.41,4.6 1.37,4.61C1.34,4.62 1.3,4.61 1.27,4.6C1.24,4.58 1.22,4.51 1.18,4.37L0.16,0.41C0.13,0.28 0.11,0.22 0.13,0.18C0.15,0.15 0.17,0.13 0.21,0.12C0.25,0.12 0.31,0.14 0.42,0.2L4.01,2.14C4.14,2.21 4.2,2.24 4.21,2.28C4.22,2.31 4.21,2.35 4.2,2.38C4.18,2.41 4.11,2.43 3.97,2.47L2.39,2.88Z"})],-1)])]))]),_:1},8,["cursor"]))}}),uv=f.defineComponent({__name:"HandTool",setup(t){return(e,n)=>(f.openBlock(),f.createBlock(lr,{name:"hand",tooltip:"Hand",cursor:f.unref(ts).Hand},{default:f.withCtx(()=>[...n[0]||(n[0]=[f.createElementVNode("svg",{viewBox:"0 0 20.56 24"},[f.createElementVNode("path",{fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4.47,11.39v3.18M4.47,11.39V3.81c0-1.06.86-1.92,1.92-1.92s1.92.86,1.92,1.92M4.47,11.39c0-1.06-.86-1.87-1.92-1.87s-1.92.86-1.92,1.87v2.53c0,5.25,4.35,9.45,9.65,9.45s9.65-4.24,9.65-9.45v-6.32c0-1.06-.86-1.92-1.92-1.92s-1.92.86-1.92,1.92M8.36,3.81v6.97M8.36,3.81v-1.26c0-1.06.86-1.92,1.92-1.92s1.92.86,1.92,1.92v1.26M12.2,3.81v6.97M12.2,3.81c0-1.06.86-1.92,1.92-1.92s1.92.86,1.92,1.92v3.79M16.09,7.6v3.18"})],-1)])]),_:1},8,["cursor"]))}}),dv=f.defineComponent({__name:"StickyNoteTool",setup(t){const e=JSON.stringify({block:{tag:"sticky-note",size:[200,200]},color:{red:255,green:242,blue:117},text:{defaultAlignment:wn.Center},verticalAlign:{value:st.Center}});return(n,r)=>(f.openBlock(),f.createBlock(lr,{name:"sticky-note",tooltip:"Sticky Note","drag-out-snapshot":f.unref(e),"placement-snapshot":f.unref(e)},{default:f.withCtx(()=>[...r[0]||(r[0]=[f.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[f.createElementVNode("path",{d:"M4 4h12v12H4z"}),f.createElementVNode("path",{d:"M7 8h6M7 11h4"})],-1)])]),_:1},8,["drag-out-snapshot","placement-snapshot"]))}}),fv=f.defineComponent({__name:"ShapeTool",setup(t){const e=JSON.stringify({block:{tag:"shape",size:[200,200]},shape:{kind:"rectangle",strokeKind:dt.Solid,strokeWidth:2,strokeRed:0,strokeGreen:0,strokeBlue:0,strokeAlpha:255,fillRed:255,fillGreen:255,fillBlue:255,fillAlpha:0},text:{defaultAlignment:wn.Center},verticalAlign:{value:st.Center}});return(n,r)=>(f.openBlock(),f.createBlock(lr,{name:"shape",tooltip:"Shape","drag-out-snapshot":f.unref(e),"placement-snapshot":f.unref(e)},{default:f.withCtx(()=>[...r[0]||(r[0]=[f.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[f.createElementVNode("rect",{x:"3",y:"3",width:"14",height:"14",rx:"2"})],-1)])]),_:1},8,["drag-out-snapshot","placement-snapshot"]))}}),hv=f.defineComponent({__name:"EraserTool",setup(t){return(e,n)=>(f.openBlock(),f.createBlock(lr,{name:"eraser",tooltip:"Eraser"},{default:f.withCtx(()=>[...n[0]||(n[0]=[f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 640",fill:"currentColor"},[f.createElementVNode("path",{d:"M210.5 480L333.5 480L398.8 414.7L225.3 241.2L98.6 367.9L210.6 479.9zM256 544L210.5 544C193.5 544 177.2 537.3 165.2 525.3L49 409C38.1 398.1 32 383.4 32 368C32 352.6 38.1 337.9 49 327L295 81C305.9 70.1 320.6 64 336 64C351.4 64 366.1 70.1 377 81L559 263C569.9 273.9 576 288.6 576 304C576 319.4 569.9 334.1 559 345L424 480L544 480C561.7 480 576 494.3 576 512C576 529.7 561.7 544 544 544L256 544z"})],-1)])]),_:1}))}}),pv=f.defineComponent({__name:"PenTool",setup(t){return(e,n)=>(f.openBlock(),f.createBlock(lr,{name:"pen",tooltip:"Pen"},{default:f.withCtx(()=>[...n[0]||(n[0]=[f.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[f.createElementVNode("path",{d:"M13.586 3.586a2 2 0 1 1 2.828 2.828l-8.793 8.793-3.536.707.707-3.536 8.794-8.792Z","stroke-linecap":"round","stroke-linejoin":"round"}),f.createElementVNode("path",{d:"M12 5l3 3","stroke-linecap":"round"})],-1)])]),_:1}))}}),mv=f.defineComponent({__name:"TextTool",setup(t){const e=JSON.stringify({block:{tag:"text",size:[10,29]},text:{constrainWidth:!1,fontSizePx:24}}),n=JSON.stringify({block:{tag:"text",size:[36,29]},text:{content:"text",constrainWidth:!1,fontSizePx:24}});return(r,o)=>(f.openBlock(),f.createBlock(lr,{name:"text",tooltip:"Text","drag-out-snapshot":f.unref(n),"placement-snapshot":f.unref(e)},{default:f.withCtx(()=>[...o[0]||(o[0]=[f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-type-icon lucide-type"},[f.createElementVNode("path",{d:"M12 4v16"}),f.createElementVNode("path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2"}),f.createElementVNode("path",{d:"M9 20h6"})],-1)])]),_:1},8,["drag-out-snapshot","placement-snapshot"]))}}),gv=f.defineComponent({__name:"ElbowArrowTool",setup(t){const e=JSON.stringify({block:{tag:"elbow-arrow",size:[200,200]},elbowArrow:{points:[0,0,.5,0,.5,1,1,1],pointCount:4,startArrowHead:Ce.None,endArrowHead:Ce.V},connector:{}});return(n,r)=>(f.openBlock(),f.createBlock(lr,{name:"elbow-arrow",tooltip:"Elbow Arrow",cursor:"crosshair","drag-out-snapshot":f.unref(e)},{default:f.withCtx(()=>[...r[0]||(r[0]=[f.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[f.createElementVNode("path",{d:"M4 6 L10 6 L10 14 L16 14"}),f.createElementVNode("path",{d:"M13 11 L16 14 L13 17"})],-1)])]),_:1},8,["drag-out-snapshot"]))}}),yv=f.defineComponent({__name:"ImageTool",setup(t){const{nextEditorTick:e}=Tt(),{show:n,hide:r}=go(),{setTool:o}=Tf(),s=f.inject(Rn);if(!s)throw new Error("ImageTool must be used within a WovenCanvas component");const i=f.ref(null),a=f.ref(null);function l(){var p;(p=a.value)==null||p.click()}async function c(p){var Z;const m=p.target,g=(Z=m.files)==null?void 0:Z[0];if(!g)return;if(m.value="",!g.type.startsWith("image/")){console.warn("Selected file is not an image");return}const y=await u(g),w=s==null?void 0:s.getAssetManager(),k=await e(),b=he.read(k),S=Nt.read(k),v=b.left+S.width/b.zoom/2,x=b.top+S.height/b.zoom/2,A=Math.min(1,400/Math.max(y.width,y.height));let P=Math.round(y.width*A),$=Math.round(y.height*A);const V=Dt.read(k);V.enabled&&(P=Math.max(V.colWidth,Math.round(P/V.colWidth)*V.colWidth),$=Math.max(V.rowHeight,Math.round($/V.rowHeight)*V.rowHeight));const U=vt(k);G(k,U,_);const M=_.write(k,U);M.tag="image",M.position[0]=v-P/2,M.position[1]=x-$/2,M.size[0]=P,M.size[1]=$,Dt.snapPosition(k,M.position);const L=crypto.randomUUID();G(k,U,_o);const q=_o.write(k,U);q.identifier=L,q.uploadState=er.Pending,G(k,U,oi);const se=oi.write(k,U);if(se.width=y.width,se.height=y.height,se.alt=g.name,G(k,U,hi,{id:crypto.randomUUID()}),o("select",void 0,ts.Select),w)try{await w.upload(L,g,{filename:g.name,mimeType:g.type});const H=await e(),J=_o.write(H,U);J.uploadState=er.Complete}catch{const H=await e(),J=_o.write(H,U);J.uploadState=er.Failed}}function u(p){return new Promise((m,g)=>{const y=new window.Image;y.onload=()=>{m({width:y.naturalWidth,height:y.naturalHeight}),URL.revokeObjectURL(y.src)},y.onerror=()=>{g(new Error("Failed to load image")),URL.revokeObjectURL(y.src)},y.src=URL.createObjectURL(p)})}function d(){i.value&&n("Image",i.value)}function h(){r()}return(p,m)=>(f.openBlock(),f.createElementBlock(f.Fragment,null,[f.createElementVNode("button",{ref_key:"buttonRef",ref:i,class:"wov-toolbar-button",onClick:l,onMouseenter:d,onMouseleave:h},[...m[0]||(m[0]=[f.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[f.createElementVNode("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),f.createElementVNode("circle",{cx:"9",cy:"9",r:"2"}),f.createElementVNode("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})],-1)])],544),f.createElementVNode("input",{ref_key:"fileInputRef",ref:a,type:"file",accept:"image/*",style:{display:"none"},onChange:c},null,544)],64))}}),Q4={class:"wov-toolbar-container"},wv=f.defineComponent({__name:"Toolbar",setup(t){const e=f.useSlots(),{reset:n}=go(),{nextEditorTick:r}=Tt(),o=f.ref(null),s=f.ref(null),i=zt(Qe),a=f.computed(()=>i.value.leftMouseTool);function l(m,g,y){s.value=g??null,r(w=>{const k=Qe.write(w);k.leftMouseTool=m,k.heldSnapshot=g??"",y&&kn.setCursor(w,y)})}function c(m){r(g=>{const y=Qe.write(g);y.leftMouseTool="drag-out",y.heldSnapshot=m})}function u(m,g){o.value=m,s.value=g??null}function d(){o.value=null,s.value=null}function h(){n(),o.value&&s.value&&c(s.value),o.value=null,s.value=null}const p={activeTool:a,heldTool:o,setTool:l,dragOutTool:c,onToolPointerDown:u,onToolPointerUp:d};return f.provide(ed,p),(m,g)=>(f.openBlock(),f.createElementBlock("div",Q4,[f.createElementVNode("div",{class:"wov-toolbar",onMouseleave:h},[f.unref(e).default?f.renderSlot(m.$slots,"default",{key:0}):(f.openBlock(),f.createElementBlock(f.Fragment,{key:1},[f.createVNode(cv),f.createVNode(uv),f.createVNode(mv),f.createVNode(yv),f.createVNode(fv),f.createVNode(gv),f.createVNode(dv),f.createVNode(pv),f.createVNode(hv)],64)),f.createVNode(Lf)],32)]))}}),eL=f.defineComponent({__name:"ArcArrowTool",setup(t){return(e,n)=>(f.openBlock(),f.createBlock(lr,{name:"arc-arrow",tooltip:"Arc Arrow",cursor:"crosshair"},{default:f.withCtx(()=>[...n[0]||(n[0]=[f.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[f.createElementVNode("path",{d:"M4 14 Q 10 4, 16 14"}),f.createElementVNode("path",{d:"M13 11 L16 14 L12.5 15.5"})],-1)])]),_:1}))}}),tL=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const nL=Object.prototype.toString,rL=t=>nL.call(t)==="[object Object]",pc=()=>{};function Ff(t){return Array.isArray(t)?t:[t]}function oL(t,e,n){return f.watch(t,e,{...n,immediate:!0})}const kv=tL?window:void 0;function ea(t){var e;const n=f.toValue(t);return(e=n==null?void 0:n.$el)!==null&&e!==void 0?e:n}function Vf(...t){const e=(r,o,s,i)=>(r.addEventListener(o,s,i),()=>r.removeEventListener(o,s,i)),n=f.computed(()=>{const r=Ff(f.toValue(t[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return oL(()=>{var r,o;return[(r=(o=n.value)===null||o===void 0?void 0:o.map(s=>ea(s)))!==null&&r!==void 0?r:[kv].filter(s=>s!=null),Ff(f.toValue(n.value?t[1]:t[0])),Ff(f.unref(n.value?t[2]:t[1])),f.toValue(n.value?t[3]:t[2])]},([r,o,s,i],a,l)=>{if(!(r!=null&&r.length)||!(o!=null&&o.length)||!(s!=null&&s.length))return;const c=rL(i)?{...i}:i,u=r.flatMap(d=>o.flatMap(h=>s.map(p=>e(d,h,p,c))));l(()=>{u.forEach(d=>d())})},{flush:"post"})}function sL(t,e,n={}){const{window:r=kv,ignore:o=[],capture:s=!0,detectIframe:i=!1,controls:a=!1}=n;if(!r)return a?{stop:pc,cancel:pc,trigger:pc}:pc;let l=!0;const c=y=>f.toValue(o).some(w=>{if(typeof w=="string")return Array.from(r.document.querySelectorAll(w)).some(k=>k===y.target||y.composedPath().includes(k));{const k=ea(w);return k&&(y.target===k||y.composedPath().includes(k))}});function u(y){const w=f.toValue(y);return w&&w.$.subTree.shapeFlag===16}function d(y,w){const k=f.toValue(y),b=k.$.subTree&&k.$.subTree.children;return b==null||!Array.isArray(b)?!1:b.some(S=>S.el===w.target||w.composedPath().includes(S.el))}const h=y=>{const w=ea(t);if(y.target!=null&&!(!(w instanceof Element)&&u(t)&&d(t,y))&&!(!w||w===y.target||y.composedPath().includes(w))){if("detail"in y&&y.detail===0&&(l=!c(y)),!l){l=!0;return}e(y)}};let p=!1;const m=[Vf(r,"click",y=>{p||(p=!0,setTimeout(()=>{p=!1},0),h(y))},{passive:!0,capture:s}),Vf(r,"pointerdown",y=>{const w=ea(t);l=!c(y)&&!!(w&&!y.composedPath().includes(w))},{passive:!0}),i&&Vf(r,"blur",y=>{setTimeout(()=>{var w;const k=ea(t);((w=r.document.activeElement)===null||w===void 0?void 0:w.tagName)==="IFRAME"&&!(k!=null&&k.contains(r.document.activeElement))&&e(y)},0)},{passive:!0})].filter(Boolean),g=()=>m.forEach(y=>y());return a?{stop:g,cancel:()=>{l=!1},trigger:y=>{l=!0,h(y),l=!1}}:g}const iL={class:"wov-user-presence-avatars"},aL=["src","alt"],lL={class:"wov-user-presence-list"},cL=["src","alt"],uL={class:"wov-user-presence-name"},dL=4,vv=f.defineComponent({__name:"UserPresence",props:{users:{}},setup(t){const e=t,n=f.ref(!1),r=f.ref(null);sL(r,()=>{n.value=!1});function o(a){if(!a)return"?";const l=a.trim().split(/\s+/);return l.length>=2?(l[0][0]+l[1][0]).toUpperCase():a.slice(0,2).toUpperCase()}const s=f.computed(()=>e.users.map(a=>({sessionId:a.sessionId,name:a.name,color:a.color,avatar:a.avatar,initials:o(a.name)}))),i=f.computed(()=>s.value.slice(0,dL));return(a,l)=>t.users.length>1?(f.openBlock(),f.createElementBlock("div",{key:0,ref_key:"containerRef",ref:r,class:"wov-user-presence"},[f.createElementVNode("button",{class:f.normalizeClass(["wov-user-presence-trigger",{"is-open":n.value}]),onClick:l[0]||(l[0]=c=>n.value=!n.value)},[f.createElementVNode("div",iL,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(i.value,c=>(f.openBlock(),f.createElementBlock("div",{key:c.sessionId,class:"wov-user-avatar",style:f.normalizeStyle({backgroundColor:c.avatar?"transparent":c.color})},[c.avatar?(f.openBlock(),f.createElementBlock("img",{key:0,src:c.avatar,alt:c.name,class:"wov-user-avatar-img"},null,8,aL)):(f.openBlock(),f.createElementBlock(f.Fragment,{key:1},[f.createTextVNode(f.toDisplayString(c.initials),1)],64))],4))),128))])],2),n.value?(f.openBlock(),f.createElementBlock("div",{key:0,class:"wov-user-presence-dropdown",onWheel:l[1]||(l[1]=f.withModifiers(()=>{},["stop"]))},[f.createElementVNode("div",lL,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(s.value,c=>(f.openBlock(),f.createElementBlock("div",{key:c.sessionId,class:"wov-user-presence-item"},[f.createElementVNode("div",{class:"wov-user-avatar wov-user-avatar-small",style:f.normalizeStyle({backgroundColor:c.avatar?"transparent":c.color})},[c.avatar?(f.openBlock(),f.createElementBlock("img",{key:0,src:c.avatar,alt:c.name,class:"wov-user-avatar-img"},null,8,cL)):(f.openBlock(),f.createElementBlock(f.Fragment,{key:1},[f.createTextVNode(f.toDisplayString(c.initials),1)],64))],4),f.createElementVNode("span",uL,f.toDisplayString(c.name),1)]))),128))])],32)):f.createCommentVNode("",!0)],512)):f.createCommentVNode("",!0)}});async function Wf(t,e){const n=await Qf(t,1,{upgrade(r){r.objectStoreNames.contains(e)||r.createObjectStore(e)}});return new fL(n,e)}var fL=class{constructor(t,e){this.db=t,this.storeName=e}async get(t){return this.db.get(this.storeName,t)}async put(t,e){await this.db.put(this.storeName,e,t)}async delete(t){await this.db.delete(this.storeName,t)}async getAllEntries(){const e=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName),n=await e.getAllKeys(),r=await e.getAll(),o=[];for(let s=0;s<n.length;s++)o.push([n[s],r[s]]);return o}async clear(){const t=this.db.transaction(this.storeName,"readwrite");t.objectStore(this.storeName).clear(),await t.done}close(){this.db.close()}},hL=class{constructor(t){this.jobsStore=null,this.binariesStore=null,this.blobUrls=new Map,this.uploading=new Set,this.uploadPromises=new Map,this.provider=t.provider,this.documentId=t.documentId,this.maxRetries=t.provider.maxRetries??3,this.retryDelay=t.provider.retryDelay??5e3}async init(){const t=`wovencanvas-assets-${this.documentId}`,[e,n]=await Promise.all([Wf(`${t}-jobs`,"jobs"),Wf(`${t}-binaries`,"binaries")]);this.jobsStore=e,this.binariesStore=n}async upload(t,e,n){if(!this.jobsStore||!this.binariesStore)throw new Error("AssetManager not initialized");await this.binariesStore.put(t,e);const r={identifier:t,metadata:n,createdAt:Date.now(),retryCount:0};await this.jobsStore.put(t,r);const o=URL.createObjectURL(e);return this.blobUrls.set(t,o),new Promise((s,i)=>{this.uploadPromises.set(t,{resolve:s,reject:i}),this.startUpload(t)})}async getDisplayUrl(t){const e=this.blobUrls.get(t);if(e)return e;try{return await this.provider.resolveUrl(t)}catch(n){return console.error(`Failed to resolve URL for ${t}:`,n),null}}async resumePendingUploads(){if(!this.jobsStore||!this.binariesStore)throw new Error("AssetManager not initialized");const t=await this.jobsStore.getAllEntries();for(const[e]of t){const n=await this.binariesStore.get(e);if(n){const r=URL.createObjectURL(n);this.blobUrls.set(e,r)}this.startUpload(e)}}hasPendingUpload(t){return this.blobUrls.has(t)}isUploading(t){return this.uploading.has(t)}async cancelUpload(t){if(!this.jobsStore||!this.binariesStore)return;const e=this.blobUrls.get(t);e&&(URL.revokeObjectURL(e),this.blobUrls.delete(t)),await this.jobsStore.delete(t),await this.binariesStore.delete(t),this.uploading.delete(t);const n=this.uploadPromises.get(t);n&&(n.reject(new Error("Upload cancelled")),this.uploadPromises.delete(t))}close(){var t,e;for(const n of this.blobUrls.values())URL.revokeObjectURL(n);this.blobUrls.clear(),(t=this.jobsStore)==null||t.close(),(e=this.binariesStore)==null||e.close(),this.jobsStore=null,this.binariesStore=null}async startUpload(t){if(!this.jobsStore||!this.binariesStore||this.uploading.has(t))return;this.uploading.add(t);const e=await this.jobsStore.get(t),n=await this.binariesStore.get(t);if(!e||!n){this.uploading.delete(t);return}try{await this.provider.upload(n,t,e.metadata),await this.onUploadSuccess(t)}catch(r){await this.onUploadError(t,e,r)}}async onUploadSuccess(t){if(!this.jobsStore||!this.binariesStore)return;const e=this.blobUrls.get(t);e&&(URL.revokeObjectURL(e),this.blobUrls.delete(t)),await this.jobsStore.delete(t),await this.binariesStore.delete(t),this.uploading.delete(t);const n=this.uploadPromises.get(t);n&&(n.resolve(),this.uploadPromises.delete(t))}async onUploadError(t,e,n){if(!this.jobsStore)return;const r=n instanceof Error?n.message:"Unknown error";if(console.error(`Upload failed for ${t}:`,r),this.uploading.delete(t),e.retryCount<this.maxRetries){const o={...e,retryCount:e.retryCount+1};await this.jobsStore.put(t,o),setTimeout(()=>{this.startUpload(t)},this.retryDelay*2**e.retryCount)}else{const o=this.uploadPromises.get(t);o&&(o.reject(new Error(r)),this.uploadPromises.delete(t))}}},pL="wovencanvas-assets",mL="blobs",gL=class{constructor(){this.store=null,this.initPromise=null,this.maxRetries=3,this.retryDelay=5e3}async upload(t,e,n){return await(await this.getStore()).put(e,{blob:t,metadata:n}),{}}async resolveUrl(t){const n=await(await this.getStore()).get(t);if(!n)throw new Error(`Asset not found: ${t}`);return URL.createObjectURL(n.blob)}async delete(t){await(await this.getStore()).delete(t)}close(){this.store&&(this.store.close(),this.store=null,this.initPromise=null)}getStore(){return this.store?Promise.resolve(this.store):(this.initPromise||(this.initPromise=Wf(pL,mL).then(t=>(this.store=t,t))),this.initPromise)}},bv=qt({minZoom:Xe().default(.05),maxZoom:Xe().default(2.7)});bv.parse({});var Uf=Gr("panState",{state:E.string().max(16).default("idle"),panStartX:E.float64().default(0),panStartY:E.float64().default(0),velocityX:E.float64().default(0),velocityY:E.float64().default(0),targetX:E.float64().default(0),targetY:E.float64().default(0),expectedLeft:E.float64().default(0),expectedTop:E.float64().default(0)}),Pr=[0,0],mc=[0,0],ta=[0,0],Hf=[0,0],jf=[0,0];function yL(t,e,n,r,o,s){r=Math.max(1e-4,r);const i=2/r,a=i*s,l=1/(1+a+.48*a*a+.235*a*a*a);z.copy(Pr,t),z.sub(Pr,e);const c=o*r,u=c*c,d=z.lengthSq(Pr);d>u&&z.scale(Pr,c/Math.sqrt(d)),z.copy(mc,t),z.sub(mc,Pr),z.set(ta,(n[0]+i*Pr[0])*s,(n[1]+i*Pr[1])*s);const h=[(n[0]-i*ta[0])*l,(n[1]-i*ta[1])*l],p=[mc[0]+(Pr[0]+ta[0])*l,mc[1]+(Pr[1]+ta[1])*l];return z.copy(Hf,e),z.sub(Hf,t),z.copy(jf,p),z.sub(jf,e),z.dot(Hf,jf)>0&&(p[0]=e[0],p[1]=e[1],h[0]=(p[0]-e[0])/s,h[1]=(p[1]-e[1])/s),{position:p,velocity:h}}var Zf=.1,Sv=.1,wL=yr({guards:{hasVelocity:({event:t})=>{if(t.type!=="pointerUp")return!1;const e=t.velocity;return Math.hypot(e[0],e[1])>Sv},isGlideComplete:({context:t})=>Math.hypot(t.velocityX,t.velocityY)<Sv,cameraWasMoved:({context:t,event:e})=>{const n=he.read(e.ctx);return n.left!==t.expectedLeft||n.top!==t.expectedTop},isEscapeKey:({event:t})=>t.key===Xt.Escape},actions:{setDragStart:Oe({panStartX:({event:t})=>t.worldPosition[0],panStartY:({event:t})=>t.worldPosition[1]}),moveCamera:({context:t,event:e})=>{const n=e,{ctx:r}=n,o=n.worldPosition[0]-t.panStartX,s=n.worldPosition[1]-t.panStartY,i=he.write(r);i.left-=o,i.top-=s},startGlide:Oe(({event:t})=>{const e=t,{ctx:n}=e,r=he.read(n),o=e.cameraZoom,s=-e.velocity[0]/o,i=-e.velocity[1]/o;return{velocityX:s,velocityY:i,targetX:r.left+s*Zf,targetY:r.top+i*Zf,expectedLeft:r.left,expectedTop:r.top}}),animateGlide:Oe(({context:t,event:e})=>{const n=e,{ctx:r,delta:o}=n,s=he.read(r),{position:i,velocity:a}=yL([s.left,s.top],[t.targetX,t.targetY],[t.velocityX,t.velocityY],Zf,Number.POSITIVE_INFINITY,o),l=he.write(r);return l.left=i[0],l.top=i[1],{velocityX:a[0],velocityY:a[1],expectedLeft:i[0],expectedTop:i[1]}}),resetContext:Oe({panStartX:0,panStartY:0,velocityX:0,velocityY:0,targetX:0,targetY:0,expectedLeft:0,expectedTop:0})}}).createMachine({id:"pan",initial:"idle",context:{panStartX:0,panStartY:0,velocityX:0,velocityY:0,targetX:0,targetY:0,expectedLeft:0,expectedTop:0},states:{idle:{on:{pointerDown:{actions:"setDragStart",target:"panning"}}},panning:{entry:"moveCamera",on:{pointerMove:{actions:"moveCamera"},pointerUp:[{guard:"hasVelocity",actions:"startGlide",target:"gliding"},{target:"idle"}],keyDown:{guard:"isEscapeKey",target:"idle"}}},gliding:{on:{frame:[{guard:"cameraWasMoved",actions:"resetContext",target:"idle"},{guard:"isGlideComplete",actions:"resetContext",target:"idle"},{actions:"animateGlide"}],pointerDown:{actions:["resetContext","setDragStart"],target:"panning"}}}}}),kL=pe({phase:"input",priority:-100},t=>{const e=Uf.read(t).state,n=Qe.getButtons(t,"hand"),o=[...br(t,n)];e==="gliding"&&o.push(e2(t)),o.push(...t2(t,[Xt.Escape])),o.length!==0&&Uf.run(t,wL,o)}),vL=pe({phase:"input",priority:-100},t=>{const e=_n.read(t);if(!Qe.wheelActive(t,"scroll",e.modDown))return;const r=Wm(t).find(l=>l.type==="wheel");if(!r)return;const o=he.read(t),s=o.left+r.wheelDeltaX/o.zoom,i=o.top+r.wheelDeltaY/o.zoom,a=he.write(t);a.left=s,a.top=i}),bL=pe({phase:"input",priority:-100},t=>{const e=si(t,"controls"),n=_n.read(t);if(!Qe.wheelActive(t,"zoom",n.modDown))return;const o=Wm(t).find(S=>S.type==="wheel");if(!o)return;const s=he.read(t),i=Nt.read(t),a=An.read(t);let l=2**(-.8*o.wheelDeltaY/500)*s.zoom;l=Math.min(e.maxZoom,Math.max(e.minZoom,l));const c=i.width/s.zoom,u=i.height/s.zoom,d=i.width/l,h=i.height/l,p=d-c,m=h-u,g=a.position[0]/i.width,y=a.position[1]/i.height,w=s.left-g*p,k=s.top-y*m,b=he.write(t);b.left=w,b.top=k,b.zoom=l});function SL(t={}){return{name:"controls",resources:bv.parse(t),singletons:[Uf],systems:[bL,vL,kL]}}var EL=(t={})=>SL(t);const CL={class:"wov-selection-box"},xL=f.defineComponent({__name:"SelectionBox",setup(t){return(e,n)=>(f.openBlock(),f.createElementBlock("div",CL))}}),TL={class:"wov-transform-box"},ML=f.defineComponent({__name:"TransformBox",setup(t){return(e,n)=>(f.openBlock(),f.createElementBlock("div",TL))}}),_L={},AL={class:"wov-transform-handle"};function IL(t,e){return f.openBlock(),f.createElementBlock("div",AL)}const BL=Bo(_L,[["render",IL]]),PL=f.defineComponent({__name:"StickyNote",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=pt(e.entityId,gn),r=pt(e.entityId,Ao),o=f.ref(null),s={[st.Top]:"flex-start",[st.Center]:"center",[st.Bottom]:"flex-end"},i=f.computed(()=>{var l;return{backgroundColor:n.value?`rgb(${n.value.red}, ${n.value.green}, ${n.value.blue})`:void 0,minHeight:`${e.block.size[0]}px`,alignItems:s[((l=r.value)==null?void 0:l.value)??st.Top]}}),{handleEditEnd:a}=xf({blockData:e,containerRef:o,minWidth:()=>e.block.size[0],minHeight:()=>e.block.size[0]});return(l,c)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"containerRef",ref:o,class:"wov-sticky-note",style:f.normalizeStyle(i.value)},[f.createVNode(tc,f.mergeProps(e,{"block-element":o.value,"measure-element":o.value,onEditEnd:f.unref(a)}),null,16,["block-element","measure-element","onEditEnd"])],4))}}),gc=qm({name:"blockPlacementState"},{editedCheckpoint:E.string().default("").max(36)}),Ev=ne(t=>t.with(wr));function NL(t){var e;if(!t)return null;try{const n=JSON.parse(t);return(e=n.block)!=null&&e.tag?n:(console.warn("Block snapshot missing required tag:",n),null)}catch{return console.warn("Invalid block snapshot JSON:",t),null}}function DL(t,e,n){const r=Ft(t,e.block.tag);if(!r)throw new Error(`Block placement: block definition for tag "${e.block.tag}" not found`);const o=e.block.size??[100,100],s=n[0]-o[0]/2,i=n[1]-o[1]/2,a=e.block.rank??In.genNext(t),l=vt(t);"synced"in e||G(t,l,de,{id:crypto.randomUUID()});const c=Object.assign({},e.block,{position:[s,i],size:o,rank:a});G(t,l,_,c);for(const d of r.components)if(!(d.name in e))G(t,l,d);else{const h=e[d.name];G(t,l,d,h)}const{sessionId:u}=Le(t);return G(t,l,xt,{sessionId:u}),l}function Cv(t,e,n,r,o){const s=DL(t,e,n),i=_.read(t,s);if(Im(t,e.block.tag)&&(G(t,s,gi,{}),o==="placement")){const{store:u}=si(t,"editing"),d=u.createCheckpoint();if(d){const h=gc.write(t);h.editedCheckpoint=d}}const a=Nn.write(t);a.state=o==="dragOut"?me.Dragging:me.Pointing,a.dragStart=n,a.draggedEntity=s,a.draggedEntityStart=i.position,a.pointingStartClient=r,a.pointingStartWorld=n,a.isCloning=!1;const l=Qe.write(t);l.leftMouseTool="select",l.heldSnapshot="";const c=kn.write(t);c.cursorKind="select",c.rotation=0}function OL(t){const e=gc.read(t);if(e.editedCheckpoint){const n=e.editedCheckpoint;gc.write(t).editedCheckpoint="";const{store:r}=si(t,"editing");r.onSettled(()=>r.squashToCheckpoint(n),{frames:5})}}const RL=pe({phase:"capture"},t=>{Ev.removed(t).length>0&&Ev.current(t).length===0&&OL(t);const e=Qe.read(t);if(!e.heldSnapshot)return;const n=br(t,[ln.Left]);if(n.length===0)return;const r=NL(e.heldSnapshot);if(!r)return;if(e.leftMouseTool==="drag-out"){const s=n.find(i=>i.type==="pointerMove"&&!i.obscured);if(!s)return;Cv(t,r,s.worldPosition,s.screenPosition,"dragOut")}else{const s=n.find(i=>i.type==="pointerDown"&&!i.obscured);if(!s)return;Cv(t,r,s.worldPosition,s.screenPosition,"placement")}}),zL=pe({phase:"update"},t=>{const{store:e}=si(t,"editing");ie(t,_m,()=>{e.canUndo()&&(wg(t),e.undo())}),ie(t,xu,()=>{e.canRedo()&&(wg(t),e.redo())})}),$L=[{name:"Figtree",displayName:"Figtree",url:"https://fonts.googleapis.com/css2?family=Figtree",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/Figtree.png"},{name:"Shantell Sans",displayName:"Shantell Sans",url:"https://fonts.googleapis.com/css2?family=Shantell+Sans",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/ShantellSans.png"},{name:"Courier Prime",displayName:"Courier Prime",url:"https://fonts.googleapis.com/css2?family=Courier+Prime",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/CourierPrime.png"},{name:"EB Garamond",displayName:"EB Garamond",url:"https://fonts.googleapis.com/css2?family=EB+Garamond",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/EBGaramond.png"}];function xv(t){return{name:"editing",resources:{store:t.store},singletons:[gc],systems:[RL,zL],cursors:lv,fonts:$L,keybinds:[{command:_m.name,key:Xt.Z,mod:!0},{command:xu.name,key:Xt.Y,mod:!0},{command:xu.name,key:Xt.Z,mod:!0,shift:!0}]}}const LL={class:"wov-user-cursors"},FL={class:"wov-cursor-svg",viewBox:"0 0 4.35 4.75",width:"20",height:"20"},VL=["fill"],WL="M2.39,2.88s-.04.01-.05.02c-.01,0-.02.01-.03.02,0,.01-.02.02-.03.05l-.77,1.44c-.07.13-.1.19-.14.2-.03.01-.07,0-.1-.01-.03-.02-.05-.09-.09-.23L.16.41c-.03-.13-.05-.19-.03-.23.02-.03.04-.05.08-.06.04,0,.1.02.21.08l3.59,1.94c.13.07.19.1.2.14.01.03,0,.07-.01.1-.02.03-.09.05-.23.09l-1.58.4Z",UL=f.defineComponent({__name:"UserCursors",props:{users:{},currentSessionId:{},camera:{}},setup(t){const e=t,n=f.computed(()=>e.users.filter(r=>r.sessionId!==e.currentSessionId).map(r=>({...r,screenX:(r.position[0]-e.camera.left)*e.camera.zoom,screenY:(r.position[1]-e.camera.top)*e.camera.zoom})));return(r,o)=>(f.openBlock(),f.createElementBlock("div",LL,[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(n.value,s=>(f.openBlock(),f.createElementBlock("div",{key:s.sessionId,class:"wov-user-cursor",style:f.normalizeStyle({transform:`translate(${s.screenX}px, ${s.screenY}px)`})},[(f.openBlock(),f.createElementBlock("svg",FL,[f.createElementVNode("path",{fill:s.color,stroke:"#fff","stroke-miterlimit":"10","stroke-width":".25",d:WL},null,8,VL)])),f.createElementVNode("span",{class:"wov-cursor-label",style:f.normalizeStyle({backgroundColor:s.color})},f.toDisplayString(s.name),5)],4))),128))]))}}),HL={key:0,class:"wov-offline-indicator"},jL=f.defineComponent({__name:"OfflineIndicator",props:{isOnline:{type:Boolean}},setup(t){return(e,n)=>t.isOnline?f.createCommentVNode("",!0):(f.openBlock(),f.createElementBlock("div",HL,"Working Offline"))}}),ZL={key:0,class:"wov-version-mismatch-overlay"},KL=f.defineComponent({__name:"VersionMismatch",props:{versionMismatch:{type:Boolean}},setup(t){function e(){window.location.reload()}return(n,r)=>t.versionMismatch?(f.openBlock(),f.createElementBlock("div",ZL,[f.createElementVNode("div",{class:"wov-version-mismatch-dialog"},[r[0]||(r[0]=f.createElementVNode("p",null,"A new version is available.",-1)),r[1]||(r[1]=f.createElementVNode("p",null,"Please refresh the page to continue.",-1)),f.createElementVNode("button",{onClick:e},"Refresh")])])):f.createCommentVNode("",!0)}}),YL=f.defineComponent({__name:"BackToContentButton",setup(t){const{nextEditorTick:e}=Tt(),n=zt(he),r=ne(l=>l.with(de,_,Ae)),o=f.ref(0),s=f.inject(Rn);if(s){const l=s.registerTickCallback(c=>{r.addedOrRemoved(c).length>0&&(o.value=r.current(c).length)});f.onUnmounted(l)}const i=f.ref(!1);f.watchEffect(()=>{i.value=!n.value.canSeeBlocks&&o.value>0});function a(){e(l=>{const c=r.current(l);if(c.length===0)return;let u=Number.POSITIVE_INFINITY,d=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(const x of c){const T=Ae.read(l,x);u=Math.min(u,T.value[0]),d=Math.min(d,T.value[1]),h=Math.max(h,T.value[2]),p=Math.max(p,T.value[3])}const m=Nt.read(l),g=he.read(l);let y=Math.min(m.width/(h-u),m.height/(p-d));y/=1.1,y=Math.min(y,g.zoom);const w=(u+h)/2,k=(d+p)/2,b=w-m.width/y/2,S=k-m.height/y/2,v=he.write(l);v.left=b,v.top=S,v.zoom=y})}return(l,c)=>i.value?(f.openBlock(),f.createElementBlock("button",{key:0,class:"wov-back-to-content",onClick:a},[...c[0]||(c[0]=[f.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},[f.createElementVNode("path",{d:"M10 12L6 8L10 4",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})],-1),f.createTextVNode(" Back to content ",-1)])])):f.createCommentVNode("",!0)}}),qL=["data-entity-id","data-selected","data-held-by-other","data-hovered"],JL=f.defineComponent({__name:"WovenCanvas",props:{store:{},editor:{},background:{},assetProvider:{},pluginOptions:{},controls:{}},emits:["ready"],setup(t,{emit:e}){var Zn;const n=ne(B=>B.tracking(_)),r=ne(B=>B.with(_).tracking(Re)),o=ne(B=>B.with(_).tracking(ht)),s=ne(B=>B.with(_).tracking(xt)),i=ne(B=>B.with(_).tracking(Yr)),a=ne(B=>B.with(_).tracking(wr)),l=ne(B=>B.with(_).tracking(Ge)),c=ne(B=>B.tracking(vr)),u=t,d=e,h=f.ref(null),p=f.shallowRef(null),m=Em.parse(((Zn=u.editor)==null?void 0:Zn.user)??{}),g=new Set,y=new Map,w=f.shallowRef([]),k=new Map,b=new Map,S=new Set,v=new Map,x=f.shallowRef([]),T=f.ref(!0),A=f.ref(!1),P=f.ref(!0),$=f.shallowRef(he.default());function V(B,ae,W){let oe=k.get(B);oe||(oe=new Map,k.set(B,oe));let X=oe.get(ae);return X||(X=new Set,oe.set(ae,X)),X.add(W),()=>{X.delete(W),X.size===0&&(oe.delete(ae),oe.size===0&&k.delete(B))}}function U(B,ae,W,oe=!1){const X=k.get(ae);if(!X)return;const F=X.get(W.name);if(!F||F.size===0)return;let nt=null;oe||(nt=W.snapshot(B,ae));for(const Kn of F)Kn(nt)}function M(B,ae){let W=b.get(B);return W||(W=new Set,b.set(B,W)),W.add(ae),()=>{W.delete(ae),W.size===0&&b.delete(B)}}function L(B,ae){const W=b.get(ae.name);if(!W||W.size===0)return;const oe=ae.snapshot(B);for(const X of W)X(oe)}function q(B){return S.add(B),()=>{S.delete(B)}}function se(){return m.sessionId}function Z(B){return y.get(B)??null}const H={hasEntity:B=>g.has(B),getEditor:()=>p.value,getAssetManager:()=>tt,getSessionId:se,getUserBySessionId:Z,subscribeComponent:V,subscribeSingleton:M,registerTickCallback:q};f.provide(Rn,H),f.provide("containerRef",h);const J=gk();f.provide(ny,J);let ce=0,Ke=null,Be=null,tt=null;async function ko(){!p.value||!Be||(p.value.nextTick(B=>{yc(B),na(B);for(const ae of S)ae(B);Be&&Be.sync(B)}),await p.value.tick(),Ke=requestAnimationFrame(ko))}f.onMounted(async()=>{var Kn,tn;if(!h.value)return;const B=u.store??{},ae={...B};B.websocket&&(ae.websocket={...B.websocket,onVersionMismatch:kc=>{var Or,oa;A.value=!0,(oa=(Or=B.websocket)==null?void 0:Or.onVersionMismatch)==null||oa.call(Or,kc)},onConnectivityChange:kc=>{var Or,oa;T.value=kc,(oa=(Or=B.websocket)==null?void 0:Or.onConnectivityChange)==null||oa.call(Or,kc)}}),Be=new Jm(ae);const W=[],oe=u.pluginOptions;(oe==null?void 0:oe.controls)!==!1&&W.push(EL((oe==null?void 0:oe.controls)??{})),(oe==null?void 0:oe.selection)!==!1&&W.push(mI((oe==null?void 0:oe.selection)||void 0)),(oe==null?void 0:oe.eraser)!==!1&&W.push(qB((oe==null?void 0:oe.eraser)||void 0)),(oe==null?void 0:oe.pen)!==!1&&W.push(BP()),(oe==null?void 0:oe.arrows)!==!1&&W.push(cB((oe==null?void 0:oe.arrows)||void 0)),W.push(xv({store:Be})),(Kn=u.editor)!=null&&Kn.plugins&&W.push(...u.editor.plugins);const X={...u.editor,user:m,plugins:W,controls:u.controls},F=new XA(h.value,X);await F.initialize(),await Be.initialize({components:F.components,singletons:F.singletons});const nt=((tn=B.persistence)==null?void 0:tn.documentId)??"default";tt=new hL({provider:u.assetProvider??new gL,documentId:nt}),await tt.init(),await tt.resumePendingUploads(),p.value=F,Ke=requestAnimationFrame(ko),P.value=!1,d("ready",F,Be)}),f.onUnmounted(()=>{var B;Ke!==null&&cancelAnimationFrame(Ke),tt==null||tt.close(),Be==null||Be.close(),(B=p.value)==null||B.dispose()});function yc(B){const{events:ae,newIndex:W}=B.eventBuffer.readEvents(ce);if(ce=W,ae.length===0)return;const{componentsById:oe,singletonsById:X}=Le(B);for(const{entityId:F,eventType:nt,componentId:Kn}of ae){if(F===ls){if(nt===_e.CHANGED){const tn=X.get(Kn);tn&&L(B,tn)}continue}if(nt===_e.ADDED)g.add(F);else if(nt===_e.REMOVED)g.delete(F),k.delete(F);else if(nt===_e.COMPONENT_ADDED){g.add(F);const tn=oe.get(Kn);tn&&U(B,F,tn)}else if(nt===_e.COMPONENT_REMOVED){const tn=oe.get(Kn);tn&&U(B,F,tn,!0)}else if(nt===_e.CHANGED){const tn=oe.get(Kn);tn&&U(B,F,tn)}}}function na(B){var oe;let ae=!1;for(const X of n.added(B)){const F=_.snapshot(B,X),nt=(oe=p.value)==null?void 0:oe.blockDefs[F.tag],Kn=(nt==null?void 0:nt.stratum)??"content";v.set(X,f.ref({entityId:X,block:F,stratum:Kn,selected:!1,held:null,hovered:!1,edited:!1,opacity:null,connector:null})),ae=!0}for(const X of n.removed(B))v.delete(X),ae=!0;for(const X of n.changed(B)){const F=v.get(X);if(F){const nt=_.snapshot(B,X);F.value.block.rank!==nt.rank&&(ae=!0),F.value.block=nt}}let W=!1;for(const X of c.addedOrChanged(B)){const F=vr.snapshot(B,X);y.set(F.sessionId,F),W=!0}for(const X of c.removed(B)){const F=vr.read(B,X);y.delete(F.sessionId),W=!0}W&&(w.value=Array.from(y.values()));for(const X of o.added(B)){const F=v.get(X);F&&!F.value.selected&&(F.value.selected=!0)}for(const X of o.removed(B)){const F=v.get(X);F&&F.value.selected&&(F.value.selected=!1)}for(const X of s.addedOrChanged(B)){const F=v.get(X);F&&(F.value.held=xt.snapshot(B,X))}for(const X of s.removed(B)){const F=v.get(X);F&&F.value.held!==null&&(F.value.held=null)}for(const X of i.added(B)){const F=v.get(X);F&&!F.value.hovered&&(F.value.hovered=!0)}for(const X of i.removed(B)){const F=v.get(X);F&&F.value.hovered&&(F.value.hovered=!1)}for(const X of a.added(B)){const F=v.get(X);F&&!F.value.edited&&(F.value.edited=!0)}for(const X of a.removed(B)){const F=v.get(X);F&&F.value.edited&&(F.value.edited=!1)}for(const X of l.addedOrChanged(B)){const F=v.get(X);F&&(F.value.opacity=Ge.snapshot(B,X))}for(const X of l.removed(B)){const F=v.get(X);F&&F.value.opacity!==null&&(F.value.opacity=null)}for(const X of r.addedOrChanged(B)){const F=v.get(X);F&&(F.value.connector=Re.snapshot(B,X))}for(const X of r.removed(B)){const F=v.get(X);F&&F.value.connector!==null&&(F.value.connector=null)}if(ae){const X=Array.from(v.values());X.sort((F,nt)=>F.value.block.rank>nt.value.block.rank?1:-1),x.value=X}}M(he.name,B=>{B&&($.value=B)});function Kf(B){const ae=B.rotateZ!==0,W=B.flip[0],oe=B.flip[1];if(!ae&&!W&&!oe)return;const X=[];return ae&&X.push(`rotate(${B.rotateZ}rad)`),W&&X.push("scaleX(-1)"),oe&&X.push("scaleY(-1)"),X.join(" ")}function ra(B){const{held:ae}=B;if(!ae||!ae.sessionId||ae.sessionId===m.sessionId)return null;const W=Z(ae.sessionId);return(W==null?void 0:W.color)??null}function wc(B){const{block:ae,stratum:W,opacity:oe}=B,X=ra(B),F=oe!==null?oe.value/255:1;return{position:"absolute",left:`${ae.position[0]}px`,top:`${ae.position[1]}px`,width:`${ae.size[0]}px`,height:`${ae.size[1]}px`,zIndex:ku[W]*1e3,transform:Kf(ae),opacity:F,pointerEvents:"none",userSelect:"none","--wov-held-by-color":X??void 0,transition:F===1?"opacity 0ms 32ms":void 0}}return(B,ae)=>(f.openBlock(),f.createElementBlock("div",{ref_key:"containerRef",ref:h,class:"wov-root",style:{position:"relative",width:"100%",height:"100%",overflow:"hidden"}},[t.background?f.renderSlot(B.$slots,"background",{key:0,background:t.background},()=>[f.createVNode(rv,{background:t.background},null,8,["background"])]):f.createCommentVNode("",!0),f.createElementVNode("div",{class:"wov-canvas",style:f.normalizeStyle({position:"absolute",transformOrigin:"0 0",transform:`scale(${$.value.zoom}) translate(${-$.value.left}px, ${-$.value.top}px)`,"--wov-zoom":$.value.zoom})},[(f.openBlock(!0),f.createElementBlock(f.Fragment,null,f.renderList(x.value,W=>(f.openBlock(),f.createElementBlock("div",{key:W.value.entityId,"data-entity-id":W.value.entityId,style:f.normalizeStyle(wc(W.value)),"data-selected":W.value.selected||void 0,"data-held-by-other":ra(W.value)!==null||void 0,"data-hovered":W.value.hovered||void 0,class:"wov-block"},[f.renderSlot(B.$slots,`block:${W.value.block.tag}`,f.mergeProps({ref_for:!0},W.value),()=>[W.value.block.tag==="selection-box"?(f.openBlock(),f.createBlock(xL,f.mergeProps({key:0,ref_for:!0},W.value),null,16)):W.value.block.tag==="transform-box"?(f.openBlock(),f.createBlock(ML,f.mergeProps({key:1,ref_for:!0},W.value),null,16)):W.value.block.tag==="transform-handle"?(f.openBlock(),f.createBlock(BL,f.mergeProps({key:2,ref_for:!0},W.value),null,16)):W.value.block.tag==="arrow-handle"?(f.openBlock(),f.createBlock(oy,f.mergeProps({key:3,ref_for:!0},W.value),null,16)):W.value.block.tag==="arrow-terminal"?(f.openBlock(),f.createBlock(sy,f.mergeProps({key:4,ref_for:!0},W.value),null,16)):W.value.block.tag==="sticky-note"?(f.openBlock(),f.createBlock(PL,f.mergeProps({key:5,ref_for:!0},W.value),null,16)):W.value.block.tag==="eraser"?(f.openBlock(),f.createBlock(vy,f.mergeProps({key:6,ref_for:!0},W.value),null,16)):W.value.block.tag==="pen-stroke"?(f.openBlock(),f.createBlock(Py,f.mergeProps({key:7,ref_for:!0},W.value),null,16)):W.value.block.tag==="arc-arrow"?(f.openBlock(),f.createBlock(ry,f.mergeProps({key:8,ref_for:!0},W.value),null,16)):W.value.block.tag==="elbow-arrow"?(f.openBlock(),f.createBlock(iy,f.mergeProps({key:9,ref_for:!0},W.value),null,16)):W.value.block.tag==="text"?(f.openBlock(),f.createBlock(wk,f.mergeProps({key:10,ref_for:!0},W.value),null,16)):W.value.block.tag==="image"?(f.openBlock(),f.createBlock(by,f.mergeProps({key:11,ref_for:!0},W.value),null,16)):W.value.block.tag==="shape"?(f.openBlock(),f.createBlock(yk,f.mergeProps({key:12,ref_for:!0},W.value),null,16)):f.createCommentVNode("",!0)])],12,qL))),128))],4),p.value?f.renderSlot(B.$slots,"user-cursors",{key:1,users:w.value,currentSessionId:f.unref(m).sessionId,camera:$.value},()=>[f.createVNode(UL,{users:w.value,"current-session-id":f.unref(m).sessionId,camera:$.value},null,8,["users","current-session-id","camera"])]):f.createCommentVNode("",!0),p.value?(f.openBlock(),f.createBlock(iv,{key:2},{default:f.withCtx(W=>[f.renderSlot(B.$slots,"floating-menu",f.normalizeProps(f.guardReactiveProps(W)))]),_:3})):f.createCommentVNode("",!0),p.value?f.renderSlot(B.$slots,"user-presence",{key:3,users:w.value},()=>[f.createVNode(vv,{users:w.value},null,8,["users"])]):f.createCommentVNode("",!0),p.value?f.renderSlot(B.$slots,"toolbar",{key:4},()=>[f.createVNode(wv)]):f.createCommentVNode("",!0),p.value?f.renderSlot(B.$slots,"default",{key:5}):f.createCommentVNode("",!0),f.renderSlot(B.$slots,"offline-indicator",{isOnline:T.value},()=>[f.createVNode(jL,{"is-online":T.value},null,8,["is-online"])]),f.renderSlot(B.$slots,"version-mismatch",{versionMismatch:A.value},()=>[f.createVNode(KL,{"version-mismatch":A.value},null,8,["version-mismatch"])]),f.renderSlot(B.$slots,"back-to-content",{},()=>[f.createVNode(YL)]),f.renderSlot(B.$slots,"loading",{isLoading:P.value},()=>[f.createVNode(av,{"is-loading":P.value},null,8,["is-loading"])])],512))}});R.ARROW_HEADS=Qu,R.ArcArrow=ry,R.ArcArrowTool=eL,R.ArrowHandle=oy,R.ArrowHead=Sr,R.ArrowHeadButton=$f,R.ArrowTerminal=sy,R.ArrowThicknessButton=Vk,R.CURSORS=lv,R.CanvasBackground=rv,R.CanvasComponentDef=Km,R.CanvasSingletonDef=Ym,R.CanvasStore=Jm,R.ColorButton=Hk,R.ColorPicker=Uk,R.CursorKind=ts,R.EditableText=tc,R.EditingPlugin=xv,R.ElbowArrow=iy,R.ElbowArrowTool=gv,R.Eraser=vy,R.EraserTool=hv,R.FloatingMenu=iv,R.FloatingMenuBar=sv,R.HandTool=uv,R.IconChevronDown=jn,R.ImageBlock=by,R.ImageTool=yv,R.LoadingOverlay=av,R.MenuButton=qs,R.MenuDropdown=Hn,R.MenuTooltip=Lf,R.PenStroke=Py,R.PenStrokeThicknessButton=jk,R.PenTool=pv,R.SHAPES=Ti,R.SelectTool=cv,R.Shape=yn,R.ShapeBlock=yk,R.ShapeFillColorButton=Zk,R.ShapeKindButton=Kk,R.ShapeStrokeColorButton=Yk,R.ShapeTool=fv,R.StickyNoteTool=dv,R.StrokeKind=dt,R.Synced=hi,R.TextAlignment=wn,R.TextAlignmentButton=qk,R.TextBlock=wk,R.TextBoldButton=Jk,R.TextColorButton=Xk,R.TextFontFamilyButton=Qk,R.TextFontSizeButton=ev,R.TextItalicButton=tv,R.TextTool=mv,R.TextUnderlineButton=nv,R.Toolbar=wv,R.ToolbarButton=lr,R.User=vr,R.UserPresence=vv,R.WovenCanvas=JL,R.computeCommonComponents=ov,R.createTooltipContext=gk,R.defineCanvasComponent=f2,R.defineCanvasSingleton=qm,R.getArrowHead=Is,R.useComponent=pt,R.useComponents=po,R.useEditorContext=Tt,R.useFonts=Gk,R.useQuery=lk,R.useSingleton=zt,R.useTextBatchController=mk,R.useTextEditorController=Ji,R.useTextFormatting=Br,R.useTextStretchBehavior=xf,R.useToolbar=Tf,R.useTooltipSingleton=go,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})});
170
+ `):""}),nk=JR,QR=Cf.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Qs(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];return n.length===1&&n[0].type==="image"?e.parseChildren([n[0]]):e.createNode("paragraph",void 0,e.parseInline(n))},renderMarkdown:(t,e)=>!t||!Array.isArray(t.content)?"":e.renderChildren(t.content),addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),rk=QR,ez=Cf.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),ok=ez,sk=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...r}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},tz=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,nz=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,rz=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,oz=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,sz=na.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return sk("strong",{...Qs(this.options.HTMLAttributes,t),children:sk("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[rc({find:tz,type:this.type}),rc({find:rz,type:this.type})]},addPasteRules(){return[oc({find:nz,type:this.type}),oc({find:oz,type:this.type})]}}),ik=sz,iz=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,az=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,lz=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,cz=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,uz=na.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",Qs(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[rc({find:iz,type:this.type}),rc({find:lz,type:this.type})]},addPasteRules(){return[oc({find:az,type:this.type}),oc({find:cz,type:this.type})]}}),ak=uz,dz=na.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",Qs(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown(t,e){return`++${e.renderChildren(t)}++`},markdownTokenizer:{name:"underline",level:"inline",start(t){return t.indexOf("++")},tokenize(t,e,n){const o=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!o)return;const s=o[2].trim();return{type:"underline",raw:o[0],text:s,tokens:n.inlineTokens(s)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),lk=dz,fz=Le.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>this.options.alignments.includes(t)?this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(n=>n):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(e=>e),toggleTextAlign:t=>({editor:e,commands:n})=>this.options.alignments.includes(t)?e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),ck=fz,hz=20,uk=(t,e=0)=>{const n=[];return!t.children.length||e>hz||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...uk(r,e+1))}),n},pz=t=>{if(!t.children.length)return;const e=uk(t);e&&e.forEach(n=>{var r,o;const s=n.getAttribute("style"),i=(o=(r=n.parentElement)==null?void 0:r.closest("span"))==null?void 0:o.getAttribute("style");n.setAttribute("style",`${i};${s}`)})},xf=na.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&pz(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Qs(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(o=>o.type===this.type).some(o=>Object.values(o.attrs).some(s=>!!s))||t.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),mz=Le.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(o=>o.trim()).filter(Boolean);for(let o=r.length-1;o>=0;o-=1){const s=r[o].split(":");if(s.length>=2){const i=s[0].trim().toLowerCase(),a=s.slice(1).join(":").trim();if(i==="background-color")return a.replace(/['"]+/g,"")}}}return(e=t.style.backgroundColor)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),dk=Le.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=t.getAttribute("style");if(n){const r=n.split(";").map(o=>o.trim()).filter(Boolean);for(let o=r.length-1;o>=0;o-=1){const s=r[o].split(":");if(s.length>=2){const i=s[0].trim().toLowerCase(),a=s.slice(1).join(":").trim();if(i==="color")return a.replace(/['"]+/g,"")}}}return(e=t.style.color)==null?void 0:e.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),gz=Le.create({name:"fontFamily",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>t.style.fontFamily,renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands(){return{setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()}}}),yz=Le.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>t.style.fontSize,renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),wz=Le.create({name:"lineHeight",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>t.style.lineHeight,renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands(){return{setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()}}});Le.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(mz.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(dk.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(gz.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(yz.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(wz.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(xf.configure(this.options.textStyle)),t}});var fk=dk;function kz(t={}){return new ct({view(e){return new vz(e,t)}})}class vz{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(o=>{let s=i=>{this[o](i)};return e.dom.addEventListener(o,s),{name:o,handler:s}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,o=this.editorView.dom,s=o.getBoundingClientRect(),i=s.width/o.offsetWidth,a=s.height/o.offsetHeight;if(n){let f=e.nodeBefore,h=e.nodeAfter;if(f||h){let p=this.editorView.nodeDOM(this.cursorPos-(f?f.nodeSize:0));if(p){let m=p.getBoundingClientRect(),g=f?m.bottom:m.top;f&&h&&(g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*a;r={left:m.left,right:m.right,top:g-y,bottom:g+y}}}}if(!r){let f=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*i;r={left:f.left-h,right:f.left+h,top:f.top,bottom:f.bottom}}let l=this.editorView.dom.offsetParent;this.element||(this.element=l.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,u;if(!l||l==document.body&&getComputedStyle(l).position=="static")c=-pageXOffset,u=-pageYOffset;else{let f=l.getBoundingClientRect(),h=f.width/l.offsetWidth,p=f.height/l.offsetHeight;c=f.left-l.scrollLeft*h,u=f.top-l.scrollTop*p}this.element.style.left=(r.left-c)/i+"px",this.element.style.top=(r.top-u)/a+"px",this.element.style.width=(r.right-r.left)/i+"px",this.element.style.height=(r.bottom-r.top)/a+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),o=r&&r.type.spec.disableDropCursor,s=typeof o=="function"?o(this.editorView,n,e):o;if(n&&!s){let i=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let a=B0(this.editorView.state.doc,i,this.editorView.dragging.slice);a!=null&&(i=a)}this.setCursor(i),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class Ye extends fe{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return Ye.valid(r)?new Ye(r):fe.near(r)}content(){return Z.empty}eq(e){return e instanceof Ye&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Ye(e.resolve(n.pos))}getBookmark(){return new Tf(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!bz(e)||!Sz(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let o=n.contentMatchAt(e.index()).defaultType;return o&&o.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&Ye.valid(e))return e;let o=e.pos,s=null;for(let i=e.depth;;i--){let a=e.node(i);if(n>0?e.indexAfter(i)<a.childCount:e.index(i)>0){s=a.child(n>0?e.indexAfter(i):e.index(i)-1);break}else if(i==0)return null;o+=n;let l=e.doc.resolve(o);if(Ye.valid(l))return l}for(;;){let i=n>0?s.firstChild:s.lastChild;if(!i){if(s.isAtom&&!s.isText&&!oe.isSelectable(s)){e=e.doc.resolve(o+s.nodeSize*n),r=!1;continue e}break}s=i,o+=n;let a=e.doc.resolve(o);if(Ye.valid(a))return a}return null}}}Ye.prototype.visible=!1,Ye.findFrom=Ye.findGapCursorFrom,fe.jsonID("gapcursor",Ye);class Tf{constructor(e){this.pos=e}map(e){return new Tf(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return Ye.valid(n)?new Ye(n):fe.near(n)}}function hk(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function bz(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n-1);;o=o.lastChild){if(o.childCount==0&&!o.inlineContent||hk(o.type))return!0;if(o.inlineContent)return!1}}return!0}function Sz(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n);;o=o.firstChild){if(o.childCount==0&&!o.inlineContent||hk(o.type))return!0;if(o.inlineContent)return!1}}return!0}function Ez(){return new ct({props:{decorations:Mz,createSelectionBetween(t,e,n){return e.pos==n.pos&&Ye.valid(n)?new Ye(n):null},handleClick:xz,handleKeyDown:Cz,handleDOMEvents:{beforeinput:Tz}}})}const Cz=w1({ArrowLeft:sc("horiz",-1),ArrowRight:sc("horiz",1),ArrowUp:sc("vert",-1),ArrowDown:sc("vert",1)});function sc(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,o,s){let i=r.selection,a=e>0?i.$to:i.$from,l=i.empty;if(i instanceof ce){if(!s.endOfTextblock(n)||a.depth==0)return!1;l=!1,a=r.doc.resolve(e>0?a.after():a.before())}let c=Ye.findGapCursorFrom(a,e,l);return c?(o&&o(r.tr.setSelection(new Ye(c))),!0):!1}}function xz(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!Ye.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&oe.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new Ye(r))),!0)}function Tz(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof Ye))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=D.empty;for(let i=r.length-1;i>=0;i--)o=D.from(r[i].createAndFill(null,o));let s=t.state.tr.replace(n.pos,n.pos,new Z(o,0,0));return s.setSelection(ce.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function Mz(t){if(!(t.selection instanceof Ye))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",je.create(t.doc,[jt.widget(t.selection.head,e,{key:"gapcursor"})])}var ic=200,vt=function(){};vt.prototype.append=function(e){return e.length?(e=vt.from(e),!this.length&&e||e.length<ic&&this.leafAppend(e)||this.length<ic&&e.leafPrepend(this)||this.appendInner(e)):this},vt.prototype.prepend=function(e){return e.length?vt.from(e).append(this):this},vt.prototype.appendInner=function(e){return new Az(this,e)},vt.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?vt.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))},vt.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},vt.prototype.forEach=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(e,n,r,0):this.forEachInvertedInner(e,n,r,0)},vt.prototype.map=function(e,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var o=[];return this.forEach(function(s,i){return o.push(e(s,i))},n,r),o},vt.from=function(e){return e instanceof vt?e:e&&e.length?new pk(e):vt.empty};var pk=function(t){function e(r){t.call(this),this.values=r}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(o,s){return o==0&&s==this.length?this:new e(this.values.slice(o,s))},e.prototype.getInner=function(o){return this.values[o]},e.prototype.forEachInner=function(o,s,i,a){for(var l=s;l<i;l++)if(o(this.values[l],a+l)===!1)return!1},e.prototype.forEachInvertedInner=function(o,s,i,a){for(var l=s-1;l>=i;l--)if(o(this.values[l],a+l)===!1)return!1},e.prototype.leafAppend=function(o){if(this.length+o.length<=ic)return new e(this.values.concat(o.flatten()))},e.prototype.leafPrepend=function(o){if(this.length+o.length<=ic)return new e(o.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e}(vt);vt.empty=new pk([]);var Az=function(t){function e(n,r){t.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,o,s,i){var a=this.left.length;if(o<a&&this.left.forEachInner(r,o,Math.min(s,a),i)===!1||s>a&&this.right.forEachInner(r,Math.max(o-a,0),Math.min(this.length,s)-a,i+a)===!1)return!1},e.prototype.forEachInvertedInner=function(r,o,s,i){var a=this.left.length;if(o>a&&this.right.forEachInvertedInner(r,o-a,Math.max(s,a)-a,i+a)===!1||s<a&&this.left.forEachInvertedInner(r,Math.min(o,a),s,i)===!1)return!1},e.prototype.sliceInner=function(r,o){if(r==0&&o==this.length)return this;var s=this.left.length;return o<=s?this.left.slice(r,o):r>=s?this.right.slice(r-s,o-s):this.left.slice(r,s).append(this.right.slice(0,o-s))},e.prototype.leafAppend=function(r){var o=this.right.leafAppend(r);if(o)return new e(this.left,o)},e.prototype.leafPrepend=function(r){var o=this.left.leafPrepend(r);if(o)return new e(o,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e}(vt);const _z=500;class Hn{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let o,s;n&&(o=this.remapping(r,this.items.length),s=o.maps.length);let i=e.tr,a,l,c=[],u=[];return this.items.forEach((f,h)=>{if(!f.step){o||(o=this.remapping(r,h+1),s=o.maps.length),s--,u.push(f);return}if(o){u.push(new ir(f.map));let p=f.step.map(o.slice(s)),m;p&&i.maybeStep(p).doc&&(m=i.mapping.maps[i.mapping.maps.length-1],c.push(new ir(m,void 0,void 0,c.length+u.length))),s--,m&&o.appendMap(m,s)}else i.maybeStep(f.step);if(f.selection)return a=o?f.selection.map(o.slice(s)):f.selection,l=new Hn(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:l,transform:i,selection:a}}addTransform(e,n,r,o){let s=[],i=this.eventCount,a=this.items,l=!o&&a.length?a.get(a.length-1):null;for(let u=0;u<e.steps.length;u++){let f=e.steps[u].invert(e.docs[u]),h=new ir(e.mapping.maps[u],f,n),p;(p=l&&l.merge(h))&&(h=p,u?s.pop():a=a.slice(0,a.length-1)),s.push(h),n&&(i++,n=void 0),o||(l=h)}let c=i-r.depth;return c>Bz&&(a=Iz(a,c),i-=c),new Hn(a.append(s),i)}remapping(e,n){let r=new Li;return this.items.forEach((o,s)=>{let i=o.mirrorOffset!=null&&s-o.mirrorOffset>=e?r.maps.length-o.mirrorOffset:void 0;r.appendMap(o.map,i)},e,n),r}addMaps(e){return this.eventCount==0?this:new Hn(this.items.append(e.map(n=>new ir(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],o=Math.max(0,this.items.length-n),s=e.mapping,i=e.steps.length,a=this.eventCount;this.items.forEach(h=>{h.selection&&a--},o);let l=n;this.items.forEach(h=>{let p=s.getMirror(--l);if(p==null)return;i=Math.min(i,p);let m=s.maps[p];if(h.step){let g=e.steps[p].invert(e.docs[p]),y=h.selection&&h.selection.map(s.slice(l+1,p));y&&a++,r.push(new ir(m,g,y))}else r.push(new ir(m))},o);let c=[];for(let h=n;h<i;h++)c.push(new ir(s.maps[h]));let u=this.items.slice(0,o).append(c).append(r),f=new Hn(u,a);return f.emptyItemCount()>_z&&(f=f.compress(this.items.length-r.length)),f}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,o=[],s=0;return this.items.forEach((i,a)=>{if(a>=e)o.push(i),i.selection&&s++;else if(i.step){let l=i.step.map(n.slice(r)),c=l&&l.getMap();if(r--,c&&n.appendMap(c,r),l){let u=i.selection&&i.selection.map(n.slice(r));u&&s++;let f=new ir(c.invert(),l,u),h,p=o.length-1;(h=o.length&&o[p].merge(f))?o[p]=h:o.push(f)}}else i.map&&r--},this.items.length,0),new Hn(vt.from(o.reverse()),s)}}Hn.empty=new Hn(vt.empty,0);function Iz(t,e){let n;return t.forEach((r,o)=>{if(r.selection&&e--==0)return n=o,!1}),t.slice(n)}class ir{constructor(e,n,r,o){this.map=e,this.step=n,this.selection=r,this.mirrorOffset=o}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new ir(n.getMap().invert(),n,this.selection)}}}class go{constructor(e,n,r,o,s){this.done=e,this.undone=n,this.prevRanges=r,this.prevTime=o,this.prevComposition=s}}const Bz=20;function Nz(t,e,n,r){let o=n.getMeta(Qo),s;if(o)return o.historyState;n.getMeta(Oz)&&(t=new go(t.done,t.undone,null,0,-1));let i=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(i&&i.getMeta(Qo))return i.getMeta(Qo).redo?new go(t.done.addTransform(n,void 0,r,ac(e)),t.undone,mk(n.mapping.maps),t.prevTime,t.prevComposition):new go(t.done,t.undone.addTransform(n,void 0,r,ac(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(i&&i.getMeta("addToHistory")===!1)){let a=n.getMeta("composition"),l=t.prevTime==0||!i&&t.prevComposition!=a&&(t.prevTime<(n.time||0)-r.newGroupDelay||!Pz(n,t.prevRanges)),c=i?Mf(t.prevRanges,n.mapping):mk(n.mapping.maps);return new go(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,ac(e)),Hn.empty,c,n.time,a??t.prevComposition)}else return(s=n.getMeta("rebased"))?new go(t.done.rebased(n,s),t.undone.rebased(n,s),Mf(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new go(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),Mf(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function Pz(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((r,o)=>{for(let s=0;s<e.length;s+=2)r<=e[s+1]&&o>=e[s]&&(n=!0)}),n}function mk(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((r,o,s,i)=>e.push(s,i));return e}function Mf(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let o=e.map(t[r],1),s=e.map(t[r+1],-1);o<=s&&n.push(o,s)}return n}function Dz(t,e,n){let r=ac(e),o=Qo.get(e).spec.config,s=(n?t.undone:t.done).popEvent(e,r);if(!s)return null;let i=s.selection.resolve(s.transform.doc),a=(n?t.done:t.undone).addTransform(s.transform,e.selection.getBookmark(),o,r),l=new go(n?a:s.remaining,n?s.remaining:a,null,0,-1);return s.transform.setSelection(i).setMeta(Qo,{redo:n,historyState:l})}let Af=!1,gk=null;function ac(t){let e=t.plugins;if(gk!=e){Af=!1,gk=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){Af=!0;break}}return Af}const Qo=new Wt("history"),Oz=new Wt("closeHistory");function Rz(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new ct({key:Qo,state:{init(){return new go(Hn.empty,Hn.empty,null,0,-1)},apply(e,n,r){return Nz(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,o=r=="historyUndo"?wk:r=="historyRedo"?kk:null;return!o||!e.editable?!1:(n.preventDefault(),o(e.state,e.dispatch))}}}})}function yk(t,e){return(n,r)=>{let o=Qo.getState(n);if(!o||(t?o.undone:o.done).eventCount==0)return!1;if(r){let s=Dz(o,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const wk=yk(!1,!0),kk=yk(!0,!0);Le.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=(t==null?void 0:t.node)||this.editor.state.doc;if(((t==null?void 0:t.mode)||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=t=>{const e=(t==null?void 0:t.node)||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new ct({key:new Wt("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const o=this.options.limit;if(o==null||o===0){t=!0;return}const s=this.storage.characters({node:r.doc});if(s>o){const i=s-o,a=0,l=i;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);const c=r.tr.deleteRange(a,l);return t=!0,c}t=!0},filterTransaction:(e,n)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const o=this.storage.characters({node:n.doc}),s=this.storage.characters({node:e.doc});if(s<=r||o>r&&s>r&&s<=o)return!0;if(o>r&&s>r&&s>o||!e.getMeta("paste"))return!1;const a=e.selection.$head.pos,l=s-r,c=a-l,u=a;return e.deleteRange(c,u),!(this.storage.characters({node:e.doc})>r)}})]}}),Le.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[kz(this.options)]}}),Le.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new ct({key:new Wt("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,s=[];if(!n||!r)return je.create(t,[]);let i=0;this.options.mode==="deepest"&&t.descendants((l,c)=>{if(l.isText)return;if(!(o>=c&&o<=c+l.nodeSize-1))return!1;i+=1});let a=0;return t.descendants((l,c)=>{if(l.isText||!(o>=c&&o<=c+l.nodeSize-1))return!1;if(a+=1,this.options.mode==="deepest"&&i-a>0||this.options.mode==="shallowest"&&a>1)return this.options.mode==="deepest";s.push(jt.node(c,c+l.nodeSize,{class:this.options.className}))}),je.create(t,s)}}})]}}),Le.create({name:"gapCursor",addProseMirrorPlugins(){return[Ez()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Pe(ne(t,"allowGapCursor",n)))!=null?e:null}}}),Le.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[new ct({key:new Wt("placeholder"),props:{decorations:({doc:t,selection:e})=>{const n=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:r}=e,o=[];if(!n)return null;const s=this.editor.isEmpty;return t.descendants((i,a)=>{const l=r>=a&&r<=a+i.nodeSize,c=!i.isLeaf&&Jl(i);if((l||!this.options.showOnlyCurrent)&&c){const u=[this.options.emptyNodeClass];s&&u.push(this.options.emptyEditorClass);const f=jt.node(a,a+i.nodeSize,{class:u.join(" "),"data-placeholder":typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:i,pos:a,hasAnchor:l}):this.options.placeholder});o.push(f)}return this.options.includeChildren}),je.create(t,o)}}})]}}),Le.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new ct({key:new Wt("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||tR(n.selection)||t.view.dragging?null:je.create(n.doc,[jt.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function vk({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(e==null?void 0:e.type)===t}Le.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Wt(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,o])=>o).filter(o=>(this.options.notAfter||[]).concat(n).includes(o.name));return[new ct({key:e,appendTransaction:(o,s,i)=>{const{doc:a,tr:l,schema:c}=i,u=e.getState(i),f=a.content.size,h=c.nodes[n];if(u)return l.insert(f,h.create())},state:{init:(o,s)=>{const i=s.tr.doc.lastChild;return!vk({node:i,types:r})},apply:(o,s)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return s;const i=o.doc.lastChild;return!vk({node:i,types:r})}}})]}});var zz=Le.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>wk(t,e),redo:()=>({state:t,dispatch:e})=>kk(t,e)}},addProseMirrorPlugins(){return[Rz(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}});function yo(t,e){const n=d.inject(En);if(!n)throw new Error("useComponents must be used within a WovenCanvas component");const r=d.shallowRef(new Map),o=new Map;function s(a){if(o.has(a))return;const l=n.getEditor();if(l){const u=l._getContext();if(O(u,a,e)){const f=new Map(r.value);f.set(a,e.snapshot(u,a)),r.value=f}else{const f=new Map(r.value);f.set(a,null),r.value=f}}const c=n.subscribeComponent(a,e.name,u=>{const f=new Map(r.value);f.set(a,u),r.value=f});o.set(a,c)}function i(a){const l=o.get(a);if(l){l(),o.delete(a);const c=new Map(r.value);c.delete(a),r.value=c}}return d.watch(()=>d.toValue(t),(a,l)=>{const c=new Set(a),u=new Set(l??[]);for(const f of u)c.has(f)||i(f);for(const f of c)u.has(f)||s(f)},{immediate:!0}),d.onUnmounted(()=>{for(const a of o.values())a();o.clear()}),r}function bk(){const t=d.inject(En);if(!t)throw new Error("useImageCreation must be used within a WovenCanvas component");const{nextEditorTick:e}=tt();function n(s){return new Promise((i,a)=>{const l=new window.Image;l.onload=()=>{i({width:l.naturalWidth,height:l.naturalHeight}),URL.revokeObjectURL(l.src)},l.onerror=()=>{a(new Error("Failed to load image")),URL.revokeObjectURL(l.src)},l.src=URL.createObjectURL(s)})}async function r(s,i,a,l={}){const{maxSize:c=400}=l,u=await n(s),f=await e(),h=Math.min(1,c/Math.max(u.width,u.height));let p=Math.round(u.width*h),m=Math.round(u.height*h);const g=Ot.read(f);g.enabled&&(p=Math.max(g.colWidth,Math.round(p/g.colWidth)*g.colWidth),m=Math.max(g.rowHeight,Math.round(m/g.rowHeight)*g.rowHeight));const y=bt(f);J(f,y,A);const w=A.write(f,y);w.tag="image",w.position[0]=i-p/2,w.position[1]=a-m/2,w.size[0]=p,w.size[1]=m,Ot.snapPosition(f,w.position);const k=crypto.randomUUID();J(f,y,Bo);const b=Bo.write(f,y);b.identifier=k,b.uploadState=nr.Pending,J(f,y,pi);const S=pi.write(f,y);return S.width=u.width,S.height=u.height,S.alt=s.name,J(f,y,Si,{id:crypto.randomUUID()}),(t==null?void 0:t.getAssetManager())&&o(y,k,s),y}async function o(s,i,a){const l=t==null?void 0:t.getAssetManager();if(l)try{await l.upload(i,a,{filename:a.name,mimeType:a.type});const c=await e(),u=Bo.write(c,s);u.uploadState=nr.Complete}catch{const c=await e(),u=Bo.write(c,s);u.uploadState=nr.Failed}}return{getImageDimensions:n,createImageBlock:r}}function Sk(t){const e=d.inject(En);if(!e)throw new Error("useQuery must be used within a WovenCanvas component");const n=d.shallowRef([]),r=re(f=>f.with(...t)),o=new Map;let s=!1;function i(f){const h=e.getEditor();if(!h)return{refs:{},unsubscribes:[]};const p=h._getContext(),m={},g=[];for(const y of t){const w=d.shallowRef(y.snapshot(p,f));m[y.name]=w;const k=e.subscribeComponent(f,y.name,b=>{w.value=b});g.push(k)}return{refs:m,unsubscribes:g}}function a(f){const h=o.get(f);if(h){for(const p of h.unsubscribes)p();o.delete(f)}}function l(){const f=[];for(const[h,p]of o)f.push({entityId:h,...p.refs});return f}function c(f){if(!s){const g=r.current(f);for(const y of g)o.set(y,i(y));n.value=l(),s=!0;return}const h=r.added(f),p=r.removed(f);let m=!1;for(const g of p)a(g),m=!0;for(const g of h)o.has(g)||(o.set(g,i(g)),m=!0);m&&(n.value=l())}const u=e.registerTickCallback(c);return d.onUnmounted(()=>{u();for(const f of o.keys())a(f)}),n}function Nt(t){const e=d.inject(En);if(!e)throw new Error("useSingleton must be used within a WovenCanvas component");const n=d.shallowRef(t.default()),r=e.getEditor();if(r){const i=r._getContext();n.value=t.snapshot(i)}const o=e.subscribeSingleton(t.name,i=>{n.value=i??{}});let s=null;return r||(s=e.registerTickCallback(()=>{const i=e.getEditor();if(i){const a=i._getContext();n.value=t.snapshot(a),s==null||s(),s=null}})),d.onUnmounted(()=>{o(),s==null||s()}),n}function $z(t,e,n){if(n===0)return{width:t,height:e};if(Math.abs(n-Math.PI/2)<1e-4)return{width:e,height:t};const r=Math.abs(Math.cos(n)),o=Math.abs(Math.sin(n)),s=(e-o/r*t)/(r-o*o/r);return{width:t/r-s*o/r,height:s}}function _f(t,e,n){const r=t.closest(".wov-block");if(!r){const E=t.getBoundingClientRect();return{width:E.width,height:E.height,left:0,top:0}}const o=window.getComputedStyle(r).transform,s=new DOMMatrix(o),i=Math.atan2(s.b,s.a),a=t.getBoundingClientRect(),l=new DOMPoint(a.left+a.width/2,a.top+a.height/2),c=e.value.left,u=e.value.top,f=e.value.zoom,h=new DOMMatrix;h.translateSelf(-c*f,-u*f),h.scaleSelf(f,f),h.invertSelf();const p=h.transformPoint(l),m=h.transformPoint(new DOMPoint(a.left,a.top)),g=h.transformPoint(new DOMPoint(a.right,a.bottom)),y=g.x-m.x,w=g.y-m.y,{width:k,height:b}=$z(y,w,-i),S=n.value.left,v=n.value.top;return{width:k,height:b,left:p.x-k/2-S,top:p.y-b/2-v}}function Ek(t){if(t.startsWith("#"))return t.toUpperCase();const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1],10).toString(16).padStart(2,"0"),r=parseInt(e[2],10).toString(16).padStart(2,"0"),o=parseInt(e[3],10).toString(16).padStart(2,"0");return`#${n}${r}${o}`.toUpperCase()}return t}function ra(t){const e=Math.round(t.red),n=Math.round(t.green),r=Math.round(t.blue),o=Math.round(t.alpha);return o<255?"#"+[e,n,r,o].map(s=>{const i=s.toString(16);return i.length===1?`0${i}`:i}).join(""):"#"+[e,n,r].map(s=>{const i=s.toString(16);return i.length===1?`0${i}`:i}).join("")}function If(t){t=t.replace(/^#/,"");let e,n,r,o=255;if(t.length===6)e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);else if(t.length===8)e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),o=parseInt(t.slice(6,8),16);else return null;return{red:e,green:n,blue:r,alpha:o}}function Ck(t){const e=If(t);if(!e)return{h:0,s:100,v:100,a:255};const n=e.red/255,r=e.green/255,o=e.blue/255,s=Math.max(n,r,o),i=Math.min(n,r,o),a=s-i;let l=0;const c=s===0?0:a/s*100,u=s*100;if(a!==0)switch(s){case n:l=((r-o)/a+(r<o?6:0))*60;break;case r:l=((o-n)/a+2)*60;break;case o:l=((n-r)/a+4)*60;break}return{h:l,s:c,v:u,a:e.alpha}}function xk(t){const e=t.h/360,n=t.s/100,r=t.v/100;let o=0,s=0,i=0;const a=Math.floor(e*6),l=e*6-a,c=r*(1-n),u=r*(1-l*n),f=r*(1-(1-l)*n);switch(a%6){case 0:o=r,s=f,i=c;break;case 1:o=u,s=r,i=c;break;case 2:o=c,s=r,i=f;break;case 3:o=c,s=u,i=r;break;case 4:o=f,s=c,i=r;break;case 5:o=r,s=c,i=u;break}const h=p=>Math.round(p*255).toString(16).padStart(2,"0");return`#${h(o)}${h(s)}${h(i)}`}function Tk(t){const e=t.h/360,n=t.s/100,r=t.v/100;let o=0,s=0,i=0;const a=Math.floor(e*6),l=e*6-a,c=r*(1-n),u=r*(1-l*n),f=r*(1-(1-l)*n);switch(a%6){case 0:o=r,s=f,i=c;break;case 1:o=u,s=r,i=c;break;case 2:o=c,s=r,i=f;break;case 3:o=c,s=u,i=r;break;case 4:o=f,s=c,i=r;break;case 5:o=r,s=c,i=u;break}const h=m=>Math.round(m*255).toString(16).padStart(2,"0"),p=Math.round(t.a).toString(16).padStart(2,"0");return t.a<255?`#${h(o)}${h(s)}${h(i)}${p}`:`#${h(o)}${h(s)}${h(i)}`}const en=d.shallowRef(null),Bf=d.shallowRef(null),Nf=d.shallowRef(null),wo=d.ref(0);function oa(){const t={hasEditor:d.computed(()=>en.value!==null),isBold:d.computed(()=>{var o;return wo.value,((o=en.value)==null?void 0:o.isActive("bold"))??!1}),isItalic:d.computed(()=>{var o;return wo.value,((o=en.value)==null?void 0:o.isActive("italic"))??!1}),isUnderline:d.computed(()=>{var o;return wo.value,((o=en.value)==null?void 0:o.isActive("underline"))??!1}),alignment:d.computed(()=>{wo.value;const o=en.value;return o?o.isActive({textAlign:"center"})?"center":o.isActive({textAlign:"right"})?"right":o.isActive({textAlign:"justify"})?"justify":"left":"left"}),color:d.computed(()=>{wo.value;const o=en.value;if(!o)return null;const i=o.getAttributes("textStyle").color??null;return i?Ek(i):null})},e={toggleBold(){const o=en.value;if(!o)return;const{from:s,to:i}=o.state.selection,a=s===i;let l=o.chain().focus();a&&(l=l.selectAll()),l=l.toggleBold(),a&&(l=l.setTextSelection(i)),l.run()},toggleItalic(){const o=en.value;if(!o)return;const{from:s,to:i}=o.state.selection,a=s===i;let l=o.chain().focus();a&&(l=l.selectAll()),l=l.toggleItalic(),a&&(l=l.setTextSelection(i)),l.run()},toggleUnderline(){const o=en.value;if(!o)return;const{from:s,to:i}=o.state.selection,a=s===i;let l=o.chain().focus();a&&(l=l.selectAll()),l=l.toggleUnderline(),a&&(l=l.setTextSelection(i)),l.run()},setAlignment(o){const s=en.value;s&&s.chain().selectAll().setTextAlign(o).run()},setColor(o){const s=en.value;if(!s)return;const{from:i,to:a}=s.state.selection;i===a?s.chain().focus().selectAll().setColor(o).setTextSelection(a).run():s.chain().focus().setColor(o).run()}};function n(o,s,i){en.value=o,Nf.value=s,Bf.value=i,o.on("selectionUpdate",()=>{wo.value++}),o.on("transaction",()=>{wo.value++})}function r(){en.value=null,Nf.value=null,Bf.value=null}return{editor:en,blockElement:Bf,textElement:Nf,state:t,commands:e,updateCounter:wo,register:n,unregister:r}}const _n=[nk,rk,ok,xf,fk,ik,ak,lk,ck.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})];function Lz(t){return t.type==="text"&&typeof t.text=="string"}function es(t,e){if(Lz(t)){e(t);return}if(t.content)for(const n of t.content)es(n,e)}function Pf(t,e){if(t.type==="paragraph"){e(t);return}if(t.content)for(const n of t.content)Pf(n,e)}function Vz(t,e){var n;return((n=t.marks)==null?void 0:n.some(r=>r.type===e))??!1}function Fz(t){var r,o;const e=(r=t.marks)==null?void 0:r.find(s=>s.type==="textStyle"),n=((o=e==null?void 0:e.attrs)==null?void 0:o.color)??null;return n?Ek(n):null}function Wz(t,e){if(!t.trim())return!1;const n=mo(t,_n);let r=!1,o=!0,s=0;return es(n,i=>{s++,Vz(i,e)?r=!0:o=!1}),s===0?!1:o?!0:r?null:!1}function Uz(t){if(!t.trim())return"left";const e=mo(t,_n);let n="left";return Pf(e,r=>{var s;const o=(s=r.attrs)==null?void 0:s.textAlign;o&&(n=o)}),n}function Hz(t){if(!t.trim())return null;const e=mo(t,_n);let n=null;return es(e,r=>{n===null&&(n=Fz(r))}),n}function Df(t,e){if(!t.trim())return t;const n=mo(t,_n);return es(n,r=>{const o=r.marks??[];o.findIndex(i=>i.type===e)===-1&&(r.marks=[...o,{type:e}])}),ql(n,_n)}function Of(t,e){if(!t.trim())return t;const n=mo(t,_n);return es(n,r=>{const o=r.marks??[];r.marks=o.filter(s=>s.type!==e)}),ql(n,_n)}function jz(t,e){if(!t.trim())return t;const n=mo(t,_n);return Pf(n,r=>{r.attrs={...r.attrs,textAlign:e}}),ql(n,_n)}function Zz(t,e){if(!t.trim())return t;const n=mo(t,_n);return es(n,r=>{const o=r.marks??[],s=o.findIndex(i=>i.type==="textStyle");s!==-1?(o[s]={...o[s],attrs:{...o[s].attrs,color:e}},r.marks=o):r.marks=[...o,{type:"textStyle",attrs:{color:e}}]}),ql(n,_n)}function Mk(t){const e=document.querySelector(`[data-entity-id="${t}"]`);if(!e)return null;const n=e.firstElementChild;return n||e.querySelector(".wov-editable-text")}function Ak(t,e,n,r){var l;const o=t.cloneNode(!0);o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.top="0",o.style.left="0";const s=o.classList.contains("wov-editable-text")?o:o.querySelector(".wov-editable-text");s&&(s.style.fontSize=`${r.fontSizePx}px`,s.style.fontFamily=r.fontFamily);const i=o.querySelector(".ProseMirror, .tiptap");i?i.innerHTML=r.content:s?s.innerHTML=r.content:o.innerHTML=r.content,(l=t.parentElement)==null||l.appendChild(o);const a=_f(o,e,n);return o.remove(),a}function _k(t){const{nextEditorTick:e}=tt(),n=yo(t,at),r=Nt(he),o=Nt(Mt),s=oa(),i={hasTextEntities:d.computed(()=>{for(const h of n.value.values())if(h)return!0;return!1}),hasTextContent:d.computed(()=>{for(const h of n.value.values()){if(!h)continue;const p=h.content?mo(h.content,_n):null;if(p){let m=!1;if(es(p,g=>{var y;(y=g.text)!=null&&y.trim()&&(m=!0)}),m)return!0}}return!1}),isBold:d.computed(()=>a("bold")),isItalic:d.computed(()=>a("italic")),isUnderline:d.computed(()=>a("underline")),alignment:d.computed(()=>{let h=null;for(const p of n.value.values()){if(!p)continue;const m=Uz(p.content);if(h===null)h=m;else if(h!==m)return null}return h??"left"}),color:d.computed(()=>{let h=null,p=!1;for(const m of n.value.values()){if(!m)continue;const g=Hz(m.content);if(!p)h=g,p=!0;else if(h!==g)return null}return h}),fontSize:d.computed(()=>{let h=null,p=!1;for(const m of n.value.values())if(m){if(!p)h=m.fontSizePx,p=!0;else if(h!==m.fontSizePx)return null}return h}),fontFamily:d.computed(()=>{let h=null,p=!1;for(const m of n.value.values())if(m){if(!p)h=m.fontFamily,p=!0;else if(h!==m.fontFamily)return null}return h})};function a(h){let p=null,m=!1;for(const g of n.value.values()){if(!g)continue;const y=Wz(g.content,h);if(!m)p=y,m=!0;else if(p!==y)return null}return p}const l={toggleBold(){u(h=>i.isBold.value?Of(h,"bold"):Df(h,"bold"))},toggleItalic(){u(h=>i.isItalic.value?Of(h,"italic"):Df(h,"italic"))},toggleUnderline(){u(h=>i.isUnderline.value?Of(h,"underline"):Df(h,"underline"))},setAlignment(h){f(p=>jz(p,h))},setColor(h){f(p=>Zz(p,h))},setFontSize(h){c(p=>({...p,fontSizePx:h}),p=>{p.fontSizePx=h})},setFontFamily(h){c(p=>({...p,fontFamily:h}),p=>{p.fontFamily=h})}};function c(h,p){const m=d.toValue(t),g=[];for(const y of m){const w=n.value.get(y);if(!w)continue;const k=Mk(y);if(k){const b=Ak(k,r,o,h(w));g.push({entityId:y,...b})}}e(y=>{for(const w of m)p(at.write(y,w));for(const{entityId:w,width:k,height:b,left:S,top:v}of g){const E=A.write(y,w);E.size=[k,b],E.position=[S,v]}d.nextTick(()=>{s.updateCounter.value++})})}function u(h){const p=d.toValue(t),m=[];for(const g of p){const y=n.value.get(g);if(!y)continue;const w=h(y.content),k=Mk(g);if(k){const b=Ak(k,r,o,{...y,content:w});m.push({entityId:g,content:w,...b})}else m.push({entityId:g,content:w,width:0,height:0,left:0,top:0})}e(g=>{for(const{entityId:y,content:w,width:k,height:b,left:S,top:v}of m){const E=at.write(g,y);if(E.content=w,k>0&&b>0){const T=A.write(g,y);T.size=[k,b],T.position=[S,v]}}})}function f(h){const p=d.toValue(t);e(m=>{for(const g of p){const y=at.write(m,g);y.content=h(y.content)}})}return{state:i,commands:l}}function ar(t){const e=oa(),n=_k(t),r=e.state.hasEditor;return{state:d.reactive({hasTextToFormat:d.computed(()=>r.value||n.state.hasTextEntities.value),hasEditor:r,hasTextContent:d.computed(()=>n.state.hasTextContent.value),showTextMenuButtons:d.computed(()=>r.value||n.state.hasTextContent.value),isBold:d.computed(()=>r.value?e.state.isBold.value:n.state.isBold.value===!0),isItalic:d.computed(()=>r.value?e.state.isItalic.value:n.state.isItalic.value===!0),isUnderline:d.computed(()=>r.value?e.state.isUnderline.value:n.state.isUnderline.value===!0),alignment:d.computed(()=>r.value?e.state.alignment.value:n.state.alignment.value??"left"),color:d.computed(()=>r.value?e.state.color.value:n.state.color.value),fontSize:d.computed(()=>n.state.fontSize.value),fontFamily:d.computed(()=>n.state.fontFamily.value)}),commands:{toggleBold(){r.value?e.commands.toggleBold():n.commands.toggleBold()},toggleItalic(){r.value?e.commands.toggleItalic():n.commands.toggleItalic()},toggleUnderline(){r.value?e.commands.toggleUnderline():n.commands.toggleUnderline()},setAlignment(i){r.value?e.commands.setAlignment(i):n.commands.setAlignment(i)},setColor(i){r.value?e.commands.setColor(i):n.commands.setColor(i)},setFontSize(i){n.commands.setFontSize(i)},setFontFamily(i){n.commands.setFontFamily(i)}}}}function Rf(t){const e=Nt(he),n=Nt(Mt),r=Nt(Ku),o=Nt(zn),{nextEditorTick:s}=tt();let i=!1,a=null;function l(u,f){const{entityId:h}=d.toValue(t.blockData),p=d.toValue(t.minWidth)??0,m=d.toValue(t.minHeight)??0,g=Math.max(f.width,p),y=Math.max(f.height,m),w=A.read(u,h),k=Math.abs(w.size[0]-g)>.5,b=Math.abs(w.size[1]-y)>.5;if(!k&&!b)return;const S=A.write(u,h);S.size=[g,y],S.position=[f.left,f.top],r.value.transformBoxId!==null&&Uu.spawn(u,{transformBoxId:r.value.transformBoxId})}d.watch(()=>o.value,()=>{const u=t.containerRef.value;u&&i&&(a=_f(u,e,n)),s(f=>{const h=Kz(f);i&&!h&&a&&(l(f,a),a=null),i=h})},{flush:"sync"});function c(u){const{content:f,...h}=u;s(p=>{const{entityId:m}=d.toValue(t.blockData);if(at.read(p,m).content!==f){const y=at.write(p,m);y.content=f}l(p,h)})}return{handleEditEnd:c}}function Kz(t){const e=zn.read(t);return e.state===ye.Dragging&&e.draggedEntity!==null&&O(t,e.draggedEntity,$e)&&$e.read(t,e.draggedEntity).kind===Rn.Stretch}function zf(){const t=d.inject(dd);if(!t)throw new Error("useToolbar must be used within a Toolbar component");return{activeTool:t.activeTool,heldTool:t.heldTool,setTool:t.setTool,dragOutTool:t.dragOutTool,onToolPointerDown:t.onToolPointerDown,onToolPointerUp:t.onToolPointerUp,isActive:e=>d.computed(()=>t.activeTool.value===e)}}const Yz=500,qz=1500;function Ik(){const t=d.ref(null),e=d.ref(!1),n=d.ref(!1);let r=null,o=null;function s(){r&&(clearTimeout(r),r=null),o&&(clearTimeout(o),o=null)}function i(c,u){s(),t.value={text:c,anchor:u},n.value?e.value=!0:r=setTimeout(()=>{e.value=!0,n.value=!0,r=null},Yz)}function a(){s(),e.value=!1,t.value=null,n.value&&(o=setTimeout(()=>{n.value=!1,o=null},qz))}function l(){s(),e.value=!1,t.value=null,n.value=!1}return{activeTooltip:d.readonly(t),isVisible:d.readonly(e),isWarmedUp:d.readonly(n),show:i,hide:a,reset:l}}function ko(){const t=d.inject(my);if(!t)throw new Error("useTooltipSingleton must be used within a WovenCanvas component");return t}const Xz={key:1},Gz=["innerHTML"],Jz=50,Qz=300,lc=d.defineComponent({__name:"EditableText",props:{blockElement:{},entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},emits:["editEnd"],setup(t,{expose:e,emit:n}){var v;const r=t,o=n,s=mt(r.entityId,at),i=Nt(he),a=Nt(Mt),l=oa(),{nextEditorTick:c}=tt(),u=Nt(bn),f=d.ref(null);e({editableTextRef:f});const h=d.ref(((v=s.value)==null?void 0:v.content)??""),p=d.shallowRef(null);function m(E,T){var z;const _=s.value;return!_||_.constrainWidth||(((z=T.clipboardData)==null?void 0:z.getData("text/plain"))??"").length>Jz&&c(F=>{const j=at.write(F,r.entityId);j.constrainWidth=!0;const M=A.read(F,r.entityId),V=Math.max(M.size[0],Qz),K=A.write(F,r.entityId);K.size=[V,M.size[1]],Vm.spawn(F),Ps.spawn(F)}),!1}function g(){var E,T;return new XR({extensions:[nk,rk,ok,xf,fk,ik,ak,lk,ck.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:((E=s.value)==null?void 0:E.defaultAlignment)??"left"}),zz],content:((T=s.value)==null?void 0:T.content)??"",editable:!0,parseOptions:{preserveWhitespace:!0},editorProps:{handlePaste:m}})}d.watch(()=>r.edited,async E=>{if(E&&f.value){if(p.value=g(),await y(p.value),!r.blockElement)return;l.register(p.value,f.value,r.blockElement)}else p.value&&(l.unregister(),w(p.value),p.value.destroy(),p.value=null)},{immediate:!0});async function y(E){var z;const T=(z=u.value)==null?void 0:z.position,_=a.value;await d.nextTick(),await new Promise(F=>requestAnimationFrame(F));const I=f.value;if(T&&_&&I){const F=T[0]+_.left,j=T[1]+_.top,M=E.view.posAtCoords({left:F,top:j});if(M){E.chain().focus().setTextSelection(M.pos).run();return}}E.commands.focus("start")}function w(E){let T=E.getHTML();const I=T.replace(/<[^>]*>/g,"").trim().length>0;I||(T=""),h.value=T,c(z=>{var K,se;const F=Vt(z,r.block.tag);if(!I&&((K=F.editOptions)!=null&&K.removeWhenTextEmpty)){qe(z,r.entityId);return}const j=(se=f.value)==null?void 0:se.closest(".wov-block"),M=(j==null?void 0:j.firstElementChild)??f.value;if(!M){console.warn("EditableText: no element to measure");return}const V=_f(M,i,a);o("editEnd",{content:T,...V})})}d.watch(()=>{var E;return(E=s.value)==null?void 0:E.content},E=>{E!==void 0&&(p.value?p.value.getHTML()!==E&&p.value.commands.setContent(E,{emitUpdate:!1}):h.value=E)});const k=d.computed(()=>{const E=s.value;return E?{fontFamily:E.fontFamily,fontSize:`${E.fontSizePx}px`,lineHeight:E.lineHeight,letterSpacing:`${E.letterSpacingEm}em`,width:E.constrainWidth?"100%":"fit-content",whiteSpace:E.constrainWidth?"pre-wrap":"pre",minWidth:"2px",wordBreak:"break-word",pointerEvents:r.edited?"auto":"none",userSelect:r.edited?"auto":"none"}:{}});function b(E){E.key==="Control"||E.key==="Meta"||E.stopPropagation()}function S(E){r.edited&&E.stopPropagation()}return d.onUnmounted(()=>{p.value&&(l.unregister(),p.value.destroy(),p.value=null)}),(E,T)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"editableTextRef",ref:f,class:"wov-editable-text",style:d.normalizeStyle(k.value),onKeydown:b,onPointerdown:S,onPointermove:S,onPointerup:S},[p.value?(d.openBlock(),d.createBlock(d.unref(GR),{key:0,editor:p.value},null,8,["editor"])):(d.openBlock(),d.createElementBlock("div",Xz,[d.createElementVNode("div",{class:"tiptap ProseMirror",innerHTML:h.value},null,8,Gz)]))],36))}}),e$={class:"wov-shape-svg",viewBox:"0 0 100 100",preserveAspectRatio:"none"},t$=["d","fill","stroke","stroke-width","stroke-dasharray"],Bk=d.defineComponent({__name:"ShapeBlock",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=mt(e.entityId,wn),r=mt(e.entityId,No),o=d.ref(null),s={[it.Top]:"flex-start",[it.Center]:"center",[it.Bottom]:"flex-end"},i=d.computed(()=>n.value?`rgba(${n.value.fillRed}, ${n.value.fillGreen}, ${n.value.fillBlue}, ${(n.value.fillAlpha??255)/255})`:"rgba(0, 0, 0, 0)"),a=d.computed(()=>n.value?n.value.strokeKind===ht.None?"none":`rgba(${n.value.strokeRed}, ${n.value.strokeGreen}, ${n.value.strokeBlue}, ${n.value.strokeAlpha/255})`:"rgba(0, 0, 0, 1)"),l=d.computed(()=>{var g;return((g=n.value)==null?void 0:g.strokeWidth)??2}),c=d.computed(()=>{var g;return((g=n.value)==null?void 0:g.strokeKind)??ht.Solid}),u=d.computed(()=>{var g;return Di[((g=n.value)==null?void 0:g.kind)??"rectangle"]??Di.rectangle}),f=d.computed(()=>{const g=l.value;switch(c.value){case ht.Dashed:return`${g*3} ${g*3}`;case ht.None:return"";case ht.Solid:default:return""}}),h=d.computed(()=>{var g;return{overflow:e.edited?"visible":"hidden",alignItems:s[((g=r.value)==null?void 0:g.value)??it.Top]}}),{nextEditorTick:p}=tt();function m(g){p(y=>{if(at.read(y,e.entityId).content===g.content)return;const k=at.write(y,e.entityId);k.content=g.content})}return(g,y)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:o,class:"wov-shape-block"},[(d.openBlock(),d.createElementBlock("svg",e$,[d.createElementVNode("path",{d:u.value,fill:i.value,stroke:a.value,"stroke-width":l.value,"stroke-dasharray":f.value,"stroke-linecap":"round","stroke-linejoin":"round","vector-effect":"non-scaling-stroke"},null,8,t$)])),d.createElementVNode("div",{class:"wov-shape-content",style:d.normalizeStyle(h.value)},[d.createVNode(lc,d.mergeProps(e,{"block-element":o.value,onEditEnd:m}),null,16,["block-element"])],4)],512))}}),n$=["data-text-empty"],Nk=d.defineComponent({__name:"TextBlock",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=d.ref(null),r=mt(e.entityId,at),o=d.computed(()=>{var l;return(((l=r.value)==null?void 0:l.content)??"").replace(/<[^>]*>/g,"").trim().length===0}),{handleEditEnd:s}=Rf({blockData:e,containerRef:n});return(i,a)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-text-block","data-text-empty":o.value||void 0},[d.createVNode(lc,d.mergeProps(e,{"block-element":n.value,onEditEnd:d.unref(s)}),null,16,["block-element","onEditEnd"])],8,n$))}}),cc=Math.min,ts=Math.max,uc=Math.round,dc=Math.floor,lr=t=>({x:t,y:t}),r$={left:"right",right:"left",bottom:"top",top:"bottom"},o$={start:"end",end:"start"};function Pk(t,e,n){return ts(t,cc(e,n))}function fc(t,e){return typeof t=="function"?t(e):t}function ns(t){return t.split("-")[0]}function hc(t){return t.split("-")[1]}function Dk(t){return t==="x"?"y":"x"}function Ok(t){return t==="y"?"height":"width"}const s$=new Set(["top","bottom"]);function vo(t){return s$.has(ns(t))?"y":"x"}function Rk(t){return Dk(vo(t))}function i$(t,e,n){n===void 0&&(n=!1);const r=hc(t),o=Rk(t),s=Ok(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=pc(i)),[i,pc(i)]}function a$(t){const e=pc(t);return[$f(t),e,$f(e)]}function $f(t){return t.replace(/start|end/g,e=>o$[e])}const zk=["left","right"],$k=["right","left"],l$=["top","bottom"],c$=["bottom","top"];function u$(t,e,n){switch(t){case"top":case"bottom":return n?e?$k:zk:e?zk:$k;case"left":case"right":return e?l$:c$;default:return[]}}function d$(t,e,n,r){const o=hc(t);let s=u$(ns(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map($f)))),s}function pc(t){return t.replace(/left|right|bottom|top/g,e=>r$[e])}function f$(t){return{top:0,right:0,bottom:0,left:0,...t}}function h$(t){return typeof t!="number"?f$(t):{top:t,right:t,bottom:t,left:t}}function mc(t){const{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}function Lk(t,e,n){let{reference:r,floating:o}=t;const s=vo(e),i=Rk(e),a=Ok(i),l=ns(e),c=s==="y",u=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:u,y:r.y-o.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(hc(e)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const p$=async(t,e,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(e));let c=await i.getElementRects({reference:t,floating:e,strategy:o}),{x:u,y:f}=Lk(c,r,l),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:y,fn:w}=a[g],{x:k,y:b,data:S,reset:v}=await w({x:u,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:t,floating:e}});u=k??u,f=b??f,p={...p,[y]:{...p[y],...S}},v&&m<=50&&(m++,typeof v=="object"&&(v.placement&&(h=v.placement),v.rects&&(c=v.rects===!0?await i.getElementRects({reference:t,floating:e,strategy:o}):v.rects),{x:u,y:f}=Lk(c,h,l)),g=-1)}return{x:u,y:f,placement:h,strategy:o,middlewareData:p}};async function Vk(t,e){var n;e===void 0&&(e={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=fc(e,t),m=h$(p),y=a[h?f==="floating"?"reference":"floating":f],w=mc(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),k=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),S=await(s.isElement==null?void 0:s.isElement(b))?await(s.getScale==null?void 0:s.getScale(b))||{x:1,y:1}:{x:1,y:1},v=mc(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:k,offsetParent:b,strategy:l}):k);return{top:(w.top-v.top+m.top)/S.y,bottom:(v.bottom-w.bottom+m.bottom)/S.y,left:(w.left-v.left+m.left)/S.x,right:(v.right-w.right+m.right)/S.x}}const m$=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=fc(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const w=ns(o),k=vo(a),b=ns(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),v=h||(b||!g?[pc(a)]:a$(a)),E=m!=="none";!h&&E&&v.push(...d$(a,g,m,S));const T=[a,...v],_=await Vk(e,y),I=[];let z=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&I.push(_[w]),f){const V=i$(o,i,S);I.push(_[V[0]],_[V[1]])}if(z=[...z,{placement:o,overflows:I}],!I.every(V=>V<=0)){var F,j;const V=(((F=s.flip)==null?void 0:F.index)||0)+1,K=T[V];if(K&&(!(f==="alignment"?k!==vo(K):!1)||z.every(R=>vo(R.placement)===k?R.overflows[0]>0:!0)))return{data:{index:V,overflows:z},reset:{placement:K}};let se=(j=z.filter(Y=>Y.overflows[0]<=0).sort((Y,R)=>Y.overflows[1]-R.overflows[1])[0])==null?void 0:j.placement;if(!se)switch(p){case"bestFit":{var M;const Y=(M=z.filter(R=>{if(E){const W=vo(R.placement);return W===k||W==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(W=>W>0).reduce((W,Q)=>W+Q,0)]).sort((R,W)=>R[1]-W[1])[0])==null?void 0:M[0];Y&&(se=Y);break}case"initialPlacement":se=a;break}if(o!==se)return{reset:{placement:se}}}return{}}}},g$=new Set(["left","top"]);async function y$(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=ns(n),a=hc(n),l=vo(n)==="y",c=g$.has(i)?-1:1,u=s&&l?-1:1,f=fc(e,t);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*u,y:h*c}:{x:h*c,y:p*u}}const w$=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=e,l=await y$(e,t);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},k$=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:o}=e,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x:w,y:k}=y;return{x:w,y:k}}},...l}=fc(t,e),c={x:n,y:r},u=await Vk(e,l),f=vo(ns(o)),h=Dk(f);let p=c[h],m=c[f];if(s){const y=h==="y"?"top":"left",w=h==="y"?"bottom":"right",k=p+u[y],b=p-u[w];p=Pk(k,p,b)}if(i){const y=f==="y"?"top":"left",w=f==="y"?"bottom":"right",k=m+u[y],b=m-u[w];m=Pk(k,m,b)}const g=a.fn({...e,[h]:p,[f]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[f]:i}}}}}};function gc(){return typeof window<"u"}function rs(t){return Lf(t)?(t.nodeName||"").toLowerCase():"#document"}function hn(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function cr(t){var e;return(e=(Lf(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Lf(t){return gc()?t instanceof Node||t instanceof hn(t).Node:!1}function jn(t){return gc()?t instanceof Element||t instanceof hn(t).Element:!1}function ur(t){return gc()?t instanceof HTMLElement||t instanceof hn(t).HTMLElement:!1}function Fk(t){return!gc()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof hn(t).ShadowRoot}const v$=new Set(["inline","contents"]);function sa(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=Zn(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!v$.has(o)}const b$=new Set(["table","td","th"]);function S$(t){return b$.has(rs(t))}const E$=[":popover-open",":modal"];function yc(t){return E$.some(e=>{try{return t.matches(e)}catch{return!1}})}const C$=["transform","translate","scale","rotate","perspective"],x$=["transform","translate","scale","rotate","perspective","filter"],T$=["paint","layout","strict","content"];function Vf(t){const e=Ff(),n=jn(t)?Zn(t):t;return C$.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||x$.some(r=>(n.willChange||"").includes(r))||T$.some(r=>(n.contain||"").includes(r))}function M$(t){let e=bo(t);for(;ur(e)&&!ei(e);){if(Vf(e))return e;if(yc(e))return null;e=bo(e)}return null}function Ff(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const A$=new Set(["html","body","#document"]);function ei(t){return A$.has(rs(t))}function Zn(t){return hn(t).getComputedStyle(t)}function wc(t){return jn(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function bo(t){if(rs(t)==="html")return t;const e=t.assignedSlot||t.parentNode||Fk(t)&&t.host||cr(t);return Fk(e)?e.host:e}function Wk(t){const e=bo(t);return ei(e)?t.ownerDocument?t.ownerDocument.body:t.body:ur(e)&&sa(e)?e:Wk(e)}function ia(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=Wk(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=hn(o);if(s){const a=Wf(i);return e.concat(i,i.visualViewport||[],sa(o)?o:[],a&&n?ia(a):[])}return e.concat(o,ia(o,[],n))}function Wf(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Uk(t){const e=Zn(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=ur(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=uc(n)!==s||uc(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Uf(t){return jn(t)?t:t.contextElement}function ti(t){const e=Uf(t);if(!ur(e))return lr(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=Uk(e);let i=(s?uc(n.width):n.width)/r,a=(s?uc(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const _$=lr(0);function Hk(t){const e=hn(t);return!Ff()||!e.visualViewport?_$:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function I$(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==hn(t)?!1:e}function ss(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=Uf(t);let i=lr(1);e&&(r?jn(r)&&(i=ti(r)):i=ti(t));const a=I$(s,n,r)?Hk(s):lr(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,u=o.width/i.x,f=o.height/i.y;if(s){const h=hn(s),p=r&&jn(r)?hn(r):r;let m=h,g=Wf(m);for(;g&&r&&p!==m;){const y=ti(g),w=g.getBoundingClientRect(),k=Zn(g),b=w.left+(g.clientLeft+parseFloat(k.paddingLeft))*y.x,S=w.top+(g.clientTop+parseFloat(k.paddingTop))*y.y;l*=y.x,c*=y.y,u*=y.x,f*=y.y,l+=b,c+=S,m=hn(g),g=Wf(m)}}return mc({width:u,height:f,x:l,y:c})}function kc(t,e){const n=wc(t).scrollLeft;return e?e.left+n:ss(cr(t)).left+n}function jk(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-kc(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function B$(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=cr(r),a=e?yc(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=lr(1);const u=lr(0),f=ur(r);if((f||!f&&!s)&&((rs(r)!=="body"||sa(i))&&(l=wc(r)),ur(r))){const p=ss(r);c=ti(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const h=i&&!f&&!s?jk(i,l):lr(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+h.x,y:n.y*c.y-l.scrollTop*c.y+u.y+h.y}}function N$(t){return Array.from(t.getClientRects())}function P$(t){const e=cr(t),n=wc(t),r=t.ownerDocument.body,o=ts(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=ts(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+kc(t);const a=-n.scrollTop;return Zn(r).direction==="rtl"&&(i+=ts(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Zk=25;function D$(t,e){const n=hn(t),r=cr(t),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const u=Ff();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=kc(r);if(c<=0){const u=r.ownerDocument,f=u.body,h=getComputedStyle(f),p=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=Zk&&(s-=m)}else c<=Zk&&(s+=c);return{width:s,height:i,x:a,y:l}}const O$=new Set(["absolute","fixed"]);function R$(t,e){const n=ss(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=ur(t)?ti(t):lr(1),i=t.clientWidth*s.x,a=t.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Kk(t,e,n){let r;if(e==="viewport")r=D$(t,n);else if(e==="document")r=P$(cr(t));else if(jn(e))r=R$(e,n);else{const o=Hk(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return mc(r)}function Yk(t,e){const n=bo(t);return n===e||!jn(n)||ei(n)?!1:Zn(n).position==="fixed"||Yk(n,e)}function z$(t,e){const n=e.get(t);if(n)return n;let r=ia(t,[],!1).filter(a=>jn(a)&&rs(a)!=="body"),o=null;const s=Zn(t).position==="fixed";let i=s?bo(t):t;for(;jn(i)&&!ei(i);){const a=Zn(i),l=Vf(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&O$.has(o.position)||sa(i)&&!l&&Yk(t,i))?r=r.filter(u=>u!==i):o=a,i=bo(i)}return e.set(t,r),r}function $$(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?yc(e)?[]:z$(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const f=Kk(e,u,o);return c.top=ts(f.top,c.top),c.right=cc(f.right,c.right),c.bottom=cc(f.bottom,c.bottom),c.left=ts(f.left,c.left),c},Kk(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function L$(t){const{width:e,height:n}=Uk(t);return{width:e,height:n}}function V$(t,e,n){const r=ur(e),o=cr(e),s=n==="fixed",i=ss(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=lr(0);function c(){l.x=kc(o)}if(r||!r&&!s)if((rs(e)!=="body"||sa(o))&&(a=wc(e)),r){const p=ss(e,!0,s,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else o&&c();s&&!r&&o&&c();const u=o&&!r&&!s?jk(o,a):lr(0),f=i.left+a.scrollLeft-l.x-u.x,h=i.top+a.scrollTop-l.y-u.y;return{x:f,y:h,width:i.width,height:i.height}}function Hf(t){return Zn(t).position==="static"}function qk(t,e){if(!ur(t)||Zn(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return cr(t)===n&&(n=n.ownerDocument.body),n}function Xk(t,e){const n=hn(t);if(yc(t))return n;if(!ur(t)){let o=bo(t);for(;o&&!ei(o);){if(jn(o)&&!Hf(o))return o;o=bo(o)}return n}let r=qk(t,e);for(;r&&S$(r)&&Hf(r);)r=qk(r,e);return r&&ei(r)&&Hf(r)&&!Vf(r)?n:r||M$(t)||n}const F$=async function(t){const e=this.getOffsetParent||Xk,n=this.getDimensions,r=await n(t.floating);return{reference:V$(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function W$(t){return Zn(t).direction==="rtl"}const U$={convertOffsetParentRelativeRectToViewportRelativeRect:B$,getDocumentElement:cr,getClippingRect:$$,getOffsetParent:Xk,getElementRects:F$,getClientRects:N$,getDimensions:L$,getScale:ti,isElement:jn,isRTL:W$};function Gk(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function H$(t,e){let n=null,r;const o=cr(t);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=t.getBoundingClientRect(),{left:u,top:f,width:h,height:p}=c;if(a||e(),!h||!p)return;const m=dc(f),g=dc(o.clientWidth-(u+h)),y=dc(o.clientHeight-(f+p)),w=dc(u),b={rootMargin:-m+"px "+-g+"px "+-y+"px "+-w+"px",threshold:ts(0,cc(1,l))||1};let S=!0;function v(E){const T=E[0].intersectionRatio;if(T!==l){if(!S)return i();T?i(!1,T):r=setTimeout(()=>{i(!1,1e-7)},1e3)}T===1&&!Gk(c,t.getBoundingClientRect())&&i(),S=!1}try{n=new IntersectionObserver(v,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(v,b)}n.observe(t)}return i(!0),s}function Jk(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Uf(t),u=o||s?[...c?ia(c):[],...ia(e)]:[];u.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),s&&w.addEventListener("resize",n)});const f=c&&a?H$(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(w=>{let[k]=w;k&&k.target===c&&p&&(p.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var b;(b=p)==null||b.observe(e)})),n()}),c&&!l&&p.observe(c),p.observe(e));let m,g=l?ss(t):null;l&&y();function y(){const w=ss(t);g&&!Gk(g,w)&&n(),g=w,m=requestAnimationFrame(y)}return n(),()=>{var w;u.forEach(k=>{o&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),f==null||f(),(w=p)==null||w.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const vc=w$,bc=k$,Sc=m$,j$=(t,e,n)=>{const r=new Map,o={platform:U$,...n},s={...o.platform,_c:r};return p$(t,e,{...o,platform:s})};function Z$(t){return t!=null&&typeof t=="object"&&"$el"in t}function Qk(t){if(Z$(t)){const e=t.$el;return Lf(e)&&rs(e)==="#comment"?null:e}return t}function aa(t){return typeof t=="function"?t():d.unref(t)}function ev(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function tv(t,e){const n=ev(t);return Math.round(e*n)/n}function Ec(t,e,n){n===void 0&&(n={});const r=n.whileElementsMounted,o=d.computed(()=>{var T;return(T=aa(n.open))!=null?T:!0}),s=d.computed(()=>aa(n.middleware)),i=d.computed(()=>{var T;return(T=aa(n.placement))!=null?T:"bottom"}),a=d.computed(()=>{var T;return(T=aa(n.strategy))!=null?T:"absolute"}),l=d.computed(()=>{var T;return(T=aa(n.transform))!=null?T:!0}),c=d.computed(()=>Qk(t.value)),u=d.computed(()=>Qk(e.value)),f=d.ref(0),h=d.ref(0),p=d.ref(a.value),m=d.ref(i.value),g=d.shallowRef({}),y=d.ref(!1),w=d.computed(()=>{const T={position:p.value,left:"0",top:"0"};if(!u.value)return T;const _=tv(u.value,f.value),I=tv(u.value,h.value);return l.value?{...T,transform:"translate("+_+"px, "+I+"px)",...ev(u.value)>=1.5&&{willChange:"transform"}}:{position:p.value,left:_+"px",top:I+"px"}});let k;function b(){if(c.value==null||u.value==null)return;const T=o.value;j$(c.value,u.value,{middleware:s.value,placement:i.value,strategy:a.value}).then(_=>{f.value=_.x,h.value=_.y,p.value=_.strategy,m.value=_.placement,g.value=_.middlewareData,y.value=T!==!1})}function S(){typeof k=="function"&&(k(),k=void 0)}function v(){if(S(),r===void 0){b();return}if(c.value!=null&&u.value!=null){k=r(c.value,u.value,b);return}}function E(){o.value||(y.value=!1)}return d.watch([s,i,a,o],b,{flush:"sync"}),d.watch([c,u],v,{flush:"sync"}),d.watch(o,E,{flush:"sync"}),d.getCurrentScope()&&d.onScopeDispose(S),{x:d.shallowReadonly(f),y:d.shallowReadonly(h),strategy:d.shallowReadonly(p),placement:d.shallowReadonly(m),middlewareData:d.shallowReadonly(g),isPositioned:d.shallowReadonly(y),floatingStyles:w,update:b}}const K$=["menu-open"],In=d.defineComponent({__name:"MenuDropdown",props:{title:{},disabled:{type:Boolean},placement:{default:"top"},offsetPx:{default:8}},emits:["open","close"],setup(t,{emit:e}){const n=t,r=e,o=d.inject("containerRef"),s=d.inject(fy,null),i=d.inject(hy,0),a=Math.random().toString(36).slice(2);d.provide(hy,i+1);const{show:l,hide:c}=ko(),u=d.ref(!1);s&&d.watch(()=>s.value.get(i),b=>{b!==void 0&&b!==a&&u.value&&(u.value=!1)});const f=d.ref(null),h=d.ref(null),{floatingStyles:p}=Ec(f,h,{placement:n.placement,middleware:[vc(n.offsetPx),Sc(),bc({padding:8})],whileElementsMounted:Jk});function m(){n.disabled||(u.value=!u.value)}function g(){u.value=!1}function y(b){var _,I,z;const S=b.target,v=(_=f.value)==null?void 0:_.contains(S),E=(I=h.value)==null?void 0:I.contains(S),T=(z=S.closest)==null?void 0:z.call(S,".wov-menu-dropdown");!v&&!E&&!T&&g()}function w(){n.title&&f.value&&!u.value&&l(n.title,f.value)}function k(){c()}return d.watch(u,b=>{b?(c(),document.addEventListener("click",y,!0),s&&(s.value.set(i,a),s.value=new Map(s.value)),r("open")):(document.removeEventListener("click",y,!0),(s==null?void 0:s.value.get(i))===a&&(s.value.delete(i),s.value=new Map(s.value)),r("close"))}),d.onUnmounted(()=>{document.removeEventListener("click",y,!0)}),(b,S)=>(d.openBlock(),d.createElementBlock(d.Fragment,null,[d.createElementVNode("div",{ref_key:"buttonRef",ref:f,class:d.normalizeClass(["wov-menu-dropdown-trigger",{"is-open":u.value}]),"menu-open":u.value||void 0,onMousedown:S[0]||(S[0]=d.withModifiers(()=>{},["prevent"])),onClick:m,onMouseenter:w,onMouseleave:k},[d.renderSlot(b.$slots,"button",{isOpen:u.value})],42,K$),d.unref(o)?(d.openBlock(),d.createBlock(d.Teleport,{key:0,to:d.unref(o)},[u.value?(d.openBlock(),d.createElementBlock("div",{key:0,ref_key:"dropdownRef",ref:h,class:"wov-menu-dropdown",style:d.normalizeStyle(d.unref(p))},[d.renderSlot(b.$slots,"dropdown",{close:g})],4)):d.createCommentVNode("",!0)],8,["to"])):d.createCommentVNode("",!0)],64))}}),Y$={},q$={viewBox:"0 0 512 320",fill:"currentColor",style:{width:"7px",color:"var(--wov-gray-300)"}};function X$(t,e){return d.openBlock(),d.createElementBlock("svg",q$,[...e[0]||(e[0]=[d.createElementVNode("path",{d:"M233.4 278.6c12.5 12.5 32.8 12.5 45.3 0l192-192c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L256 210.7 86.6 41.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l192 192z"},null,-1)])])}const Bn=Oo(Y$,[["render",X$]]),G$={class:"wov-menu-button"},J$=["innerHTML"],Q$=["onClick"],e4=["innerHTML"],jf=d.defineComponent({__name:"ArrowHeadButton",props:{entityIds:{},side:{}},setup(t){const e=t,{nextEditorTick:n}=tt(),r=d.shallowRef(null),o=d.computed(()=>{const a=r.value??(e.side==="start"?Te.None:Te.V);return zs(a)});n(a=>{let l=null;for(const c of e.entityIds){if(O(a,c,Ce)){const u=Ce.read(a,c),f=e.side==="start"?u.startArrowHead:u.endArrowHead;if(l===null)l=f;else if(f!==l){r.value=e.side==="start"?Te.None:Te.V;return}}if(O(a,c,we)){const u=we.read(a,c),f=e.side==="start"?u.startArrowHead:u.endArrowHead;if(l===null)l=f;else if(f!==l){r.value=e.side==="start"?Te.None:Te.V;return}}}r.value=l});function s(a){r.value=a,n(l=>{for(const c of e.entityIds){if(O(l,c,Ce)){const u=Ce.write(l,c);e.side==="start"?u.startArrowHead=a:u.endArrowHead=a}if(O(l,c,we)){const u=we.write(l,c);e.side==="start"?u.startArrowHead=a:u.endArrowHead=a}}})}function i(a){if(!a)return"";const l=e.side==="start";return`<line x1="${l?8:4}" y1="12" x2="${l?20:16}" y2="12" stroke="currentColor" stroke-width="2" stroke-linecap="round" /><g transform="${`translate(${l?4:20}, 12) scale(${l?"-0.8, 0.8":"0.8"})`}">${a.svg}</g>`}return(a,l)=>(d.openBlock(),d.createBlock(In,{title:t.side==="start"?"Start Arrow Head":"End Arrow Head"},{button:d.withCtx(()=>[d.createElementVNode("div",G$,[(d.openBlock(),d.createElementBlock("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",innerHTML:i(o.value)},null,8,J$)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(d.unref(ud),c=>(d.openBlock(),d.createElementBlock("button",{key:c.kind,class:d.normalizeClass(["wov-menu-option",{"is-active":r.value===c.kind}]),onClick:u=>s(c.kind)},[(d.openBlock(),d.createElementBlock("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",innerHTML:i(c)},null,8,e4))],10,Q$))),128))]),_:1},8,["title"]))}}),t4={class:"wov-menu-button"},n4=["onClick"],nv=d.defineComponent({__name:"ArrowThicknessButton",props:{entityIds:{}},setup(t){const e=[{label:"S",value:2},{label:"M",value:4},{label:"L",value:8}],n=t,{nextEditorTick:r}=tt(),o=d.shallowRef(null);r(i=>{let a=null;for(const l of n.entityIds){if(O(i,l,Ce)){const c=Ce.read(i,l);if(a===null)a=c.thickness;else if(c.thickness!==a){o.value=null;return}}if(O(i,l,we)){const c=we.getThickness(i,l);if(a===null)a=c;else if(c!==a){o.value=null;return}}}o.value=a});function s(i){o.value=i,r(a=>{for(const l of n.entityIds){if(O(a,l,Ce)){const c=Ce.write(a,l);c.thickness=i}O(a,l,we)&&we.setThickness(a,l,i)}})}return(i,a)=>(d.openBlock(),d.createBlock(In,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",t4,[a[0]||(a[0]=d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-linecap":"round"},[d.createElementVNode("line",{x1:"4",y1:"5",x2:"20",y2:"5","stroke-width":"1"}),d.createElementVNode("line",{x1:"4",y1:"11",x2:"20",y2:"11","stroke-width":"2.5"}),d.createElementVNode("line",{x1:"4",y1:"19",x2:"20",y2:"19","stroke-width":"4"})],-1)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(e,l=>d.createElementVNode("button",{key:l.value,class:d.normalizeClass(["wov-menu-option wov-arrow-thickness-option",{"is-active":o.value===l.value}]),onClick:c=>s(l.value)},d.toDisplayString(l.label),11,n4)),64))]),_:1}))}}),r4=["value"],o4=d.defineComponent({__name:"ColorInput",props:{modelValue:{}},emits:["update:modelValue"],setup(t,{emit:e}){const n=t,r=e,o=d.ref(n.modelValue??"");d.watch(()=>n.modelValue,u=>{u&&u!==o.value&&(o.value=u)});function s(u){const f=u.startsWith("#")?u:`#${u}`;return/^#[0-9A-Fa-f]{6}$/.test(f)}function i(u){return(u.startsWith("#")?u:`#${u}`).toLowerCase()}function a(u){let h=u.target.value;if((h.length===6||h.length===7)&&s(h)){const p=i(h);o.value=p,r("update:modelValue",p)}}function l(u){const h=u.target.value;if(h&&s(h)){const p=i(h);o.value=p,r("update:modelValue",p)}else n.modelValue&&(o.value=n.modelValue)}function c(u){if(u.stopPropagation(),u.key==="Enter"){const f=u.target,h=f.value;if(h&&s(h)){const p=i(h);o.value=p,r("update:modelValue",p),setTimeout(()=>f.select())}}}return(u,f)=>(d.openBlock(),d.createElementBlock("input",{id:"wov-color-input",class:"wov-color-input",type:"text",size:"1","aria-label":"Hex color value",autocomplete:"off",autocorrect:"off",autocapitalize:"off",spellcheck:"false",value:o.value,onInput:a,onChange:l,onKeydown:c},null,40,r4))}}),rv=d.defineComponent({__name:"ColorSlider",props:{modelValue:{},thumbColor:{},background:{}},emits:["update:modelValue"],setup(t,{expose:e,emit:n}){const r=n,o=d.ref(null),s=d.ref(!1);function i(c){s.value=!0,a(c),window.addEventListener("pointermove",a),window.addEventListener("pointerup",l)}function a(c){if(!o.value)return;const u=o.value.getBoundingClientRect(),f=Math.max(0,Math.min(100,(c.clientY-u.top)/u.height*100));r("update:modelValue",f)}function l(){s.value=!1,window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",l)}return e({isDragging:s}),(c,u)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"sliderRef",ref:o,class:"wov-color-slider",onPointerdown:d.withModifiers(i,["prevent"])},[t.background?(d.openBlock(),d.createElementBlock("div",{key:0,class:"wov-color-slider-gradient",style:d.normalizeStyle({background:t.background})},null,4)):d.createCommentVNode("",!0),d.createElementVNode("div",{class:"wov-color-slider-thumb",style:d.normalizeStyle({top:`${t.modelValue}%`,backgroundColor:t.thumbColor})},null,4)],544))}}),s4={class:"wov-color-picker"},i4={class:"wov-color-picker-area"},a4={class:"wov-color-picker-selector-gradient"},l4="linear-gradient(to bottom, red 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red 100%)",ov=d.defineComponent({__name:"ColorPicker",props:{modelValue:{},withOpacity:{type:Boolean}},emits:["update:modelValue"],setup(t,{emit:e}){const n=t,r=e,o=d.ref(null),s=d.ref(null),i=d.ref(null),a=d.ref({x:100,y:0}),l=d.ref(0),c=d.ref(0),u=d.ref(!1),f=d.computed(()=>{var E,T;return u.value||((E=o.value)==null?void 0:E.isDragging)||((T=s.value)==null?void 0:T.isDragging)}),h=d.computed(()=>({h:l.value/100*360,s:a.value.x,v:100-a.value.y,a:(100-c.value)/100*255})),p=d.computed(()=>xk({h:h.value.h,s:100,v:100})),m=d.computed(()=>xk({h:h.value.h,s:h.value.s,v:h.value.v})),g=d.computed(()=>n.withOpacity?Tk(h.value):m.value),y=d.computed(()=>`linear-gradient(to top, transparent 0%, ${m.value} 100%)`);function w(E){if(E){const T=Ck(E);a.value={x:T.s,y:100-T.v},l.value=T.h/360*100,c.value=100-T.a/255*100}}function k(E){w(E),r("update:modelValue",n.withOpacity?Tk(Ck(E)):E)}w(n.modelValue),d.watch(()=>n.modelValue,E=>{f.value||w(E)}),d.watch([a,l,c],()=>{f.value&&r("update:modelValue",g.value)});function b(E){u.value=!0,S(E),window.addEventListener("pointermove",S),window.addEventListener("pointerup",v)}function S(E){if(!i.value)return;const T=i.value.getBoundingClientRect(),_=Math.max(0,Math.min(100,(E.clientX-T.left)/T.width*100)),I=Math.max(0,Math.min(100,(E.clientY-T.top)/T.height*100));a.value={x:_,y:I}}function v(){u.value=!1,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",v)}return(E,T)=>(d.openBlock(),d.createElementBlock("div",s4,[d.createVNode(o4,{modelValue:g.value,"onUpdate:modelValue":k},null,8,["modelValue"]),d.createElementVNode("div",i4,[d.createElementVNode("div",{ref_key:"selectorRef",ref:i,class:"wov-color-picker-selector",style:d.normalizeStyle({backgroundColor:p.value}),onPointerdown:d.withModifiers(b,["prevent"])},[d.createElementVNode("div",a4,[d.createElementVNode("div",{class:"wov-color-picker-selector-thumb",style:d.normalizeStyle({left:`${a.value.x}%`,top:`${a.value.y}%`,backgroundColor:m.value})},null,4)])],36),d.createVNode(rv,{ref_key:"hueSliderRef",ref:o,modelValue:l.value,"onUpdate:modelValue":T[0]||(T[0]=_=>l.value=_),thumbColor:p.value,background:l4},null,8,["modelValue","thumbColor"]),t.withOpacity?(d.openBlock(),d.createBlock(rv,{key:0,ref_key:"opacitySliderRef",ref:s,modelValue:c.value,"onUpdate:modelValue":T[1]||(T[1]=_=>c.value=_),thumbColor:m.value,background:y.value,class:"wov-color-picker-opacity"},null,8,["modelValue","thumbColor","background"])):d.createCommentVNode("",!0)])]))}}),c4={class:"wov-color-bubbles-container"},u4={key:1,class:"wov-color-bubbles"},d4=["onClick"],Cc=d.defineComponent({__name:"ColorBubbles",props:{currentColor:{},palette:{},hideHighlight:{type:Boolean},withPicker:{type:Boolean},withOpacity:{type:Boolean}},emits:["change","picker-open"],setup(t,{emit:e}){const n=t,r=e,o=["#000000","#374151","#6B7280","#9CA3AF","#D1D5DB","#FFFFFF","#EF4444","#F97316","#EAB308","#22C55E","#14B8A6","#3B82F6","#8B5CF6","#EC4899"],s=d.computed(()=>{const m=n.palette??o,g=n.withPicker,y=m.length%2===1;return g&&!y||!g&&y?m.slice(0,-1):m}),i=d.ref(!1),a=d.ref(n.currentColor??"#ff0000");function l(m,g){const y=w=>{const k=w.replace(/^#/,"").toLowerCase();return k.length===6?k+"ff":k};return y(m)===y(g)}function c(m){return n.hideHighlight||!n.currentColor?!1:l(n.currentColor,m)}function u(){return n.hideHighlight||!n.currentColor?!1:!s.value.some(m=>l(n.currentColor,m))}function f(m){const g=If(m);g&&r("change",g)}function h(){!i.value&&n.currentColor&&(a.value=n.currentColor),i.value=!i.value,r("picker-open",i.value)}function p(m){a.value=m;const g=If(m);g&&r("change",g)}return(m,g)=>(d.openBlock(),d.createElementBlock("div",c4,[i.value?(d.openBlock(),d.createBlock(ov,{key:0,modelValue:a.value,"onUpdate:modelValue":[g[0]||(g[0]=y=>a.value=y),p],withOpacity:t.withOpacity},null,8,["modelValue","withOpacity"])):(d.openBlock(),d.createElementBlock("div",u4,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(s.value,y=>(d.openBlock(),d.createElementBlock("div",{key:y,class:d.normalizeClass(["wov-color-bubble",{selected:c(y)}]),style:d.normalizeStyle({backgroundColor:y}),onMousedown:g[1]||(g[1]=d.withModifiers(()=>{},["prevent"])),onClick:w=>f(y)},null,46,d4))),128)),t.withPicker?(d.openBlock(),d.createElementBlock("div",{key:0,class:d.normalizeClass(["wov-color-bubble wov-rainbow-bubble",{selected:u()}]),onMousedown:g[2]||(g[2]=d.withModifiers(()=>{},["prevent"])),onClick:h},null,34)):d.createCommentVNode("",!0)]))]))}}),f4={class:"wov-color-button"},sv=d.defineComponent({__name:"ColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=tt(),r=yo(()=>e.entityIds,yn),o=d.computed(()=>{const c=new Set;for(const u of r.value.values())if(u){const f=ra(u);c.add(f)}return Array.from(c)}),s=d.computed(()=>o.value.length>1),i=d.computed(()=>o.value[0]??null),a=d.computed(()=>{if(o.value.length===0)return{backgroundColor:"#000"};if(o.value.length>=2){const c=o.value[0],u=o.value[1];return{background:`linear-gradient(45deg, ${c} 0%, ${c} 50%, ${u} 50%, ${u} 100%)`}}return{backgroundColor:o.value[0]}});function l(c){const u=ra(c);n(f=>{for(const h of e.entityIds)yn.fromHex(f,h,u)})}return(c,u)=>(d.openBlock(),d.createBlock(In,{title:"Color"},{button:d.withCtx(()=>[d.createElementVNode("div",f4,[d.createElementVNode("div",{class:"wov-color-swatch",style:d.normalizeStyle(a.value)},null,4),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Cc,{currentColor:i.value??void 0,hideHighlight:s.value,withPicker:!0,onChange:l},null,8,["currentColor","hideHighlight"])]),_:1}))}}),ni=d.defineComponent({__name:"MenuButton",props:{title:{}},emits:["click"],setup(t,{emit:e}){const n=t,r=e,o=d.ref(null),{show:s,hide:i}=ko();function a(u){r("click",u)}function l(){n.title&&o.value&&s(n.title,o.value)}function c(){i()}return(u,f)=>(d.openBlock(),d.createElementBlock("button",{ref_key:"buttonRef",ref:o,class:"wov-menu-button",onClick:a,onMouseenter:l,onMouseleave:c},[d.renderSlot(u.$slots,"default")],544))}}),Zf=d.defineComponent({__name:"MenuTooltip",setup(t){const{activeTooltip:e,isVisible:n}=ko(),r=d.inject("containerRef"),o=d.ref(null),s=d.computed(()=>{var l;return((l=e.value)==null?void 0:l.anchor)??null}),{floatingStyles:i}=Ec(s,o,{placement:"top",middleware:[vc(8),Sc({fallbackPlacements:["bottom"]}),bc({padding:8})]}),a=d.computed(()=>{var l;return n.value&&((l=e.value)==null?void 0:l.text)});return(l,c)=>d.unref(r)?(d.openBlock(),d.createBlock(d.Teleport,{key:0,to:d.unref(r)},[d.createVNode(d.Transition,{name:"wov-tooltip-fade"},{default:d.withCtx(()=>{var u;return[a.value?(d.openBlock(),d.createElementBlock("div",{key:0,ref_key:"tooltipRef",ref:o,class:"wov-menu-tooltip",style:d.normalizeStyle(d.unref(i))},d.toDisplayString((u=d.unref(e))==null?void 0:u.text),5)):d.createCommentVNode("",!0)]}),_:1})],8,["to"])):d.createCommentVNode("",!0)}}),h4={class:"wov-menu-button"},p4=["onClick"],iv=d.defineComponent({__name:"PenStrokeThicknessButton",props:{entityIds:{}},setup(t){const e=[{label:"S",value:4},{label:"M",value:8},{label:"L",value:16}],n=t,{nextEditorTick:r}=tt(),o=yo(()=>n.entityIds,Wn),s=d.computed(()=>{let a=null;for(const l of o.value.values())if(l){if(a===null)a=l.thickness;else if(l.thickness!==a)return null}return a});function i(a){r(l=>{for(const c of n.entityIds){const u=Wn.write(l,c);u.thickness=a}})}return(a,l)=>(d.openBlock(),d.createBlock(In,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",h4,[l[0]||(l[0]=d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-linecap":"round"},[d.createElementVNode("line",{x1:"4",y1:"5",x2:"20",y2:"5","stroke-width":"1"}),d.createElementVNode("line",{x1:"4",y1:"11",x2:"20",y2:"11","stroke-width":"2.5"}),d.createElementVNode("line",{x1:"4",y1:"19",x2:"20",y2:"19","stroke-width":"4"})],-1)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(e,c=>d.createElementVNode("button",{key:c.value,class:d.normalizeClass(["wov-menu-option wov-pen-thickness-option",{"is-active":s.value===c.value}]),onClick:u=>i(c.value)},d.toDisplayString(c.label),11,p4)),64))]),_:1}))}}),m4={class:"wov-fill-color-button"},g4={class:"wov-fill-dropdown"},y4={key:0,class:"wov-fill-mode-section"},w4=["title","onClick"],k4={viewBox:"0 0 24 24",fill:"none"},v4=["fill","fill-opacity","stroke","stroke-width","stroke-dasharray"],av=d.defineComponent({__name:"ShapeFillColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=tt(),r=yo(()=>e.entityIds,wn),o=[{mode:"solid",label:"Solid",alpha:255},{mode:"faded",label:"Faded",alpha:128},{mode:"none",label:"None",alpha:0}],s=d.computed(()=>{const p=r.value.values().next().value,m=(p==null?void 0:p.fillAlpha)??255;return m===0?"none":m<200?"faded":"solid"}),i=d.computed(()=>{const p=new Set;for(const m of r.value.values())if(m){const g=m.fillAlpha??255;g===0?p.add("none"):g<200?p.add("faded"):p.add("solid")}return p.size>1});function a(p){n(m=>{for(const g of e.entityIds){const y=wn.write(m,g);y.fillAlpha=p}})}const l=d.computed(()=>{const p=new Set;for(const m of r.value.values())if(m){const g=ra({red:m.fillRed,green:m.fillGreen,blue:m.fillBlue,alpha:m.fillAlpha??255});p.add(g)}return Array.from(p)}),c=d.computed(()=>l.value.length>1),u=d.computed(()=>l.value[0]??"#4a90d9");function f(p){n(m=>{for(const g of e.entityIds){const y=wn.write(m,g);y.fillRed=p.red,y.fillGreen=p.green,y.fillBlue=p.blue,y.fillAlpha=p.alpha}})}const h=d.ref(!1);return(p,m)=>(d.openBlock(),d.createBlock(In,{title:"Fill Color"},{button:d.withCtx(()=>[d.createElementVNode("div",m4,[m[1]||(m[1]=d.createElementVNode("svg",{viewBox:"0 0 20 20",class:"wov-fill-color-icon",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},[d.createElementVNode("path",{d:"M5.879,2.625L14.121,2.625C15.906,2.625 17.375,4.094 17.375,5.879L17.375,14.121C17.375,15.906 15.906,17.375 14.121,17.375L5.88,17.375C4.095,17.375 2.626,15.906 2.626,14.121L2.626,5.88C2.626,4.095 4.095,2.626 5.88,2.626L5.879,2.625Z","stroke-width":"1.25"}),d.createElementVNode("path",{d:"M2.779,14.655L14.543,2.871M10.238,17.308L17.318,10.229M2.876,9.577L9.853,2.6M5.397,17.239L17.16,5.476","stroke-width":"1.25"})],-1)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",g4,[h.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",y4,[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(o,g=>d.createElementVNode("button",{key:g.mode,class:d.normalizeClass(["wov-fill-mode-option",{"is-active":!i.value&&g.mode===s.value}]),title:g.label,onClick:y=>a(g.alpha)},[(d.openBlock(),d.createElementBlock("svg",k4,[d.createElementVNode("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",fill:g.mode==="none"?"none":"currentColor","fill-opacity":g.mode==="faded"?.4:1,stroke:g.mode==="none"?"currentColor":"none","stroke-width":g.mode==="none"?1.5:0,"stroke-dasharray":g.mode==="none"?"3 3":""},null,8,v4)])),d.createElementVNode("span",null,d.toDisplayString(g.label),1)],10,w4)),64))])),d.createVNode(Cc,{currentColor:u.value,hideHighlight:c.value,withPicker:!0,withOpacity:!0,onChange:f,onPickerOpen:m[0]||(m[0]=g=>h.value=g)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),b4={class:"wov-shape-kind-button"},S4={class:"wov-shape-kind-dropdown"},E4=["onClick"],C4={viewBox:"0 0 20 20",class:"wov-shape-option-icon",fill:"none",stroke:"currentColor","stroke-width":"4"},x4=["d"],lv=d.defineComponent({__name:"ShapeKindButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=tt(),r=yo(()=>e.entityIds,wn),o=d.computed(()=>{const l=r.value.values().next().value;return(l==null?void 0:l.kind)??"rectangle"}),s=d.computed(()=>{const l=new Set;for(const c of r.value.values())c&&l.add(c.kind);return l.size>1}),i=d.computed(()=>Object.keys(Di).map(l=>({kind:l,label:l.charAt(0).toUpperCase()+l.slice(1)})));function a(l){n(c=>{for(const u of e.entityIds){const f=wn.write(c,u);f.kind=l}})}return(l,c)=>(d.openBlock(),d.createBlock(In,{title:"Shape Type"},{button:d.withCtx(()=>[d.createElementVNode("div",b4,[c[0]||(c[0]=d.createElementVNode("svg",{viewBox:"0 0 20 20",class:"wov-shape-kind-icon",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[d.createElementVNode("circle",{cx:"6",cy:"6",r:"5"}),d.createElementVNode("rect",{x:"6",y:"6",width:"10",height:"10",fill:"var(--wov-gray-600)"})],-1)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",S4,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(i.value,u=>(d.openBlock(),d.createElementBlock("button",{key:u.kind,class:d.normalizeClass(["wov-shape-kind-option",{"is-selected":!s.value&&u.kind===o.value}]),onClick:f=>a(u.kind)},[(d.openBlock(),d.createElementBlock("svg",C4,[d.createElementVNode("path",{d:d.unref(Di)[u.kind],transform:"translate(2, 2) scale(0.16)"},null,8,x4)])),d.createElementVNode("span",null,d.toDisplayString(u.label),1)],10,E4))),128))])]),_:1}))}}),T4={class:"wov-stroke-style-section"},M4=["title","onClick"],A4={viewBox:"0 0 24 8",fill:"none",stroke:"currentColor","stroke-width":"2"},_4=["stroke-dasharray","stroke-opacity"],I4=d.defineComponent({__name:"StrokeStyleOptions",props:{currentStyle:{},hasMultipleStyles:{type:Boolean}},emits:["change"],setup(t,{emit:e}){const n=e,r=[{kind:ht.Solid,label:"Solid"},{kind:ht.Dashed,label:"Dashed"},{kind:ht.None,label:"None"}];function o(i){switch(i){case ht.Dashed:return"6 6";case ht.None:return"";case ht.Solid:default:return""}}function s(i){n("change",i)}return(i,a)=>(d.openBlock(),d.createElementBlock("div",T4,[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(r,l=>d.createElementVNode("button",{key:l.kind,class:d.normalizeClass(["wov-stroke-style-option",{"is-active":!t.hasMultipleStyles&&l.kind===t.currentStyle}]),title:l.label,onClick:c=>s(l.kind)},[(d.openBlock(),d.createElementBlock("svg",A4,[d.createElementVNode("line",{x1:"2",y1:"4",x2:"22",y2:"4","stroke-linecap":"round","stroke-dasharray":o(l.kind),"stroke-opacity":l.kind===d.unref(ht).None?.3:1},null,8,_4)])),d.createElementVNode("span",null,d.toDisplayString(l.label),1)],10,M4)),64))]))}}),B4={class:"wov-stroke-color-button"},N4={class:"wov-stroke-dropdown"},P4={key:1,class:"wov-stroke-divider"},cv=d.defineComponent({__name:"ShapeStrokeColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=tt(),r=yo(()=>e.entityIds,wn),o=d.ref(!1),s=d.computed(()=>{const h=new Set;for(const p of r.value.values())if(p){const m=ra({red:p.strokeRed,green:p.strokeGreen,blue:p.strokeBlue,alpha:255});h.add(m)}return Array.from(h)}),i=d.computed(()=>s.value.length>1),a=d.computed(()=>s.value[0]??"#000000"),l=d.computed(()=>{const h=r.value.values().next().value;return(h==null?void 0:h.strokeKind)??ht.Solid}),c=d.computed(()=>{const h=new Set;for(const p of r.value.values())p&&h.add(p.strokeKind);return h.size>1});function u(h){n(p=>{for(const m of e.entityIds){const g=wn.write(p,m);g.strokeRed=h.red,g.strokeGreen=h.green,g.strokeBlue=h.blue}})}function f(h){n(p=>{for(const m of e.entityIds){const g=wn.write(p,m);g.strokeKind=h}})}return(h,p)=>(d.openBlock(),d.createBlock(In,{title:"Stroke Color"},{button:d.withCtx(()=>[d.createElementVNode("div",B4,[p[1]||(p[1]=d.createElementVNode("svg",{viewBox:"0 0 20 20",class:"wov-stroke-color-icon",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round"},[d.createElementVNode("path",{d:"M2.5 12.563c1.655-.886 5.9-3.293 8.568-4.355 2.668-1.062.101 2.822 1.32 3.105 1.218.283 5.112-1.814 5.112-1.814m-13.469 2.23c2.963-1.586 6.13-5.62 7.468-4.998 1.338.623-1.153 4.11-.132 5.595 1.02 1.487 6.133-1.43 6.133-1.43","stroke-width":"1.25"})],-1)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",N4,[o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createBlock(I4,{key:0,currentStyle:l.value,hasMultipleStyles:c.value,onChange:f},null,8,["currentStyle","hasMultipleStyles"])),o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",P4)),d.createVNode(Cc,{currentColor:a.value,hideHighlight:i.value,withPicker:!0,onChange:u,onPickerOpen:p[0]||(p[0]=m=>o.value=m)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),D4={key:0,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},O4={key:1,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},R4={key:2,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},z4={key:3,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},Kf=d.defineComponent({__name:"TextAlignmentButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds),o=[kn.Left,kn.Center,kn.Right,kn.Justify];function s(){const i=o.indexOf(n.alignment),a=o[(i+1)%o.length];r.setAlignment(a)}return(i,a)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(ni,{key:0,title:"Text Align",onClick:s},{default:d.withCtx(()=>[d.unref(n).alignment===d.unref(kn).Left?(d.openBlock(),d.createElementBlock("svg",D4,[...a[0]||(a[0]=[d.createElementVNode("path",{d:"M288 64c0 17.7-14.3 32-32 32L32 96C14.3 96 0 81.7 0 64S14.3 32 32 32l224 0c17.7 0 32 14.3 32 32zm0 256c0 17.7-14.3 32-32 32L32 352c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zM0 192c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 224c-17.7 0-32-14.3-32-32zM448 448c0 17.7-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z"},null,-1)])])):d.unref(n).alignment===d.unref(kn).Center?(d.openBlock(),d.createElementBlock("svg",O4,[...a[1]||(a[1]=[d.createElementVNode("path",{d:"M352 64c0-17.7-14.3-32-32-32L128 32c-17.7 0-32 14.3-32 32s14.3 32 32 32l192 0c17.7 0 32-14.3 32-32zm96 128c0-17.7-14.3-32-32-32L32 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l384 0c17.7 0 32-14.3 32-32zM0 448c0 17.7 14.3 32 32 32l384 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L32 416c-17.7 0-32 14.3-32 32zM352 320c0-17.7-14.3-32-32-32l-192 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l192 0c17.7 0 32-14.3 32-32z"},null,-1)])])):d.unref(n).alignment===d.unref(kn).Right?(d.openBlock(),d.createElementBlock("svg",R4,[...a[2]||(a[2]=[d.createElementVNode("path",{d:"M448 64c0 17.7-14.3 32-32 32L192 96c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zm0 256c0 17.7-14.3 32-32 32l-224 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l224 0c17.7 0 32 14.3 32 32zM0 192c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 224c-17.7 0-32-14.3-32-32zM448 448c0 17.7-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l384 0c17.7 0 32 14.3 32 32z"},null,-1)])])):(d.openBlock(),d.createElementBlock("svg",z4,[...a[3]||(a[3]=[d.createElementVNode("path",{d:"M448 64c0-17.7-14.3-32-32-32L32 32C14.3 32 0 46.3 0 64S14.3 96 32 96l384 0c17.7 0 32-14.3 32-32zm0 256c0-17.7-14.3-32-32-32L32 288c-17.7 0-32 14.3-32 32s14.3 32 32 32l384 0c17.7 0 32-14.3 32-32zM0 192c0 17.7 14.3 32 32 32l384 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L32 160c-17.7 0-32 14.3-32 32zM448 448c0-17.7-14.3-32-32-32L32 416c-17.7 0-32 14.3-32 32s14.3 32 32 32l384 0c17.7 0 32-14.3 32-32z"},null,-1)])]))]),_:1})):d.createCommentVNode("",!0)}}),Yf=d.defineComponent({__name:"TextBoldButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(ni,{key:0,title:"Bold",class:d.normalizeClass({"wov-active":d.unref(n).isBold}),onClick:d.unref(r).toggleBold},{default:d.withCtx(()=>[...s[0]||(s[0]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",fill:"currentColor"},[d.createElementVNode("path",{d:"M0 64C0 46.3 14.3 32 32 32l48 0 16 0 128 0c70.7 0 128 57.3 128 128c0 31.3-11.3 60.1-30 82.3c37.1 22.4 62 63.1 62 109.7c0 70.7-57.3 128-128 128L96 480l-16 0-48 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l16 0 0-160L48 96 32 96C14.3 96 0 81.7 0 64zM224 224c35.3 0 64-28.7 64-64s-28.7-64-64-64L112 96l0 128 112 0zM112 288l0 128 144 0c35.3 0 64-28.7 64-64s-28.7-64-64-64l-32 0-112 0z"})],-1)])]),_:1},8,["class","onClick"])):d.createCommentVNode("",!0)}});function $4(t,e){return d.getCurrentScope()?(d.onScopeDispose(t,e),!0):!1}const L4=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const V4=Object.prototype.toString,F4=t=>V4.call(t)==="[object Object]",xc=()=>{};function Tc(t){return Array.isArray(t)?t:[t]}function W4(t){return d.getCurrentInstance()}function U4(t,e=!0,n){W4()?d.onMounted(t,n):e?t():d.nextTick(t)}function H4(t,e,n){return d.watch(t,e,{...n,immediate:!0})}const Mc=L4?window:void 0;function Kn(t){var e;const n=d.toValue(t);return(e=n==null?void 0:n.$el)!==null&&e!==void 0?e:n}function qf(...t){const e=(r,o,s,i)=>(r.addEventListener(o,s,i),()=>r.removeEventListener(o,s,i)),n=d.computed(()=>{const r=Tc(d.toValue(t[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return H4(()=>{var r,o;return[(r=(o=n.value)===null||o===void 0?void 0:o.map(s=>Kn(s)))!==null&&r!==void 0?r:[Mc].filter(s=>s!=null),Tc(d.toValue(n.value?t[1]:t[0])),Tc(d.unref(n.value?t[2]:t[1])),d.toValue(n.value?t[3]:t[2])]},([r,o,s,i],a,l)=>{if(!(r!=null&&r.length)||!(o!=null&&o.length)||!(s!=null&&s.length))return;const c=F4(i)?{...i}:i,u=r.flatMap(f=>o.flatMap(h=>s.map(p=>e(f,h,p,c))));l(()=>{u.forEach(f=>f())})},{flush:"post"})}function j4(t,e,n={}){const{window:r=Mc,ignore:o=[],capture:s=!0,detectIframe:i=!1,controls:a=!1}=n;if(!r)return a?{stop:xc,cancel:xc,trigger:xc}:xc;let l=!0;const c=y=>d.toValue(o).some(w=>{if(typeof w=="string")return Array.from(r.document.querySelectorAll(w)).some(k=>k===y.target||y.composedPath().includes(k));{const k=Kn(w);return k&&(y.target===k||y.composedPath().includes(k))}});function u(y){const w=d.toValue(y);return w&&w.$.subTree.shapeFlag===16}function f(y,w){const k=d.toValue(y),b=k.$.subTree&&k.$.subTree.children;return b==null||!Array.isArray(b)?!1:b.some(S=>S.el===w.target||w.composedPath().includes(S.el))}const h=y=>{const w=Kn(t);if(y.target!=null&&!(!(w instanceof Element)&&u(t)&&f(t,y))&&!(!w||w===y.target||y.composedPath().includes(w))){if("detail"in y&&y.detail===0&&(l=!c(y)),!l){l=!0;return}e(y)}};let p=!1;const m=[qf(r,"click",y=>{p||(p=!0,setTimeout(()=>{p=!1},0),h(y))},{passive:!0,capture:s}),qf(r,"pointerdown",y=>{const w=Kn(t);l=!c(y)&&!!(w&&!y.composedPath().includes(w))},{passive:!0}),i&&qf(r,"blur",y=>{setTimeout(()=>{var w;const k=Kn(t);((w=r.document.activeElement)===null||w===void 0?void 0:w.tagName)==="IFRAME"&&!(k!=null&&k.contains(r.document.activeElement))&&e(y)},0)},{passive:!0})].filter(Boolean),g=()=>m.forEach(y=>y());return a?{stop:g,cancel:()=>{l=!1},trigger:y=>{l=!0,h(y),l=!1}}:g}function Z4(){const t=d.shallowRef(!1),e=d.getCurrentInstance();return e&&d.onMounted(()=>{t.value=!0},e),t}function K4(t){const e=Z4();return d.computed(()=>(e.value,!!t()))}function Y4(t,e,n={}){const{window:r=Mc,...o}=n;let s;const i=K4(()=>r&&"ResizeObserver"in r),a=()=>{s&&(s.disconnect(),s=void 0)},l=d.watch(d.computed(()=>{const u=d.toValue(t);return Array.isArray(u)?u.map(f=>Kn(f)):[Kn(u)]}),u=>{if(a(),i.value&&r){s=new ResizeObserver(e);for(const f of u)f&&s.observe(f,o)}},{immediate:!0,flush:"post"}),c=()=>{a(),l()};return $4(c),{isSupported:i,stop:c}}function uv(t,e={width:0,height:0},n={}){const{window:r=Mc,box:o="content-box"}=n,s=d.computed(()=>{var f;return(f=Kn(t))===null||f===void 0||(f=f.namespaceURI)===null||f===void 0?void 0:f.includes("svg")}),i=d.shallowRef(e.width),a=d.shallowRef(e.height),{stop:l}=Y4(t,([f])=>{const h=o==="border-box"?f.borderBoxSize:o==="content-box"?f.contentBoxSize:f.devicePixelContentBoxSize;if(r&&s.value){const p=Kn(t);if(p){const m=p.getBoundingClientRect();i.value=m.width,a.value=m.height}}else if(h){const p=Tc(h);i.value=p.reduce((m,{inlineSize:g})=>m+g,0),a.value=p.reduce((m,{blockSize:g})=>m+g,0)}else i.value=f.contentRect.width,a.value=f.contentRect.height},n);U4(()=>{const f=Kn(t);f&&(i.value="offsetWidth"in f?f.offsetWidth:e.width,a.value="offsetHeight"in f?f.offsetHeight:e.height)});const c=d.watch(()=>Kn(t),f=>{i.value=f?e.width:0,a.value=f?e.height:0});function u(){l(),c()}return{width:i,height:a,stop:u}}function dv(){const t=d.inject(En);if(!t)throw new Error("useFonts must be used within a WovenCanvas component");return d.computed(()=>{const e=t.getEditor();return e?e.fonts.filter(n=>n.selectable):[]})}const q4={class:"wov-font-family-button"},X4={class:"wov-font-family-label"},G4={class:"wov-font-list"},J4=["onClick"],Q4=["src","alt"],Xf=d.defineComponent({__name:"TextFontFamilyButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds),o=dv(),s=d.computed(()=>o.value.map(u=>({name:u.name,displayName:u.displayName,previewImage:u.previewImage}))),i=d.computed(()=>n.fontFamily),a=d.computed(()=>{const u=i.value;if(u===null)return"Mixed";const f=s.value.find(h=>h.name===u);return(f==null?void 0:f.displayName)??u});function l(u){r.setFontFamily(u)}function c(u){u.stopPropagation()}return(u,f)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(In,{key:0,title:"Font Family"},{button:d.withCtx(()=>[d.createElementVNode("div",q4,[d.createElementVNode("span",X4,d.toDisplayString(a.value),1),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",{class:"wov-font-family-menu",onWheel:c,onClick:f[0]||(f[0]=d.withModifiers(()=>{},["stop"]))},[d.createElementVNode("div",G4,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(s.value,h=>(d.openBlock(),d.createElementBlock("div",{key:h.name,class:d.normalizeClass(["wov-font-item",{active:i.value===h.name}]),onClick:p=>l(h.name)},[h.previewImage?(d.openBlock(),d.createElementBlock("img",{key:0,class:"wov-font-preview",src:h.previewImage,alt:h.name},null,8,Q4)):(d.openBlock(),d.createElementBlock("span",{key:1,class:"wov-font-name",style:d.normalizeStyle({fontFamily:h.name})},d.toDisplayString(h.displayName),5))],10,J4))),128))])],32)]),_:1})):d.createCommentVNode("",!0)}}),eL={class:"wov-font-size-button"},tL={class:"wov-font-size-label"},nL=["onClick"],rL={key:0,class:"wov-check-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},oL={class:"wov-input-container"},sL=["value"],Gf=d.defineComponent({__name:"TextFontSizeButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds),o=[{label:"Small",value:16,displayValue:10},{label:"Medium",value:24,displayValue:12},{label:"Large",value:40,displayValue:16},{label:"Huge",value:96,displayValue:20}],s=d.computed(()=>n.fontSize),i=d.computed(()=>{const h=s.value;if(h===null)return"Mixed";const p=o.find(m=>m.value===h);return p?p.label:`${+h.toFixed(1)} px`}),a=d.computed(()=>{const h=s.value;return h===null?"":String(+h.toFixed(1))});function l(h){r.setFontSize(h)}function c(h){const p=h.target,m=Number.parseFloat(p.value);!Number.isNaN(m)&&m>0&&l(m)}function u(h){h.key==="Enter"&&h.target.blur()}function f(h){h.stopPropagation()}return(h,p)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(In,{key:0,title:"Font Size"},{button:d.withCtx(()=>[d.createElementVNode("div",eL,[d.createElementVNode("span",tL,d.toDisplayString(i.value),1),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",{class:"wov-font-size-menu",onWheel:f,onClick:p[0]||(p[0]=d.withModifiers(()=>{},["stop"]))},[(d.openBlock(),d.createElementBlock(d.Fragment,null,d.renderList(o,m=>d.createElementVNode("div",{key:m.value,class:d.normalizeClass(["wov-font-size-option",{active:s.value===m.value}]),onClick:g=>l(m.value)},[s.value===m.value?(d.openBlock(),d.createElementBlock("svg",rL,[...p[1]||(p[1]=[d.createElementVNode("path",{d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"},null,-1)])])):d.createCommentVNode("",!0),d.createElementVNode("span",{class:"wov-option-label",style:d.normalizeStyle({fontSize:`${m.displayValue}px`})},d.toDisplayString(m.label),5)],10,nL)),64)),p[3]||(p[3]=d.createElementVNode("div",{class:"wov-separator"},null,-1)),d.createElementVNode("div",oL,[d.createElementVNode("input",{class:"wov-custom-input",value:a.value,onInput:c,onKeydown:u,placeholder:"Custom size"},null,40,sL),p[2]||(p[2]=d.createElementVNode("span",{class:"wov-px-suffix"},"px",-1))])],32)]),_:1})):d.createCommentVNode("",!0)}}),Jf=d.defineComponent({__name:"TextItalicButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(ni,{key:0,title:"Italic",class:d.normalizeClass({"wov-active":d.unref(n).isItalic}),onClick:d.unref(r).toggleItalic},{default:d.withCtx(()=>[...s[0]||(s[0]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 384 512",fill:"currentColor"},[d.createElementVNode("path",{d:"M128 64c0-17.7 14.3-32 32-32l192 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-58.7 0L160 416l64 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32s14.3-32 32-32l58.7 0L224 96l-64 0c-17.7 0-32-14.3-32-32z"})],-1)])]),_:1},8,["class","onClick"])):d.createCommentVNode("",!0)}}),Qf=d.defineComponent({__name:"TextUnderlineButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(ni,{key:0,title:"Underline",class:d.normalizeClass({"wov-active":d.unref(n).isUnderline}),onClick:d.unref(r).toggleUnderline},{default:d.withCtx(()=>[...s[0]||(s[0]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},[d.createElementVNode("path",{d:"M16 64c0-17.7 14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 53 43 96 96 96s96-43 96-96l0-128-16 0c-17.7 0-32-14.3-32-32s14.3-32 32-32l96 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-16 0 0 128c0 88.4-71.6 160-160 160s-160-71.6-160-160L64 96 48 96C30.3 96 16 81.7 16 64zM0 448c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 480c-17.7 0-32-14.3-32-32z"})],-1)])]),_:1},8,["class","onClick"])):d.createCommentVNode("",!0)}}),iL={class:"wov-text-color-button"},aL={class:"wov-text-icon-container"},eh=d.defineComponent({__name:"TextColorButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=ar(()=>e.entityIds),o=d.computed(()=>n.color??"#000000"),s=d.computed(()=>({backgroundColor:o.value}));function i(a){r.setColor(ra(a))}return(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(In,{key:0,title:"Text Color"},{button:d.withCtx(()=>[d.createElementVNode("div",iL,[d.createElementVNode("div",aL,[l[0]||(l[0]=d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 640",fill:"currentColor",class:"wov-text-icon"},[d.createElementVNode("path",{d:"M349.1 114.7C343.9 103.3 332.5 96 320 96C307.5 96 296.1 103.3 290.9 114.7L123.5 480L112 480C94.3 480 80 494.3 80 512C80 529.7 94.3 544 112 544L200 544C217.7 544 232 529.7 232 512C232 494.3 217.7 480 200 480L193.9 480L215.9 432L424.2 432L446.2 480L440.1 480C422.4 480 408.1 494.3 408.1 512C408.1 529.7 422.4 544 440.1 544L528.1 544C545.8 544 560.1 529.7 560.1 512C560.1 494.3 545.8 480 528.1 480L516.6 480L349.2 114.7zM394.8 368L245.2 368L320 204.8L394.8 368z"})],-1)),d.createElementVNode("div",{class:"wov-color-underline",style:d.normalizeStyle(s.value)},null,4)]),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Cc,{currentColor:o.value,withPicker:!0,onChange:i},null,8,["currentColor"])]),_:1})):d.createCommentVNode("",!0)}}),lL={key:0,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-align-vertical-justify-start-icon lucide-align-vertical-justify-start"},cL={key:1,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-align-vertical-justify-center-icon lucide-align-vertical-justify-center"},uL={key:2,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-align-vertical-justify-end-icon lucide-align-vertical-justify-end"},fv=d.defineComponent({__name:"VerticalAlignButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=tt(),{state:r}=ar(()=>e.entityIds),o=[it.Top,it.Center,it.Bottom],s=yo(()=>e.entityIds,No),i=d.computed(()=>{let l=null;for(const c of s.value.values()){const u=(c==null?void 0:c.value)??it.Top;if(l===null)l=u;else if(l!==u)return null}return l});function a(){const l=i.value??it.Top,c=o.indexOf(l),u=o[(c+1)%o.length];n(f=>{for(const h of e.entityIds){const p=No.write(f,h);p.value=u}})}return(l,c)=>d.unref(r).showTextMenuButtons?(d.openBlock(),d.createBlock(ni,{key:0,title:"Vertical Align",onClick:a},{default:d.withCtx(()=>[i.value===d.unref(it).Top||i.value===null?(d.openBlock(),d.createElementBlock("svg",lL,[...c[0]||(c[0]=[d.createElementVNode("rect",{width:"14",height:"6",x:"5",y:"16",rx:"2"},null,-1),d.createElementVNode("rect",{width:"10",height:"6",x:"7",y:"6",rx:"2"},null,-1),d.createElementVNode("path",{d:"M2 2h20"},null,-1)])])):i.value===d.unref(it).Center?(d.openBlock(),d.createElementBlock("svg",cL,[...c[1]||(c[1]=[d.createElementVNode("rect",{width:"14",height:"6",x:"5",y:"16",rx:"2"},null,-1),d.createElementVNode("rect",{width:"10",height:"6",x:"7",y:"2",rx:"2"},null,-1),d.createElementVNode("path",{d:"M2 12h20"},null,-1)])])):(d.openBlock(),d.createElementBlock("svg",uL,[...c[2]||(c[2]=[d.createElementVNode("rect",{width:"14",height:"6",x:"5",y:"12",rx:"2"},null,-1),d.createElementVNode("rect",{width:"10",height:"6",x:"7",y:"2",rx:"2"},null,-1),d.createElementVNode("path",{d:"M2 22h20"},null,-1)])]))]),_:1})):d.createCommentVNode("",!0)}}),dL={class:"wov-text-group-button"},fL={class:"wov-text-group-dropdown"},hL={class:"wov-text-group-row wov-text-group-row-full"},pL={class:"wov-text-group-row"},mL=d.defineComponent({__name:"TextButtonGroup",props:{entityIds:{},showVerticalAlign:{type:Boolean}},setup(t){const e=t,{state:n}=ar(()=>e.entityIds),r=d.inject("containerRef"),{width:o}=uv(r),s=d.computed(()=>o.value>0&&o.value<600),i=d.ref(new Map);return d.provide(fy,i),(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createElementBlock(d.Fragment,{key:0},[s.value?(d.openBlock(),d.createBlock(In,{key:0,title:"Text Formatting",placement:"top"},{button:d.withCtx(()=>[d.createElementVNode("div",dL,[l[0]||(l[0]=d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 640",fill:"currentColor",class:"wov-text-group-icon"},[d.createElementVNode("path",{d:"M349.1 114.7C343.9 103.3 332.5 96 320 96C307.5 96 296.1 103.3 290.9 114.7L123.5 480L112 480C94.3 480 80 494.3 80 512C80 529.7 94.3 544 112 544L200 544C217.7 544 232 529.7 232 512C232 494.3 217.7 480 200 480L193.9 480L215.9 432L424.2 432L446.2 480L440.1 480C422.4 480 408.1 494.3 408.1 512C408.1 529.7 422.4 544 440.1 544L528.1 544C545.8 544 560.1 529.7 560.1 512C560.1 494.3 545.8 480 528.1 480L516.6 480L349.2 114.7zM394.8 368L245.2 368L320 204.8L394.8 368z"})],-1)),d.createVNode(Bn,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",fL,[d.createElementVNode("div",hL,[d.createVNode(Xf,{entityIds:t.entityIds},null,8,["entityIds"]),l[1]||(l[1]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(Gf,{entityIds:t.entityIds},null,8,["entityIds"])]),d.createElementVNode("div",pL,[d.createVNode(Yf,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Jf,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Qf,{entityIds:t.entityIds},null,8,["entityIds"]),l[2]||(l[2]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(eh,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Kf,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(fv,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)])])]),_:1})):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createVNode(Xf,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Gf,{entityIds:t.entityIds},null,8,["entityIds"]),l[3]||(l[3]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(Yf,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Jf,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Qf,{entityIds:t.entityIds},null,8,["entityIds"]),l[4]||(l[4]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(eh,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(Kf,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(fv,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)],64))],64)):d.createCommentVNode("",!0)}}),hv=d.defineComponent({__name:"CanvasBackground",props:{background:{}},setup(t){const e=t,n=Nt(he),r=Nt(Ot),o=d.inject("containerRef"),s=d.ref({width:0,height:0});let i=null;const a=d.ref(null);let l=null;typeof document<"u"&&(l=document.createElement("canvas"));function c(y,w,k,b){const S=b/2;y.beginPath(),y.arc(w,k,S,0,Math.PI*2),y.fill()}function u(y,w,k){if(!l)return null;const b=k.dotSize??2,S=y*k.subdivisionStep,v=w*k.subdivisionStep;l.width=S,l.height=v;const E=l.getContext("2d");if(!E)return null;if(E.clearRect(0,0,S,v),E.fillStyle=k.strokeColor,k.subdivisionStep===1)c(E,S/2,v/2,b);else for(let T=0;T<k.subdivisionStep;T++)for(let _=0;_<k.subdivisionStep;_++){const I=(T+.5)*(S/k.subdivisionStep),z=(_+.5)*(v/k.subdivisionStep),j=T===0&&_===0?2*b:b;c(E,I,z,j)}return E.createPattern(l,"repeat")}function f(y,w,k,b,S,v){y.lineWidth=v,y.beginPath(),y.moveTo(w,k),y.lineTo(b,S),y.stroke()}function h(y,w,k){if(!l)return null;const b=k.gridSize??1,S=y*k.subdivisionStep,v=w*k.subdivisionStep;l.width=S,l.height=v;const E=l.getContext("2d");if(!E)return null;if(E.clearRect(0,0,S,v),E.strokeStyle=k.strokeColor,k.subdivisionStep===1)f(E,0,0,S,0,b),f(E,0,0,0,v,b);else{const T=S/k.subdivisionStep,_=v/k.subdivisionStep;for(let I=0;I<=k.subdivisionStep;I++){const z=I*T,F=I%k.subdivisionStep===0;f(E,z,0,z,v,F?3*b:b)}for(let I=0;I<=k.subdivisionStep;I++){const z=I*_,F=I%k.subdivisionStep===0;f(E,0,z,S,z,F?3*b:b)}}return E.createPattern(l,"repeat")}function p(y){let w=r.value.colWidth,k=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,v=s.value.height,E=n.value.left,T=n.value.top,_=E+S/n.value.zoom,I=T+v/n.value.zoom;let z=w*b,F=k*b,j=0,M=0,V=Number.POSITIVE_INFINITY,K=Number.POSITIVE_INFINITY;for(;;){z=b*w,F=b*k,j=Math.floor(E/z)*z,M=Math.floor(T/F)*F;const Ue=Math.ceil(_/z)*z,Yn=Math.ceil(I/F)*F;if(K=Math.round((Ue-j)/w),V=Math.round((Yn-M)/k),Math.max(K,V)>200)w*=2,k*=2;else break}const se=w*n.value.zoom,Y=k*n.value.zoom,R=Math.round(se),W=Math.round(Y),Q=u(R,W,e.background);if(!Q)return;Q.setTransform(new DOMMatrix().scale(se/R,Y/W));const pe=(j-E-w/2)*n.value.zoom,me=(M-T-k/2)*n.value.zoom;y.save(),y.translate(pe,me),y.fillStyle=Q,y.fillRect(0,0,S+z*n.value.zoom,v+F*n.value.zoom),y.restore()}function m(y){let w=r.value.colWidth,k=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,v=s.value.height,E=n.value.left,T=n.value.top,_=E+S/n.value.zoom,I=T+v/n.value.zoom;let z=w*b,F=k*b,j=0,M=0,V=Number.POSITIVE_INFINITY,K=Number.POSITIVE_INFINITY;for(;;){z=b*w,F=b*k,j=Math.floor(E/z)*z,M=Math.floor(T/F)*F;const Ue=Math.ceil(_/z)*z,Yn=Math.ceil(I/F)*F;if(K=Math.round((Ue-j)/w),V=Math.round((Yn-M)/k),Math.max(K,V)>200)w*=2,k*=2;else break}const se=w*n.value.zoom,Y=k*n.value.zoom,R=Math.round(se),W=Math.round(Y),Q=h(R,W,e.background);if(!Q)return;Q.setTransform(new DOMMatrix().scale(se/R,Y/W));const pe=(j-E)*n.value.zoom,me=(M-T)*n.value.zoom;y.save(),y.translate(pe,me),y.fillStyle=Q,y.fillRect(0,0,S+z*n.value.zoom,v+F*n.value.zoom),y.restore()}function g(){const y=a.value;if(!y)return;const w=y.getContext("2d");if(!w)return;const{width:k,height:b}=s.value;k===0||b===0||(y.width=k,y.height=b,w.clearRect(0,0,k,b),w.fillStyle=e.background.color,w.fillRect(0,0,k,b),e.background.kind==="dots"?p(w):e.background.kind==="grid"&&m(w))}return d.watch(()=>[e.background,n.value,r.value,s.value],()=>{g()},{deep:!0}),d.onMounted(()=>{const y=o==null?void 0:o.value;if(y){const w=()=>{s.value={width:y.clientWidth,height:y.clientHeight}};w(),i=new ResizeObserver(w),i.observe(y)}g()}),d.onUnmounted(()=>{i==null||i.disconnect()}),(y,w)=>(d.openBlock(),d.createElementBlock("canvas",{ref_key:"canvasRef",ref:a,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none"}},null,512))}});function pv(t,e){if(e.length===0)return new Set;const n=e[0].tag,r=t.blockDefs[n];if(!r)return new Set;const o=new Set(r.components.map(s=>s.name));for(let s=1;s<e.length;s++){const i=e[s].tag,a=t.blockDefs[i];if(!a){o.clear();break}const l=new Set(a.components.map(c=>c.name));for(const c of o)l.has(c)||o.delete(c)}return o}const mv=d.defineComponent({__name:"FloatingMenuBar",setup(t){const e=d.useSlots(),{reset:n}=ko(),r=d.inject(py),{selectedIds:o,commonComponents:s}=r,i=new Set(["color","text","verticalAlign","penStroke","elbowArrow","arcArrow","shape"]),a=d.computed(()=>{const c=[];for(const u of s.value){const f=`button:${u}`;!i.has(u)&&e[f]&&c.push(u)}return c});function l(){n()}return d.onUnmounted(()=>{n()}),(c,u)=>(d.openBlock(),d.createElementBlock("div",{class:"wov-floating-menu-bar",onMouseleave:l},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(a.value,f=>d.renderSlot(c.$slots,`button:${f}`,{key:f,entityIds:d.unref(o)})),128)),d.renderSlot(c.$slots,"button:color",{entityIds:d.unref(o)},()=>[d.unref(s).has("color")?(d.openBlock(),d.createBlock(sv,{key:0,entityIds:d.unref(o)},null,8,["entityIds"])):d.createCommentVNode("",!0)]),d.renderSlot(c.$slots,"button:shape",{entityIds:d.unref(o)},()=>[d.unref(s).has("shape")?(d.openBlock(),d.createElementBlock(d.Fragment,{key:0},[d.createVNode(lv,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(av,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(cv,{entityIds:d.unref(o)},null,8,["entityIds"])],64)):d.createCommentVNode("",!0)]),d.renderSlot(c.$slots,"button:penStroke",{entityIds:d.unref(o)},()=>[d.unref(s).has("penStroke")?(d.openBlock(),d.createBlock(iv,{key:0,entityIds:d.unref(o)},null,8,["entityIds"])):d.createCommentVNode("",!0)]),d.renderSlot(c.$slots,"button:arrowThickness",{entityIds:d.unref(o)},()=>[d.unref(s).has("elbowArrow")||d.unref(s).has("arcArrow")?(d.openBlock(),d.createBlock(nv,{key:0,entityIds:d.unref(o)},null,8,["entityIds"])):d.createCommentVNode("",!0)]),d.renderSlot(c.$slots,"button:arrowHeadStart",{entityIds:d.unref(o)},()=>[d.unref(s).has("elbowArrow")||d.unref(s).has("arcArrow")?(d.openBlock(),d.createBlock(jf,{key:0,entityIds:d.unref(o),side:"start"},null,8,["entityIds"])):d.createCommentVNode("",!0)]),d.renderSlot(c.$slots,"button:arrowHeadEnd",{entityIds:d.unref(o)},()=>[d.unref(s).has("elbowArrow")||d.unref(s).has("arcArrow")?(d.openBlock(),d.createBlock(jf,{key:0,entityIds:d.unref(o),side:"end"},null,8,["entityIds"])):d.createCommentVNode("",!0)]),d.renderSlot(c.$slots,"button:text",{entityIds:d.unref(o)},()=>[d.unref(s).has("text")?(d.openBlock(),d.createBlock(mL,{key:0,entityIds:d.unref(o),showVerticalAlign:d.unref(s).has("verticalAlign")},null,8,["entityIds","showVerticalAlign"])):d.createCommentVNode("",!0)]),d.createVNode(Zf)],32))}}),gL={class:"wov-floating-menu-inner"},gv=d.defineComponent({__name:"FloatingMenu",setup(t){const e=d.inject(En),n=Sk([A,pt]),r=Nt(he),o=Nt(Mt),s=Nt(zn),i=oa(),a=d.computed(()=>n.value.map(S=>S.entityId)),l=d.computed(()=>{const S=e==null?void 0:e.getEditor();if(!S||n.value.length===0)return new Set;const v=n.value.map(E=>({tag:E.block.value.tag}));return pv(S,v)});d.provide(py,{selectedIds:a,commonComponents:l});const c=[0,0,0,0];function u(...S){let v=1/0,E=1/0,T=-1/0,_=-1/0,I=!1;for(const z of S){if(!z)continue;const F=z.getBoundingClientRect();F.width<=0||(I=!0,v=Math.min(v,F.left),E=Math.min(E,F.top),T=Math.max(T,F.right),_=Math.max(_,F.bottom))}return I?{x:v,y:E,left:v,top:E,right:T,bottom:_,width:T-v,height:_-E,toJSON:()=>({})}:null}const f=d.computed(()=>{if(n.value.length===0)return null;const S=r.value;if(!S)return null;let v=null;for(const E of n.value){const T=E.block.value;st.getAabb(T.position,T.size,T.rotateZ,c),ee.translate(c,[-S.left,-S.top]),ee.scale(c,S.zoom),v===null?v=ee.clone(c):ee.union(v,c)}return v}),h=d.inject("containerRef"),p=d.computed(()=>{const S=h==null?void 0:h.value;if(!S)return null;r.value,i.updateCounter.value;const v=i.blockElement.value,E=i.textElement.value,T=u(v,E);if(T)return{getBoundingClientRect:()=>T};const _=f.value;if(!_)return null;const I=S.getBoundingClientRect();return{getBoundingClientRect(){return{x:I.left+_[0],y:I.top+_[1],width:_[2]-_[0],height:_[3]-_[1],top:I.top+_[1],left:I.left+_[0],right:I.left+_[2],bottom:I.top+_[3]}}}}),m=d.ref(null),g={name:"clampToViewport",fn({y:S,rects:v}){const _=window.innerHeight-v.floating.height-8;return{y:Math.max(8,Math.min(S,_))}}},{floatingStyles:y}=Ec(p,m,{placement:"top",middleware:[vc(12),Sc({fallbackPlacements:["bottom"]}),bc({padding:8}),g]}),w=d.computed(()=>{const S=f.value,v=o.value;return!S||!v?!0:S[2]<0||S[0]>v.width||S[3]<0||S[1]>v.height}),k=[ye.Dragging,ye.SelectionBoxDragging],b=d.computed(()=>n.value.length>0&&!w.value&&!k.includes(s.value.state));return(S,v)=>(d.openBlock(),d.createBlock(d.Transition,{name:"wov-fade"},{default:d.withCtx(()=>[b.value?(d.openBlock(),d.createElementBlock("div",{key:0,ref_key:"floatingRef",ref:m,class:"wov-floating-menu",style:d.normalizeStyle(d.unref(y))},[d.createElementVNode("div",gL,[d.renderSlot(S.$slots,"default",{},()=>[d.createVNode(mv)])])],4)):d.createCommentVNode("",!0)]),_:3}))}}),yL={key:0,class:"wov-loading-overlay"},wL={class:"wov-loading-spinner"},yv=d.defineComponent({__name:"LoadingOverlay",props:{isLoading:{type:Boolean}},setup(t){const e=d.ref("|"),n=["|","/","-","\\"];let r=null;return d.onMounted(()=>{r=setInterval(()=>{const o=n.indexOf(e.value);e.value=n[(o+1)%n.length]},100)}),d.onUnmounted(()=>{r!==null&&clearInterval(r)}),(o,s)=>(d.openBlock(),d.createBlock(d.Transition,{name:"wov-loading-fade"},{default:d.withCtx(()=>[t.isLoading?(d.openBlock(),d.createElementBlock("div",yL,[d.createElementVNode("div",wL,d.toDisplayString(e.value),1)])):d.createCommentVNode("",!0)]),_:1}))}}),kL={class:"wov-action-bar"},vL=d.defineComponent({__name:"ActionBar",setup(t){const{getEditor:e}=tt(),n=d.inject(En),r=d.ref(!1),o=d.ref(!1);if(n){const l=n.registerTickCallback(c=>{const{store:u}=As(c,"editing");r.value=u.canUndo(),o.value=u.canRedo()});d.onUnmounted(l)}function s(){const l=e();l==null||l.command(Ou)}function i(){const l=e();l==null||l.command(Ya)}function a(){const l=e();l==null||l.command(Vu)}return(l,c)=>(d.openBlock(),d.createElementBlock("div",kL,[d.createElementVNode("button",{class:"wov-action-button",onClick:s,"aria-label":"Undo"},[...c[0]||(c[0]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-undo-icon lucide-undo"},[d.createElementVNode("path",{d:"M3 7v6h6"}),d.createElementVNode("path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"})],-1)])]),d.createElementVNode("button",{class:"wov-action-button",onClick:i,"aria-label":"Redo"},[...c[1]||(c[1]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-redo-icon lucide-redo"},[d.createElementVNode("path",{d:"M21 7v6h-6"}),d.createElementVNode("path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7"})],-1)])]),d.createElementVNode("button",{class:"wov-action-button",onClick:a,"aria-label":"Delete"},[...c[2]||(c[2]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-trash-icon lucide-trash"},[d.createElementVNode("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}),d.createElementVNode("path",{d:"M3 6h18"}),d.createElementVNode("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})],-1)])])]))}}),dr=d.defineComponent({__name:"ToolbarButton",props:{name:{},tooltip:{},dragOutSnapshot:{},placementSnapshot:{},cursor:{default:"crosshair"}},setup(t){const e=t,n=d.inject(dd);if(!n)throw new Error("ToolbarButton must be used within a Toolbar component");const r=n,o=d.ref(null),{show:s,hide:i}=ko(),a=d.computed(()=>r.activeTool.value===e.name);function l(){r.setTool(e.name,e.placementSnapshot,e.cursor)}function c(){r.onToolPointerDown(e.name,e.dragOutSnapshot)}function u(){r.onToolPointerUp()}function f(){e.tooltip&&o.value&&s(e.tooltip,o.value)}function h(){i()}return(p,m)=>(d.openBlock(),d.createElementBlock("button",{ref_key:"buttonRef",ref:o,class:d.normalizeClass(["wov-toolbar-button",{selected:a.value}]),onClick:l,onPointerdown:c,onPointerup:u,onMouseenter:f,onMouseleave:h},[d.renderSlot(p.$slots,"default")],34))}}),bL='<?xml version="1.0" encoding="UTF-8"?><svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4.35 4.75" width="20" height="20"><defs><style>.cls-1{stroke:#fff;stroke-miterlimit:10;stroke-width:.25px;}</style></defs><path class="cls-1" d="M2.39,2.88s-.04.01-.05.02c-.01,0-.02.01-.03.02,0,.01-.02.02-.03.05l-.77,1.44c-.07.13-.1.19-.14.2-.03.01-.07,0-.1-.01-.03-.02-.05-.09-.09-.23L.16.41c-.03-.13-.05-.19-.03-.23.02-.03.04-.05.08-.06.04,0,.1.02.21.08l3.59,1.94c.13.07.19.1.2.14.01.03,0,.07-.01.1-.02.03-.09.05-.23.09l-1.58.4Z"/></svg>',SL='<?xml version="1.0" encoding="UTF-8"?><svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4.08 4.75" width="24" height="24"><defs><style>.cls-1{fill:#fff;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:.25px;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;stroke-width:.51px;}</style></defs><path class="cls-1" d="M.89,2.25v.63M.89,2.25V.75c0-.21.17-.38.38-.38s.38.17.38.38M.89,2.25c0-.21-.17-.37-.38-.37s-.38.17-.38.37v.5c0,1.04.86,1.87,1.91,1.87s1.91-.84,1.91-1.87v-1.25c0-.21-.17-.38-.38-.38s-.38.17.38.38M1.66.75v1.38M1.66.75v-.25c0-.21.17-.38.38-.38s.38.17.38.38v.25M2.42.75v1.38M2.42.75c0-.21.17-.38.38-.38s.38.17.38.38v.75M3.19,1.5v.63"/><line class="cls-2" x1="2.8" y1=".77" x2="2.8" y2="2.03"/><line class="cls-2" x1="2.04" y1=".64" x2="2.04" y2="2.02"/><line class="cls-2" x1="1.27" y1=".84" x2="1.27" y2="2.29"/></svg>',EL='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 8v-2a2 2 0 0 1 2 -2h2" /><path d="M4 16v2a2 2 0 0 0 2 2h2" /><path d="M16 4h2a2 2 0 0 1 2 2v2" /><path d="M16 20h2a2 2 0 0 0 2 -2v-2" /><path d="M9 12l6 0" /><path d="M12 9l0 6" /></svg>',is={Select:"select",Hand:"hand",Crosshair:"crosshair"},wv={[is.Select]:{makeSvg:()=>bL,hotspot:[1,0],rotationOffset:0},[is.Hand]:{makeSvg:()=>SL,hotspot:[12,12],rotationOffset:0},[is.Crosshair]:{makeSvg:()=>EL,hotspot:[12,12],rotationOffset:0}},CL={viewBox:"0 0 20 20",style:{"fill-rule":"evenodd","clip-rule":"evenodd","stroke-miterlimit":"10"}},kv=d.defineComponent({__name:"SelectTool",setup(t){const{nextEditorTick:e}=tt(),{activeTool:n}=zf();return d.watch(n,(r,o)=>{o==="select"&&e(s=>{Ps.spawn(s)})}),(r,o)=>(d.openBlock(),d.createBlock(dr,{name:"select",tooltip:"Select",cursor:d.unref(is).Select},{default:d.withCtx(()=>[(d.openBlock(),d.createElementBlock("svg",CL,[...o[0]||(o[0]=[d.createElementVNode("g",{transform:"matrix(4.21053,0,0,4.21053,0.842105,0)"},[d.createElementVNode("path",{fill:"none",stroke:"currentColor","stroke-width":"0.5",d:"M2.39,2.88C2.38,2.885 2.34,2.9 2.33,2.91C2.32,2.91 2.298,2.939 2.28,2.97L1.51,4.41C1.44,4.54 1.41,4.6 1.37,4.61C1.34,4.62 1.3,4.61 1.27,4.6C1.24,4.58 1.22,4.51 1.18,4.37L0.16,0.41C0.13,0.28 0.11,0.22 0.13,0.18C0.15,0.15 0.17,0.13 0.21,0.12C0.25,0.12 0.31,0.14 0.42,0.2L4.01,2.14C4.14,2.21 4.2,2.24 4.21,2.28C4.22,2.31 4.21,2.35 4.2,2.38C4.18,2.41 4.11,2.43 3.97,2.47L2.39,2.88Z"})],-1)])]))]),_:1},8,["cursor"]))}}),vv=d.defineComponent({__name:"HandTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(dr,{name:"hand",tooltip:"Hand",cursor:d.unref(is).Hand},{default:d.withCtx(()=>[...n[0]||(n[0]=[d.createElementVNode("svg",{viewBox:"0 0 20.56 24"},[d.createElementVNode("path",{fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4.47,11.39v3.18M4.47,11.39V3.81c0-1.06.86-1.92,1.92-1.92s1.92.86,1.92,1.92M4.47,11.39c0-1.06-.86-1.87-1.92-1.87s-1.92.86-1.92,1.87v2.53c0,5.25,4.35,9.45,9.65,9.45s9.65-4.24,9.65-9.45v-6.32c0-1.06-.86-1.92-1.92-1.92s-1.92.86-1.92,1.92M8.36,3.81v6.97M8.36,3.81v-1.26c0-1.06.86-1.92,1.92-1.92s1.92.86,1.92,1.92v1.26M12.2,3.81v6.97M12.2,3.81c0-1.06.86-1.92,1.92-1.92s1.92.86,1.92,1.92v3.79M16.09,7.6v3.18"})],-1)])]),_:1},8,["cursor"]))}}),bv=d.defineComponent({__name:"StickyNoteTool",setup(t){const e=JSON.stringify({block:{tag:"sticky-note",size:[200,200]},color:{red:255,green:242,blue:117},text:{defaultAlignment:kn.Center},verticalAlign:{value:it.Center}});return(n,r)=>(d.openBlock(),d.createBlock(dr,{name:"sticky-note",tooltip:"Sticky Note","drag-out-snapshot":d.unref(e),"placement-snapshot":d.unref(e)},{default:d.withCtx(()=>[...r[0]||(r[0]=[d.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[d.createElementVNode("path",{d:"M4 4h12v12H4z"}),d.createElementVNode("path",{d:"M7 8h6M7 11h4"})],-1)])]),_:1},8,["drag-out-snapshot","placement-snapshot"]))}}),Sv=d.defineComponent({__name:"ShapeTool",setup(t){const e=JSON.stringify({block:{tag:"shape",size:[200,200]},shape:{kind:"rectangle",strokeKind:ht.Solid,strokeWidth:2,strokeRed:0,strokeGreen:0,strokeBlue:0,strokeAlpha:255,fillRed:255,fillGreen:255,fillBlue:255,fillAlpha:0},text:{defaultAlignment:kn.Center},verticalAlign:{value:it.Center}});return(n,r)=>(d.openBlock(),d.createBlock(dr,{name:"shape",tooltip:"Shape","drag-out-snapshot":d.unref(e),"placement-snapshot":d.unref(e)},{default:d.withCtx(()=>[...r[0]||(r[0]=[d.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[d.createElementVNode("rect",{x:"3",y:"3",width:"14",height:"14",rx:"2"})],-1)])]),_:1},8,["drag-out-snapshot","placement-snapshot"]))}}),Ev=d.defineComponent({__name:"EraserTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(dr,{name:"eraser",tooltip:"Eraser"},{default:d.withCtx(()=>[...n[0]||(n[0]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 640",fill:"currentColor"},[d.createElementVNode("path",{d:"M210.5 480L333.5 480L398.8 414.7L225.3 241.2L98.6 367.9L210.6 479.9zM256 544L210.5 544C193.5 544 177.2 537.3 165.2 525.3L49 409C38.1 398.1 32 383.4 32 368C32 352.6 38.1 337.9 49 327L295 81C305.9 70.1 320.6 64 336 64C351.4 64 366.1 70.1 377 81L559 263C569.9 273.9 576 288.6 576 304C576 319.4 569.9 334.1 559 345L424 480L544 480C561.7 480 576 494.3 576 512C576 529.7 561.7 544 544 544L256 544z"})],-1)])]),_:1}))}}),Cv=d.defineComponent({__name:"PenTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(dr,{name:"pen",tooltip:"Pen"},{default:d.withCtx(()=>[...n[0]||(n[0]=[d.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[d.createElementVNode("path",{d:"M13.586 3.586a2 2 0 1 1 2.828 2.828l-8.793 8.793-3.536.707.707-3.536 8.794-8.792Z","stroke-linecap":"round","stroke-linejoin":"round"}),d.createElementVNode("path",{d:"M12 5l3 3","stroke-linecap":"round"})],-1)])]),_:1}))}}),xv=d.defineComponent({__name:"TextTool",setup(t){const e=JSON.stringify({block:{tag:"text",size:[10,29]},text:{constrainWidth:!1,fontSizePx:24}}),n=JSON.stringify({block:{tag:"text",size:[36,29]},text:{content:"text",constrainWidth:!1,fontSizePx:24}});return(r,o)=>(d.openBlock(),d.createBlock(dr,{name:"text",tooltip:"Text","drag-out-snapshot":d.unref(n),"placement-snapshot":d.unref(e)},{default:d.withCtx(()=>[...o[0]||(o[0]=[d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-type-icon lucide-type"},[d.createElementVNode("path",{d:"M12 4v16"}),d.createElementVNode("path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2"}),d.createElementVNode("path",{d:"M9 20h6"})],-1)])]),_:1},8,["drag-out-snapshot","placement-snapshot"]))}}),Tv=d.defineComponent({__name:"ElbowArrowTool",setup(t){const e=JSON.stringify({block:{tag:"elbow-arrow",size:[200,200]},elbowArrow:{points:[0,0,.5,0,.5,1,1,1],pointCount:4,startArrowHead:Te.None,endArrowHead:Te.V},connector:{}});return(n,r)=>(d.openBlock(),d.createBlock(dr,{name:"elbow-arrow",tooltip:"Elbow Arrow",cursor:"crosshair","drag-out-snapshot":d.unref(e)},{default:d.withCtx(()=>[...r[0]||(r[0]=[d.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[d.createElementVNode("path",{d:"M4 6 L10 6 L10 14 L16 14"}),d.createElementVNode("path",{d:"M13 11 L16 14 L13 17"})],-1)])]),_:1},8,["drag-out-snapshot"]))}}),Mv=d.defineComponent({__name:"ImageTool",setup(t){const{nextEditorTick:e}=tt(),{show:n,hide:r}=ko(),{setTool:o}=zf(),{createImageBlock:s}=bk(),i=d.ref(null),a=d.ref(null);function l(){var h;(h=a.value)==null||h.click()}async function c(h){var S;const p=h.target,m=(S=p.files)==null?void 0:S[0];if(!m)return;if(p.value="",!m.type.startsWith("image/")){console.warn("Selected file is not an image");return}const g=await e(),y=he.read(g),w=Mt.read(g),k=y.left+w.width/y.zoom/2,b=y.top+w.height/y.zoom/2;await s(m,k,b),o("select",void 0,is.Select)}function u(){i.value&&n("Image",i.value)}function f(){r()}return(h,p)=>(d.openBlock(),d.createElementBlock("button",{ref_key:"buttonRef",ref:i,class:"wov-toolbar-button",onClick:l,onMouseenter:u,onMouseleave:f},[p[0]||(p[0]=d.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[d.createElementVNode("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),d.createElementVNode("circle",{cx:"9",cy:"9",r:"2"}),d.createElementVNode("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})],-1)),d.createElementVNode("input",{ref_key:"fileInputRef",ref:a,type:"file",accept:"image/*",style:{display:"none"},onChange:c},null,544)],544))}}),xL={class:"wov-toolbar-container"},Av=d.defineComponent({__name:"Toolbar",setup(t){const e=d.useSlots(),{reset:n}=ko(),{nextEditorTick:r}=tt(),o=d.ref(null),s=d.ref(null),i=Nt(et),a=d.computed(()=>i.value.leftMouseTool),l=[kv,vv,xv,Mv,Sv,Tv,bv,Cv,Ev],c=d.inject("containerRef"),u=d.ref(null),f=d.ref(!1),h=d.ref(null),p=d.ref(null),m=d.ref(1/0),g=d.ref(0),y=d.ref([]),w=d.ref(8),k=d.ref(48),{width:b}=uv(c);function S(){return h.value?Array.from(h.value.children).filter(R=>!R.classList.contains("wov-overflow-button")&&!R.classList.contains("wov-menu-tooltip")):[]}function v(){var pe;const R=S();if(R.length===0)return;g.value=R.length;const W=getComputedStyle(h.value);w.value=parseFloat(W.gap)||8;const Q=((pe=p.value)==null?void 0:pe.offsetWidth)||40;k.value=Q+w.value,y.value=R.map(me=>me.offsetWidth)}function E(){if(y.value.length===0)return;const Q=b.value-40-20,pe=w.value,me=k.value;let Ue=0,Yn=0;for(let pr=0;pr<y.value.length;pr++){const So=y.value[pr],ri=Ue>0?So+pe:So,Pn=y.value.length-pr-1>0?me:0;if(Ue+ri+Pn<=Q)Ue+=ri,Yn++;else break}m.value=Math.max(1,Yn)}d.watch(b,()=>{y.value.length>0&&E()}),d.onMounted(()=>{d.nextTick(()=>{v(),E()})});const T=d.computed(()=>m.value<g.value);d.watchEffect(()=>{S().forEach((W,Q)=>{W.style.display=Q<m.value?"":"none"})}),d.watchEffect(()=>{if(!u.value)return;Array.from(u.value.children).forEach((W,Q)=>{W.style.display=Q>=m.value?"":"none"})});const{floatingStyles:_}=Ec(p,u,{placement:"top",middleware:[vc(16),Sc(),bc({padding:8})],whileElementsMounted:Jk});function I(){f.value=!f.value}function z(){f.value=!1}function F(R){const W=R.target;p.value&&!p.value.contains(W)&&u.value&&!u.value.contains(W)&&z()}d.watch(f,R=>{R?document.addEventListener("click",F,!0):document.removeEventListener("click",F,!0)}),d.watch(T,R=>{R||z()});function j(R,W,Q){s.value=W??null,r(pe=>{const me=et.write(pe);me.leftMouseTool=R,me.heldSnapshot=W??"",Q&&vn.setCursor(pe,Q)})}function M(R){r(W=>{const Q=et.write(W);Q.leftMouseTool="drag-out",Q.heldSnapshot=R})}function V(R,W){o.value=R,s.value=W??null}function K(){o.value=null,s.value=null}function se(){n(),o.value&&s.value&&M(s.value),o.value=null,s.value=null}const Y={activeTool:a,heldTool:o,setTool:j,dragOutTool:M,onToolPointerDown:V,onToolPointerUp:K};return d.provide(dd,Y),(R,W)=>(d.openBlock(),d.createElementBlock("div",xL,[d.createVNode(vL),d.createElementVNode("div",{ref_key:"toolsContainerRef",ref:h,class:"wov-toolbar",onMouseleave:se},[d.unref(e).default?d.renderSlot(R.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(Q,pe)=>d.createVNode(d.resolveDynamicComponent(Q),{key:pe})),64)),T.value?(d.openBlock(),d.createElementBlock("button",{key:2,ref_key:"overflowBtnRef",ref:p,class:d.normalizeClass(["wov-toolbar-button wov-overflow-button",{"menu-open":f.value}]),onClick:I},[...W[0]||(W[0]=[d.createElementVNode("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},[d.createElementVNode("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),d.createElementVNode("line",{x1:"5",y1:"12",x2:"19",y2:"12"})],-1)])],2)):d.createCommentVNode("",!0),d.createVNode(Zf)],544),d.unref(c)?(d.openBlock(),d.createBlock(d.Teleport,{key:0,to:d.unref(c)},[f.value&&T.value?(d.openBlock(),d.createElementBlock("div",{key:0,ref_key:"overflowMenuRef",ref:u,class:"wov-toolbar-overflow-menu",style:d.normalizeStyle(d.unref(_))},[d.unref(e).default?d.renderSlot(R.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(Q,pe)=>d.createVNode(d.resolveDynamicComponent(Q),{key:pe})),64))],4)):d.createCommentVNode("",!0)],8,["to"])):d.createCommentVNode("",!0)]))}}),TL=d.defineComponent({__name:"ArcArrowTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(dr,{name:"arc-arrow",tooltip:"Arc Arrow",cursor:"crosshair"},{default:d.withCtx(()=>[...n[0]||(n[0]=[d.createElementVNode("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[d.createElementVNode("path",{d:"M4 14 Q 10 4, 16 14"}),d.createElementVNode("path",{d:"M13 11 L16 14 L12.5 15.5"})],-1)])]),_:1}))}}),ML={class:"wov-user-presence-avatars"},AL=["src","alt"],_L={class:"wov-user-presence-list"},IL=["src","alt"],BL={class:"wov-user-presence-name"},NL=4,_v=d.defineComponent({__name:"UserPresence",props:{users:{}},setup(t){const e=t,n=d.ref(!1),r=d.ref(null);j4(r,()=>{n.value=!1});function o(a){if(!a)return"?";const l=a.trim().split(/\s+/);return l.length>=2?(l[0][0]+l[1][0]).toUpperCase():a.slice(0,2).toUpperCase()}const s=d.computed(()=>e.users.map(a=>({sessionId:a.sessionId,name:a.name,color:a.color,avatar:a.avatar,initials:o(a.name)}))),i=d.computed(()=>s.value.slice(0,NL));return(a,l)=>t.users.length>1?(d.openBlock(),d.createElementBlock("div",{key:0,ref_key:"containerRef",ref:r,class:"wov-user-presence"},[d.createElementVNode("button",{class:d.normalizeClass(["wov-user-presence-trigger",{"is-open":n.value}]),onClick:l[0]||(l[0]=c=>n.value=!n.value)},[d.createElementVNode("div",ML,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(i.value,c=>(d.openBlock(),d.createElementBlock("div",{key:c.sessionId,class:"wov-user-avatar",style:d.normalizeStyle({backgroundColor:c.avatar?"transparent":c.color})},[c.avatar?(d.openBlock(),d.createElementBlock("img",{key:0,src:c.avatar,alt:c.name,class:"wov-user-avatar-img"},null,8,AL)):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createTextVNode(d.toDisplayString(c.initials),1)],64))],4))),128))])],2),n.value?(d.openBlock(),d.createElementBlock("div",{key:0,class:"wov-user-presence-dropdown",onWheel:l[1]||(l[1]=d.withModifiers(()=>{},["stop"]))},[d.createElementVNode("div",_L,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(s.value,c=>(d.openBlock(),d.createElementBlock("div",{key:c.sessionId,class:"wov-user-presence-item"},[d.createElementVNode("div",{class:"wov-user-avatar wov-user-avatar-small",style:d.normalizeStyle({backgroundColor:c.avatar?"transparent":c.color})},[c.avatar?(d.openBlock(),d.createElementBlock("img",{key:0,src:c.avatar,alt:c.name,class:"wov-user-avatar-img"},null,8,IL)):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createTextVNode(d.toDisplayString(c.initials),1)],64))],4),d.createElementVNode("span",BL,d.toDisplayString(c.name),1)]))),128))])],32)):d.createCommentVNode("",!0)],512)):d.createCommentVNode("",!0)}});async function th(t,e){const n=await dh(t,1,{upgrade(r){r.objectStoreNames.contains(e)||r.createObjectStore(e)}});return new PL(n,e)}var PL=class{constructor(t,e){this.db=t,this.storeName=e}async get(t){return this.db.get(this.storeName,t)}async put(t,e){await this.db.put(this.storeName,e,t)}async delete(t){await this.db.delete(this.storeName,t)}async getAllEntries(){const e=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName),n=await e.getAllKeys(),r=await e.getAll(),o=[];for(let s=0;s<n.length;s++)o.push([n[s],r[s]]);return o}async clear(){const t=this.db.transaction(this.storeName,"readwrite");t.objectStore(this.storeName).clear(),await t.done}close(){this.db.close()}},DL=class{constructor(t){this.jobsStore=null,this.binariesStore=null,this.blobUrls=new Map,this.uploading=new Set,this.uploadPromises=new Map,this.provider=t.provider,this.documentId=t.documentId,this.maxRetries=t.provider.maxRetries??3,this.retryDelay=t.provider.retryDelay??5e3}async init(){const t=`wovencanvas-assets-${this.documentId}`,[e,n]=await Promise.all([th(`${t}-jobs`,"jobs"),th(`${t}-binaries`,"binaries")]);this.jobsStore=e,this.binariesStore=n}async upload(t,e,n){if(!this.jobsStore||!this.binariesStore)throw new Error("AssetManager not initialized");await this.binariesStore.put(t,e);const r={identifier:t,metadata:n,createdAt:Date.now(),retryCount:0};await this.jobsStore.put(t,r);const o=URL.createObjectURL(e);return this.blobUrls.set(t,o),new Promise((s,i)=>{this.uploadPromises.set(t,{resolve:s,reject:i}),this.startUpload(t)})}async getDisplayUrl(t){const e=this.blobUrls.get(t);if(e)return e;try{return await this.provider.resolveUrl(t)}catch(n){return console.error(`Failed to resolve URL for ${t}:`,n),null}}async resumePendingUploads(){if(!this.jobsStore||!this.binariesStore)throw new Error("AssetManager not initialized");const t=await this.jobsStore.getAllEntries();for(const[e]of t){const n=await this.binariesStore.get(e);if(n){const r=URL.createObjectURL(n);this.blobUrls.set(e,r)}this.startUpload(e)}}hasPendingUpload(t){return this.blobUrls.has(t)}isUploading(t){return this.uploading.has(t)}async cancelUpload(t){if(!this.jobsStore||!this.binariesStore)return;const e=this.blobUrls.get(t);e&&(URL.revokeObjectURL(e),this.blobUrls.delete(t)),await this.jobsStore.delete(t),await this.binariesStore.delete(t),this.uploading.delete(t);const n=this.uploadPromises.get(t);n&&(n.reject(new Error("Upload cancelled")),this.uploadPromises.delete(t))}close(){var t,e;for(const n of this.blobUrls.values())URL.revokeObjectURL(n);this.blobUrls.clear(),(t=this.jobsStore)==null||t.close(),(e=this.binariesStore)==null||e.close(),this.jobsStore=null,this.binariesStore=null}async startUpload(t){if(!this.jobsStore||!this.binariesStore||this.uploading.has(t))return;this.uploading.add(t);const e=await this.jobsStore.get(t),n=await this.binariesStore.get(t);if(!e||!n){this.uploading.delete(t);return}try{await this.provider.upload(n,t,e.metadata),await this.onUploadSuccess(t)}catch(r){await this.onUploadError(t,e,r)}}async onUploadSuccess(t){if(!this.jobsStore||!this.binariesStore)return;const e=this.blobUrls.get(t);e&&(URL.revokeObjectURL(e),this.blobUrls.delete(t)),await this.jobsStore.delete(t),await this.binariesStore.delete(t),this.uploading.delete(t);const n=this.uploadPromises.get(t);n&&(n.resolve(),this.uploadPromises.delete(t))}async onUploadError(t,e,n){if(!this.jobsStore)return;const r=n instanceof Error?n.message:"Unknown error";if(console.error(`Upload failed for ${t}:`,r),this.uploading.delete(t),e.retryCount<this.maxRetries){const o={...e,retryCount:e.retryCount+1};await this.jobsStore.put(t,o),setTimeout(()=>{this.startUpload(t)},this.retryDelay*2**e.retryCount)}else{const o=this.uploadPromises.get(t);o&&(o.reject(new Error(r)),this.uploadPromises.delete(t))}}},OL="wovencanvas-assets",RL="blobs",zL=class{constructor(){this.store=null,this.initPromise=null,this.maxRetries=3,this.retryDelay=5e3}async upload(t,e,n){return await(await this.getStore()).put(e,{blob:t,metadata:n}),{}}async resolveUrl(t){const n=await(await this.getStore()).get(t);if(!n)throw new Error(`Asset not found: ${t}`);return URL.createObjectURL(n.blob)}async delete(t){await(await this.getStore()).delete(t)}close(){this.store&&(this.store.close(),this.store=null,this.initPromise=null)}getStore(){return this.store?Promise.resolve(this.store):(this.initPromise||(this.initPromise=th(OL,RL).then(t=>(this.store=t,t))),this.initPromise)}},Iv=qt({minZoom:Je().default(.05),maxZoom:Je().default(2.7)});Iv.parse({});var nh=to("panState",{state:C.string().max(16).default("idle"),panStartX:C.float64().default(0),panStartY:C.float64().default(0),velocityX:C.float64().default(0),velocityY:C.float64().default(0),targetX:C.float64().default(0),targetY:C.float64().default(0),expectedLeft:C.float64().default(0),expectedTop:C.float64().default(0)}),Or=[0,0],Ac=[0,0],la=[0,0],rh=[0,0],oh=[0,0];function $L(t,e,n,r,o,s){r=Math.max(1e-4,r);const i=2/r,a=i*s,l=1/(1+a+.48*a*a+.235*a*a*a);L.copy(Or,t),L.sub(Or,e);const c=o*r,u=c*c,f=L.lengthSq(Or);f>u&&L.scale(Or,c/Math.sqrt(f)),L.copy(Ac,t),L.sub(Ac,Or),L.set(la,(n[0]+i*Or[0])*s,(n[1]+i*Or[1])*s);const h=[(n[0]-i*la[0])*l,(n[1]-i*la[1])*l],p=[Ac[0]+(Or[0]+la[0])*l,Ac[1]+(Or[1]+la[1])*l];return L.copy(rh,e),L.sub(rh,t),L.copy(oh,p),L.sub(oh,e),L.dot(rh,oh)>0&&(p[0]=e[0],p[1]=e[1],h[0]=(p[0]-e[0])/s,h[1]=(p[1]-e[1])/s),{position:p,velocity:h}}var sh=.1,Bv=.1,LL=br({guards:{hasVelocity:({event:t})=>{if(t.type!=="pointerUp")return!1;const e=t.velocity;return Math.hypot(e[0],e[1])>Bv},isGlideComplete:({context:t})=>Math.hypot(t.velocityX,t.velocityY)<Bv,cameraWasMoved:({context:t,event:e})=>{const n=he.read(e.ctx);return n.left!==t.expectedLeft||n.top!==t.expectedTop},isEscapeKey:({event:t})=>t.key===Gt.Escape},actions:{setDragStart:Re({panStartX:({event:t})=>t.worldPosition[0],panStartY:({event:t})=>t.worldPosition[1]}),moveCamera:({context:t,event:e})=>{const n=e,{ctx:r}=n,o=n.worldPosition[0]-t.panStartX,s=n.worldPosition[1]-t.panStartY,i=he.write(r);i.left-=o,i.top-=s},startGlide:Re(({event:t})=>{const e=t,{ctx:n}=e,r=he.read(n),o=e.cameraZoom,s=-e.velocity[0]/o,i=-e.velocity[1]/o;return{velocityX:s,velocityY:i,targetX:r.left+s*sh,targetY:r.top+i*sh,expectedLeft:r.left,expectedTop:r.top}}),animateGlide:Re(({context:t,event:e})=>{const n=e,{ctx:r,delta:o}=n,s=he.read(r),{position:i,velocity:a}=$L([s.left,s.top],[t.targetX,t.targetY],[t.velocityX,t.velocityY],sh,Number.POSITIVE_INFINITY,o),l=he.write(r);return l.left=i[0],l.top=i[1],{velocityX:a[0],velocityY:a[1],expectedLeft:i[0],expectedTop:i[1]}}),resetContext:Re({panStartX:0,panStartY:0,velocityX:0,velocityY:0,targetX:0,targetY:0,expectedLeft:0,expectedTop:0})}}).createMachine({id:"pan",initial:"idle",context:{panStartX:0,panStartY:0,velocityX:0,velocityY:0,targetX:0,targetY:0,expectedLeft:0,expectedTop:0},states:{idle:{on:{pointerDown:{actions:"setDragStart",target:"panning"}}},panning:{entry:"moveCamera",on:{pointerMove:{actions:"moveCamera"},pointerUp:[{guard:"hasVelocity",actions:"startGlide",target:"gliding"},{target:"idle"}],keyDown:{guard:"isEscapeKey",target:"idle"}}},gliding:{on:{frame:[{guard:"cameraWasMoved",actions:"resetContext",target:"idle"},{guard:"isGlideComplete",actions:"resetContext",target:"idle"},{actions:"animateGlide"}],pointerDown:{actions:["resetContext","setDragStart"],target:"panning"}}}}}),VL=ge({phase:"input",priority:-100},t=>{const e=nh.read(t).state,n=et.getButtons(t,"hand"),o=[...xr(t,n)];e==="gliding"&&o.push(l2(t)),o.push(...c2(t,[Gt.Escape])),o.length!==0&&nh.run(t,LL,o)}),FL=ge({phase:"input",priority:-100},t=>{const e=cn.read(t);if(!et.wheelActive(t,"scroll",e.modDown))return;const r=eg(t).find(l=>l.type==="wheel");if(!r)return;const o=he.read(t),s=o.left+r.wheelDeltaX/o.zoom,i=o.top+r.wheelDeltaY/o.zoom,a=he.write(t);a.left=s,a.top=i}),WL=ge({phase:"input",priority:-100},t=>{const e=As(t,"controls"),n=cn.read(t);if(!et.wheelActive(t,"zoom",n.modDown))return;const o=eg(t).find(S=>S.type==="wheel");if(!o)return;const s=he.read(t),i=Mt.read(t),a=bn.read(t);let l=2**(-.8*o.wheelDeltaY/500)*s.zoom;l=Math.min(e.maxZoom,Math.max(e.minZoom,l));const c=i.width/s.zoom,u=i.height/s.zoom,f=i.width/l,h=i.height/l,p=f-c,m=h-u,g=a.position[0]/i.width,y=a.position[1]/i.height,w=s.left-g*p,k=s.top-y*m,b=he.write(t);b.left=w,b.top=k,b.zoom=l});function UL(t={}){return{name:"controls",resources:Iv.parse(t),singletons:[nh],systems:[WL,FL,VL]}}var HL=(t={})=>UL(t);const jL={class:"wov-selection-box"},ZL=d.defineComponent({__name:"SelectionBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",jL))}}),KL={class:"wov-transform-box"},YL=d.defineComponent({__name:"TransformBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",KL))}}),qL={},XL={class:"wov-transform-handle"};function GL(t,e){return d.openBlock(),d.createElementBlock("div",XL)}const JL=Oo(qL,[["render",GL]]),QL=d.defineComponent({__name:"StickyNote",props:{entityId:{},block:{},stratum:{},selected:{type:Boolean},held:{},hovered:{type:Boolean},edited:{type:Boolean},opacity:{},connector:{}},setup(t){const e=t,n=mt(e.entityId,yn),r=mt(e.entityId,No),o=d.ref(null),s={[it.Top]:"flex-start",[it.Center]:"center",[it.Bottom]:"flex-end"},i=d.computed(()=>{var l;return{backgroundColor:n.value?`rgb(${n.value.red}, ${n.value.green}, ${n.value.blue})`:void 0,minHeight:`${e.block.size[0]}px`,alignItems:s[((l=r.value)==null?void 0:l.value)??it.Top]}}),{handleEditEnd:a}=Rf({blockData:e,containerRef:o,minWidth:()=>e.block.size[0],minHeight:()=>e.block.size[0]});return(l,c)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:o,class:"wov-sticky-note",style:d.normalizeStyle(i.value)},[d.createVNode(lc,d.mergeProps(e,{"block-element":o.value,onEditEnd:d.unref(a)}),null,16,["block-element","onEditEnd"])],4))}}),_c=ag({name:"blockPlacementState"},{editedCheckpoint:C.string().default("").max(36)}),Nv=re(t=>t.with(Sr));function eV(t){var e;if(!t)return null;try{const n=JSON.parse(t);return(e=n.block)!=null&&e.tag?n:(console.warn("Block snapshot missing required tag:",n),null)}catch{return console.warn("Invalid block snapshot JSON:",t),null}}function tV(t,e,n){const r=Vt(t,e.block.tag);if(!r)throw new Error(`Block placement: block definition for tag "${e.block.tag}" not found`);const o=e.block.size??[100,100],s=n[0]-o[0]/2,i=n[1]-o[1]/2,a=e.block.rank??Dn.genNext(t),l=bt(t);"synced"in e||J(t,l,de,{id:crypto.randomUUID()});const c=Object.assign({},e.block,{position:[s,i],size:o,rank:a});J(t,l,A,c);for(const f of r.components)if(!(f.name in e))J(t,l,f);else{const h=e[f.name];J(t,l,f,h)}const{sessionId:u}=Ve(t);return J(t,l,Tt,{sessionId:u}),l}function Pv(t,e,n,r,o){const s=tV(t,e,n),i=A.read(t,s);if(Wm(t,e.block.tag)&&(J(t,s,Ci,{}),o==="placement")){const{store:u}=As(t,"editing"),f=u.createCheckpoint();if(f){const h=_c.write(t);h.editedCheckpoint=f}}const a=zn.write(t);a.state=o==="dragOut"?ye.Dragging:ye.Pointing,a.dragStart=n,a.draggedEntity=s,a.draggedEntityStart=i.position,a.pointingStartClient=r,a.pointingStartWorld=n,a.isCloning=!1;const l=et.write(t);l.leftMouseTool="select",l.heldSnapshot="";const c=vn.write(t);c.cursorKind="select",c.rotation=0}function nV(t){const e=_c.read(t);if(e.editedCheckpoint){const n=e.editedCheckpoint;_c.write(t).editedCheckpoint="";const{store:r}=As(t,"editing");r.onSettled(()=>r.squashToCheckpoint(n),{frames:5})}}const rV=ge({phase:"capture"},t=>{Nv.removed(t).length>0&&Nv.current(t).length===0&&nV(t);const e=et.read(t);if(!e.heldSnapshot)return;const n=xr(t,[ln.Left]);if(n.length===0)return;const r=eV(e.heldSnapshot);if(!r)return;if(e.leftMouseTool==="drag-out"){const s=n.find(i=>i.type==="pointerMove"&&!i.obscured);if(!s)return;Pv(t,r,s.worldPosition,s.screenPosition,"dragOut")}else{const s=n.find(i=>i.type==="pointerDown"&&!i.obscured);if(!s)return;Pv(t,r,s.worldPosition,s.screenPosition,"placement")}}),oV=ge({phase:"update"},t=>{const{store:e}=As(t,"editing");ae(t,Ou,()=>{e.canUndo()&&(_g(t),e.undo())}),ae(t,Ya,()=>{e.canRedo()&&(_g(t),e.redo())})}),sV=[{name:"Figtree",displayName:"Figtree",url:"https://fonts.googleapis.com/css2?family=Figtree",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/Figtree.png"},{name:"Shantell Sans",displayName:"Shantell Sans",url:"https://fonts.googleapis.com/css2?family=Shantell+Sans",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/ShantellSans.png"},{name:"Courier Prime",displayName:"Courier Prime",url:"https://fonts.googleapis.com/css2?family=Courier+Prime",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/CourierPrime.png"},{name:"EB Garamond",displayName:"EB Garamond",url:"https://fonts.googleapis.com/css2?family=EB+Garamond",previewImage:"https://storage.googleapis.com/scrolly-page-fonts/EBGaramond.png"}];function Dv(t){return{name:"editing",resources:{store:t.store},singletons:[_c],systems:[rV,oV],cursors:wv,fonts:sV,keybinds:[{command:Ou.name,key:Gt.Z,mod:!0},{command:Ya.name,key:Gt.Y,mod:!0},{command:Ya.name,key:Gt.Z,mod:!0,shift:!0}]}}const iV=d.defineComponent({__name:"FileDropZone",props:{maxSize:{default:400}},setup(t){const e=t,{nextEditorTick:n}=tt(),{createImageBlock:r}=bk(),o=d.ref(!1);let s=0;const i=d.inject("containerRef");function a(k){var b;(b=k.dataTransfer)!=null&&b.types.some(S=>S==="Files"||S==="text/uri-list"||S==="text/html")&&(s++,s===1&&(o.value=!0))}function l(){s--,s===0&&(o.value=!1)}function c(){s=0,o.value=!1}d.onMounted(()=>{const k=i==null?void 0:i.value;k&&(k.addEventListener("dragenter",a),k.addEventListener("dragleave",l),k.addEventListener("drop",c))}),d.onUnmounted(()=>{const k=i==null?void 0:i.value;k&&(k.removeEventListener("dragenter",a),k.removeEventListener("dragleave",l),k.removeEventListener("drop",c))});function u(k){k.preventDefault(),k.dataTransfer&&(k.dataTransfer.dropEffect="copy")}function f(k){k.preventDefault()}function h(k){k.preventDefault()}async function p(k){if(k.preventDefault(),!k.dataTransfer)return;const b=k.clientX,S=k.clientY,v=Array.from(k.dataTransfer.files).filter(T=>T.type.startsWith("image/"));if(v.length>0){for(const T of v)await y(T,b,S);return}const E=m(k.dataTransfer);E&&await w(E,b,S)}function m(k){const b=k.getData("text/uri-list");if(b){const T=b.split(`
171
+ `).filter(_=>!_.startsWith("#")).find(_=>g(_));if(T)return T}const S=k.getData("text/html");if(S){const E=S.match(/<img[^>]+src=["']([^"']+)["']/i);if(E!=null&&E[1])return E[1]}const v=k.getData("text/plain");return v&&g(v)?v:null}function g(k){try{const S=new URL(k).pathname.toLowerCase();return/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i.test(S)||k.startsWith("data:image/"),!0}catch{return!1}}async function y(k,b,S){const v=await n(),E=he.read(v),T=Mt.read(v),_=E.left+(b-T.left)/E.zoom,I=E.top+(S-T.top)/E.zoom;await r(k,_,I,{maxSize:e.maxSize})}async function w(k,b,S){try{const v=await fetch(k);if(!v.ok){console.warn("Failed to fetch image from URL:",k);return}const E=await v.blob();if(!E.type.startsWith("image/")){console.warn("URL did not return an image:",k);return}const _=new URL(k).pathname.split("/").pop()||"image",I=new File([E],_,{type:E.type});await y(I,b,S)}catch(v){console.warn("Failed to load image from URL:",k,v)}}return(k,b)=>(d.openBlock(),d.createElementBlock("div",{class:d.normalizeClass(["wov-image-drop-zone",{"wov-drag-over":o.value}]),onDragover:u,onDragenter:f,onDragleave:h,onDrop:p},null,34))}}),aV={class:"wov-user-cursors"},lV={class:"wov-cursor-svg",viewBox:"0 0 4.35 4.75",width:"20",height:"20"},cV=["fill"],uV="M2.39,2.88s-.04.01-.05.02c-.01,0-.02.01-.03.02,0,.01-.02.02-.03.05l-.77,1.44c-.07.13-.1.19-.14.2-.03.01-.07,0-.1-.01-.03-.02-.05-.09-.09-.23L.16.41c-.03-.13-.05-.19-.03-.23.02-.03.04-.05.08-.06.04,0,.1.02.21.08l3.59,1.94c.13.07.19.1.2.14.01.03,0,.07-.01.1-.02.03-.09.05-.23.09l-1.58.4Z",dV=d.defineComponent({__name:"UserCursors",props:{users:{},currentSessionId:{},camera:{}},setup(t){const e=t,n=d.computed(()=>e.users.filter(r=>r.sessionId!==e.currentSessionId).map(r=>({...r,screenX:(r.position[0]-e.camera.left)*e.camera.zoom,screenY:(r.position[1]-e.camera.top)*e.camera.zoom})));return(r,o)=>(d.openBlock(),d.createElementBlock("div",aV,[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(n.value,s=>(d.openBlock(),d.createElementBlock("div",{key:s.sessionId,class:"wov-user-cursor",style:d.normalizeStyle({transform:`translate(${s.screenX}px, ${s.screenY}px)`})},[(d.openBlock(),d.createElementBlock("svg",lV,[d.createElementVNode("path",{fill:s.color,stroke:"#fff","stroke-miterlimit":"10","stroke-width":".25",d:uV},null,8,cV)])),d.createElementVNode("span",{class:"wov-cursor-label",style:d.normalizeStyle({backgroundColor:s.color})},d.toDisplayString(s.name),5)],4))),128))]))}}),fV={key:0,class:"wov-offline-indicator"},hV=d.defineComponent({__name:"OfflineIndicator",props:{isOnline:{type:Boolean}},setup(t){return(e,n)=>t.isOnline?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",fV,"Working Offline"))}}),pV={key:0,class:"wov-version-mismatch-overlay"},mV=d.defineComponent({__name:"VersionMismatch",props:{versionMismatch:{type:Boolean}},setup(t){function e(){window.location.reload()}return(n,r)=>t.versionMismatch?(d.openBlock(),d.createElementBlock("div",pV,[d.createElementVNode("div",{class:"wov-version-mismatch-dialog"},[r[0]||(r[0]=d.createElementVNode("p",null,"A new version is available.",-1)),r[1]||(r[1]=d.createElementVNode("p",null,"Please refresh the page to continue.",-1)),d.createElementVNode("button",{onClick:e},"Refresh")])])):d.createCommentVNode("",!0)}}),gV=d.defineComponent({__name:"BackToContentButton",setup(t){const{nextEditorTick:e}=tt(),n=Nt(he),r=re(l=>l.with(de,A,Be)),o=d.ref(0),s=d.inject(En);if(s){const l=s.registerTickCallback(c=>{r.addedOrRemoved(c).length>0&&(o.value=r.current(c).length)});d.onUnmounted(l)}const i=d.ref(!1);d.watchEffect(()=>{i.value=!n.value.canSeeBlocks&&o.value>0});function a(){e(l=>{const c=r.current(l);if(c.length===0)return;let u=Number.POSITIVE_INFINITY,f=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(const E of c){const T=Be.read(l,E);u=Math.min(u,T.value[0]),f=Math.min(f,T.value[1]),h=Math.max(h,T.value[2]),p=Math.max(p,T.value[3])}const m=Mt.read(l),g=he.read(l);let y=Math.min(m.width/(h-u),m.height/(p-f));y/=1.1,y=Math.min(y,g.zoom);const w=(u+h)/2,k=(f+p)/2,b=w-m.width/y/2,S=k-m.height/y/2,v=he.write(l);v.left=b,v.top=S,v.zoom=y})}return(l,c)=>i.value?(d.openBlock(),d.createElementBlock("button",{key:0,class:"wov-back-to-content",onClick:a},[...c[0]||(c[0]=[d.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},[d.createElementVNode("path",{d:"M10 12L6 8L10 4",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})],-1),d.createTextVNode(" Back to content ",-1)])])):d.createCommentVNode("",!0)}}),yV=["data-entity-id","data-selected","data-held-by-other","data-hovered"],wV=d.defineComponent({__name:"WovenCanvas",props:{store:{},editor:{},background:{},assetProvider:{},pluginOptions:{},controls:{}},emits:["ready"],setup(t,{emit:e}){var si;const n=re(N=>N.tracking(A)),r=re(N=>N.with(A).tracking(ze)),o=re(N=>N.with(A).tracking(pt)),s=re(N=>N.with(A).tracking(Tt)),i=re(N=>N.with(A).tracking(Gr)),a=re(N=>N.with(A).tracking(Sr)),l=re(N=>N.with(A).tracking(Qe)),c=re(N=>N.tracking(Cr)),u=t,f=e,h=d.ref(null),p=d.shallowRef(null),m=Om.parse(((si=u.editor)==null?void 0:si.user)??{}),g=new Set,y=new Map,w=d.shallowRef([]),k=new Map,b=new Map,S=new Set,v=new Map,E=d.shallowRef([]),T=d.ref(!0),_=d.ref(!1),I=d.ref(!0),z=d.shallowRef(he.default());function F(N,ue,H){let ie=k.get(N);ie||(ie=new Map,k.set(N,ie));let G=ie.get(ue);return G||(G=new Set,ie.set(ue,G)),G.add(H),()=>{G.delete(H),G.size===0&&(ie.delete(ue),ie.size===0&&k.delete(N))}}function j(N,ue,H,ie=!1){const G=k.get(ue);if(!G)return;const U=G.get(H.name);if(!U||U.size===0)return;let rt=null;ie||(rt=H.snapshot(N,ue));for(const qn of U)qn(rt)}function M(N,ue){let H=b.get(N);return H||(H=new Set,b.set(N,H)),H.add(ue),()=>{H.delete(ue),H.size===0&&b.delete(N)}}function V(N,ue){const H=b.get(ue.name);if(!H||H.size===0)return;const ie=ue.snapshot(N);for(const G of H)G(ie)}function K(N){return S.add(N),()=>{S.delete(N)}}function se(){return m.sessionId}function Y(N){return y.get(N)??null}const R={hasEntity:N=>g.has(N),getEditor:()=>p.value,getAssetManager:()=>Ue,getSessionId:se,getUserBySessionId:Y,subscribeComponent:F,subscribeSingleton:M,registerTickCallback:K};d.provide(En,R),d.provide("containerRef",h);const W=Ik();d.provide(my,W);let Q=0,pe=null,me=null,Ue=null;async function Yn(){!p.value||!me||(p.value.nextTick(N=>{So(N),ri(N);for(const ue of S)ue(N);me&&me.sync(N)}),await p.value.tick(),pe=requestAnimationFrame(Yn))}let pr=null;d.onMounted(async()=>{var qn,tn;if(!h.value)return;pr=()=>{var ds;(ds=h.value)==null||ds.scrollTo(0,0)},h.value.addEventListener("scroll",pr);const N=u.store??{},ue={...N};N.websocket&&(ue.websocket={...N.websocket,onVersionMismatch:ds=>{var $r,ua;_.value=!0,(ua=($r=N.websocket)==null?void 0:$r.onVersionMismatch)==null||ua.call($r,ds)},onConnectivityChange:ds=>{var $r,ua;T.value=ds,(ua=($r=N.websocket)==null?void 0:$r.onConnectivityChange)==null||ua.call($r,ds)}}),me=new lg(ue);const H=[],ie=u.pluginOptions;(ie==null?void 0:ie.controls)!==!1&&H.push(HL((ie==null?void 0:ie.controls)??{})),(ie==null?void 0:ie.selection)!==!1&&H.push(EI((ie==null?void 0:ie.selection)||void 0)),(ie==null?void 0:ie.eraser)!==!1&&H.push(rN((ie==null?void 0:ie.eraser)||void 0)),(ie==null?void 0:ie.pen)!==!1&&H.push(LN()),(ie==null?void 0:ie.arrows)!==!1&&H.push(yB((ie==null?void 0:ie.arrows)||void 0)),H.push(Dv({store:me})),(qn=u.editor)!=null&&qn.plugins&&H.push(...u.editor.plugins);const G={...u.editor,user:m,plugins:H,controls:u.controls},U=new s2(h.value,G);await U.initialize(),await me.initialize({components:U.components,singletons:U.singletons});const rt=((tn=N.persistence)==null?void 0:tn.documentId)??"default";Ue=new DL({provider:u.assetProvider??new zL,documentId:rt}),await Ue.init(),await Ue.resumePendingUploads(),p.value=U,pe=requestAnimationFrame(Yn),I.value=!1,f("ready",U,me)}),d.onUnmounted(()=>{var N;pe!==null&&cancelAnimationFrame(pe),Ue==null||Ue.close(),me==null||me.close(),(N=p.value)==null||N.dispose()});function So(N){const{events:ue,newIndex:H}=N.eventBuffer.readEvents(Q);if(Q=H,ue.length===0)return;const{componentsById:ie,singletonsById:G}=Ve(N);for(const{entityId:U,eventType:rt,componentId:qn}of ue){if(U===hs){if(rt===Ie.CHANGED){const tn=G.get(qn);tn&&V(N,tn)}continue}if(rt===Ie.ADDED)g.add(U);else if(rt===Ie.REMOVED)g.delete(U),k.delete(U);else if(rt===Ie.COMPONENT_ADDED){g.add(U);const tn=ie.get(qn);tn&&j(N,U,tn)}else if(rt===Ie.COMPONENT_REMOVED){const tn=ie.get(qn);tn&&j(N,U,tn,!0)}else if(rt===Ie.CHANGED){const tn=ie.get(qn);tn&&j(N,U,tn)}}}function ri(N){var ie;let ue=!1;for(const G of n.added(N)){const U=A.snapshot(N,G),rt=(ie=p.value)==null?void 0:ie.blockDefs[U.tag],qn=(rt==null?void 0:rt.stratum)??"content";v.set(G,d.ref({entityId:G,block:U,stratum:qn,selected:!1,held:null,hovered:!1,edited:!1,opacity:null,connector:null})),ue=!0}for(const G of n.removed(N))v.delete(G),ue=!0;for(const G of n.changed(N)){const U=v.get(G);if(U){const rt=A.snapshot(N,G);U.value.block.rank!==rt.rank&&(ue=!0),U.value.block=rt}}let H=!1;for(const G of c.addedOrChanged(N)){const U=Cr.snapshot(N,G);y.set(U.sessionId,U),H=!0}for(const G of c.removed(N)){const U=Cr.read(N,G);y.delete(U.sessionId),H=!0}H&&(w.value=Array.from(y.values()));for(const G of o.added(N)){const U=v.get(G);U&&!U.value.selected&&(U.value.selected=!0)}for(const G of o.removed(N)){const U=v.get(G);U&&U.value.selected&&(U.value.selected=!1)}for(const G of s.addedOrChanged(N)){const U=v.get(G);U&&(U.value.held=Tt.snapshot(N,G))}for(const G of s.removed(N)){const U=v.get(G);U&&U.value.held!==null&&(U.value.held=null)}for(const G of i.added(N)){const U=v.get(G);U&&!U.value.hovered&&(U.value.hovered=!0)}for(const G of i.removed(N)){const U=v.get(G);U&&U.value.hovered&&(U.value.hovered=!1)}for(const G of a.added(N)){const U=v.get(G);U&&!U.value.edited&&(U.value.edited=!0)}for(const G of a.removed(N)){const U=v.get(G);U&&U.value.edited&&(U.value.edited=!1)}for(const G of l.addedOrChanged(N)){const U=v.get(G);U&&(U.value.opacity=Qe.snapshot(N,G))}for(const G of l.removed(N)){const U=v.get(G);U&&U.value.opacity!==null&&(U.value.opacity=null)}for(const G of r.addedOrChanged(N)){const U=v.get(G);U&&(U.value.connector=ze.snapshot(N,G))}for(const G of r.removed(N)){const U=v.get(G);U&&U.value.connector!==null&&(U.value.connector=null)}if(ue){const G=Array.from(v.values());G.sort((U,rt)=>U.value.block.rank>rt.value.block.rank?1:-1),E.value=G}}M(he.name,N=>{N&&(z.value=N)});function ca(N){const ue=N.rotateZ!==0,H=N.flip[0],ie=N.flip[1];if(!ue&&!H&&!ie)return;const G=[];return ue&&G.push(`rotate(${N.rotateZ}rad)`),H&&G.push("scaleX(-1)"),ie&&G.push("scaleY(-1)"),G.join(" ")}function oi(N){const{held:ue}=N;if(!ue||!ue.sessionId||ue.sessionId===m.sessionId)return null;const H=Y(ue.sessionId);return(H==null?void 0:H.color)??null}function Pn(N){const{block:ue,stratum:H,opacity:ie}=N,G=oi(N),U=ie!==null?ie.value/255:1;return{position:"absolute",left:`${ue.position[0]}px`,top:`${ue.position[1]}px`,width:`${ue.size[0]}px`,height:`${ue.size[1]}px`,zIndex:_u[H]*1e3,transform:ca(ue),opacity:U,pointerEvents:"none",userSelect:"none","--wov-held-by-color":G??void 0,transition:U===1?"opacity 0ms 32ms":void 0}}return(N,ue)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:h,class:"wov-root",style:{position:"relative",width:"100%",height:"100%",overflow:"hidden"}},[t.background?d.renderSlot(N.$slots,"background",{key:0,background:t.background},()=>[d.createVNode(hv,{background:t.background},null,8,["background"])]):d.createCommentVNode("",!0),d.createElementVNode("div",{class:"wov-canvas",style:d.normalizeStyle({position:"absolute",transformOrigin:"0 0",transform:`scale(${z.value.zoom}) translate(${-z.value.left}px, ${-z.value.top}px)`,"--wov-zoom":z.value.zoom})},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(E.value,H=>(d.openBlock(),d.createElementBlock("div",{key:H.value.entityId,"data-entity-id":H.value.entityId,style:d.normalizeStyle(Pn(H.value)),"data-selected":H.value.selected||void 0,"data-held-by-other":oi(H.value)!==null||void 0,"data-hovered":H.value.hovered||void 0,class:"wov-block"},[d.renderSlot(N.$slots,`block:${H.value.block.tag}`,d.mergeProps({ref_for:!0},H.value),()=>[H.value.block.tag==="selection-box"?(d.openBlock(),d.createBlock(ZL,d.mergeProps({key:0,ref_for:!0},H.value),null,16)):H.value.block.tag==="transform-box"?(d.openBlock(),d.createBlock(YL,d.mergeProps({key:1,ref_for:!0},H.value),null,16)):H.value.block.tag==="transform-handle"?(d.openBlock(),d.createBlock(JL,d.mergeProps({key:2,ref_for:!0},H.value),null,16)):H.value.block.tag==="arrow-handle"?(d.openBlock(),d.createBlock(yy,d.mergeProps({key:3,ref_for:!0},H.value),null,16)):H.value.block.tag==="arrow-terminal"?(d.openBlock(),d.createBlock(wy,d.mergeProps({key:4,ref_for:!0},H.value),null,16)):H.value.block.tag==="sticky-note"?(d.openBlock(),d.createBlock(QL,d.mergeProps({key:5,ref_for:!0},H.value),null,16)):H.value.block.tag==="eraser"?(d.openBlock(),d.createBlock(Py,d.mergeProps({key:6,ref_for:!0},H.value),null,16)):H.value.block.tag==="pen-stroke"?(d.openBlock(),d.createBlock(jy,d.mergeProps({key:7,ref_for:!0},H.value),null,16)):H.value.block.tag==="arc-arrow"?(d.openBlock(),d.createBlock(gy,d.mergeProps({key:8,ref_for:!0},H.value),null,16)):H.value.block.tag==="elbow-arrow"?(d.openBlock(),d.createBlock(ky,d.mergeProps({key:9,ref_for:!0},H.value),null,16)):H.value.block.tag==="text"?(d.openBlock(),d.createBlock(Nk,d.mergeProps({key:10,ref_for:!0},H.value),null,16)):H.value.block.tag==="image"?(d.openBlock(),d.createBlock(Dy,d.mergeProps({key:11,ref_for:!0},H.value),null,16)):H.value.block.tag==="shape"?(d.openBlock(),d.createBlock(Bk,d.mergeProps({key:12,ref_for:!0},H.value),null,16)):d.createCommentVNode("",!0)])],12,yV))),128))],4),p.value?d.renderSlot(N.$slots,"user-cursors",{key:1,users:w.value,currentSessionId:d.unref(m).sessionId,camera:z.value},()=>[d.createVNode(dV,{users:w.value,"current-session-id":d.unref(m).sessionId,camera:z.value},null,8,["users","current-session-id","camera"])]):d.createCommentVNode("",!0),p.value?(d.openBlock(),d.createBlock(gv,{key:2},{default:d.withCtx(H=>[d.renderSlot(N.$slots,"floating-menu",d.normalizeProps(d.guardReactiveProps(H)))]),_:3})):d.createCommentVNode("",!0),p.value?d.renderSlot(N.$slots,"user-presence",{key:3,users:w.value},()=>[d.createVNode(_v,{users:w.value},null,8,["users"])]):d.createCommentVNode("",!0),p.value?d.renderSlot(N.$slots,"toolbar",{key:4},()=>[d.createVNode(Av)]):d.createCommentVNode("",!0),p.value?d.renderSlot(N.$slots,"default",{key:5}):d.createCommentVNode("",!0),d.renderSlot(N.$slots,"offline-indicator",{isOnline:T.value},()=>[d.createVNode(hV,{"is-online":T.value},null,8,["is-online"])]),d.renderSlot(N.$slots,"version-mismatch",{versionMismatch:_.value},()=>[d.createVNode(mV,{"version-mismatch":_.value},null,8,["version-mismatch"])]),d.renderSlot(N.$slots,"back-to-content",{},()=>[d.createVNode(gV)]),d.renderSlot(N.$slots,"loading",{isLoading:I.value},()=>[d.createVNode(yv,{"is-loading":I.value},null,8,["is-loading"])]),p.value?d.renderSlot(N.$slots,"file-drop-zone",{key:6},()=>[d.createVNode(iV)]):d.createCommentVNode("",!0)],512))}});$.ARROW_HEADS=ud,$.ArcArrow=gy,$.ArcArrowTool=TL,$.ArrowHandle=yy,$.ArrowHead=Tr,$.ArrowHeadButton=jf,$.ArrowTerminal=wy,$.ArrowThicknessButton=nv,$.CURSORS=wv,$.CanvasBackground=hv,$.CanvasComponentDef=sg,$.CanvasSingletonDef=ig,$.CanvasStore=lg,$.ColorButton=sv,$.ColorPicker=ov,$.CursorKind=is,$.EditableText=lc,$.EditingPlugin=Dv,$.ElbowArrow=ky,$.ElbowArrowTool=Tv,$.Eraser=Py,$.EraserTool=Ev,$.FloatingMenu=gv,$.FloatingMenuBar=mv,$.HandTool=vv,$.IconChevronDown=Bn,$.ImageBlock=Dy,$.ImageTool=Mv,$.LoadingOverlay=yv,$.MenuButton=ni,$.MenuDropdown=In,$.MenuTooltip=Zf,$.PenStroke=jy,$.PenStrokeThicknessButton=iv,$.PenTool=Cv,$.SHAPES=Di,$.SelectTool=kv,$.Shape=wn,$.ShapeBlock=Bk,$.ShapeFillColorButton=av,$.ShapeKindButton=lv,$.ShapeStrokeColorButton=cv,$.ShapeTool=Sv,$.StickyNoteTool=bv,$.StrokeKind=ht,$.Synced=Si,$.TextAlignment=kn,$.TextAlignmentButton=Kf,$.TextBlock=Nk,$.TextBoldButton=Yf,$.TextColorButton=eh,$.TextFontFamilyButton=Xf,$.TextFontSizeButton=Gf,$.TextItalicButton=Jf,$.TextTool=xv,$.TextUnderlineButton=Qf,$.Toolbar=Av,$.ToolbarButton=dr,$.User=Cr,$.UserPresence=_v,$.WovenCanvas=wV,$.computeCommonComponents=pv,$.createTooltipContext=Ik,$.defineCanvasComponent=v2,$.defineCanvasSingleton=ag,$.getArrowHead=zs,$.useComponent=mt,$.useComponents=yo,$.useEditorContext=tt,$.useFonts=dv,$.useQuery=Sk,$.useSingleton=Nt,$.useTextBatchController=_k,$.useTextEditorController=oa,$.useTextFormatting=ar,$.useTextStretchBehavior=Rf,$.useToolbar=zf,$.useTooltipSingleton=ko,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});