@woven-canvas/vue 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.js +15847 -12809
- package/build/index.umd.cjs +39 -39
- package/build/src/components/buttons/text/TextButtonGroup.vue.d.ts.map +1 -1
- package/build/src/injection/dropdown.d.ts.map +1 -1
- package/build/src/injection/floatingMenu.d.ts.map +1 -1
- package/build/src/injection/toolbar.d.ts.map +1 -1
- package/build/src/injection/tooltip.d.ts.map +1 -1
- package/build/src/injection/wovenCanvas.d.ts.map +1 -1
- package/build/style.css +1 -1
- package/build/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -5
package/build/index.umd.cjs
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
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(`
|
|
1
|
+
(function(L,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],d):(L=typeof globalThis<"u"?globalThis:L||self,d(L.Vue={},L.Vue))})(this,function(L,d){"use strict";var y5=Object.defineProperty;var w5=(L,d,ao)=>d in L?y5(L,d,{enumerable:!0,configurable:!0,writable:!0,value:ao}):L[d]=ao;var x=(L,d,ao)=>w5(L,typeof d!="symbol"?d+"":d,ao);var Ar,ro,oo,Wn,Us,Ws,Hs,Ut,We,Zs,Ir;const ao=(t,e)=>e.some(n=>t instanceof n);let Cp,_p;function CS(){return Cp||(Cp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function _S(){return _p||(_p=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const $u=new WeakMap,Lu=new WeakMap,fl=new WeakMap;function xS(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(Qo(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return fl.set(e,t),e}function TS(t){if($u.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)});$u.set(t,e)}let Vu={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return $u.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Qo(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 xp(t){Vu=t(Vu)}function MS(t){return _S().includes(t)?function(...e){return t.apply(Fu(this),e),Qo(this.request)}:function(...e){return Qo(t.apply(Fu(this),e))}}function AS(t){return typeof t=="function"?MS(t):(t instanceof IDBTransaction&&TS(t),ao(t,CS())?new Proxy(t,Vu):t)}function Qo(t){if(t instanceof IDBRequest)return xS(t);if(Lu.has(t))return Lu.get(t);const e=AS(t);return e!==t&&(Lu.set(t,e),fl.set(e,t)),e}const Fu=t=>fl.get(t);function Tp(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=Qo(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Qo(i.result),l.oldVersion,l.newVersion,Qo(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 IS=["get","getKey","getAll","getAllKeys","count"],NS=["put","add","delete","clear"],ju=new Map;function Mp(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(ju.get(e))return ju.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=NS.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||IS.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 ju.set(e,s),s}xp(t=>({...t,get:(e,n,r)=>Mp(e,n)||t.get(e,n,r),has:(e,n)=>!!Mp(e,n)||t.has(e,n)}));const BS=["continue","continuePrimaryKey","advance"],Ap={},Uu=new WeakMap,Ip=new WeakMap,PS={get(t,e){if(!BS.includes(e))return t[e];let n=Ap[e];return n||(n=Ap[e]=function(...r){Uu.set(this,Ip.get(this)[e](...r))}),n}};async function*OS(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;e=e;const n=new Proxy(e,PS);for(Ip.set(n,e),fl.set(n,Fu(e));e;)yield n,e=await(Uu.get(n)||e.continue()),Uu.delete(n)}function Np(t,e){return e===Symbol.asyncIterator&&ao(t,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&ao(t,[IDBIndex,IDBObjectStore])}xp(t=>({...t,get(e,n,r){return Np(e,n)?OS:t.get(e,n,r)},has(e,n){return Np(e,n)||t.has(e,n)}}));var sn=Symbol.for("__woven_ecs_schema_default__"),Nr=class{},DS=new Set(["string","number","boolean","binary"]);function Bp(t,e){const n=t.def.type;if(!DS.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 RS=class extends Nr{constructor(){super(...arguments);x(this,"def",{type:"string"})}max(e){return this.def.maxLength=e,this}default(e){return this.def.default=e,this}[sn](){return this.def.default??""}},lo=class extends Nr{constructor(e){super();x(this,"def");this.def={type:"number",btype:e}}default(e){return this.def.default=e,this}[sn](){return this.def.default??0}},zS=class extends Nr{constructor(){super(...arguments);x(this,"def",{type:"boolean"})}default(e){return this.def.default=e,this}[sn](){return this.def.default??!1}},$S=class extends Nr{constructor(){super(...arguments);x(this,"def",{type:"binary"})}max(e){return this.def.maxLength=e,this}default(e){return this.def.default=e,this}[sn](){return this.def.default??new Uint8Array(0)}},LS=class extends Nr{constructor(e,n){super();x(this,"def");Bp(e,"array"),this.def={type:"array",elementDef:e.def,maxLength:n}}default(e){return this.def.default=e,this}[sn](){return this.def.default??[]}},VS=class extends Nr{constructor(e,n){super();x(this,"def");x(this,"elementBuilder");Bp(e,"tuple"),this.elementBuilder=e,this.def={type:"tuple",elementDef:e.def,length:n}}default(e){return this.def.default=e,this}[sn](){if(this.def.default)return this.def.default;const e=this.elementBuilder[sn]();return new Array(this.def.length).fill(e)}},FS=class extends Nr{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}[sn](){return this.def.default??new Array(this.def.size).fill(0)}},jS=class extends Nr{constructor(e){super();x(this,"def");this.def={type:"enum",values:Object.values(e)}}default(e){return this.def.default=e,this}[sn](){return this.def.default!==void 0?this.def.default:[...this.def.values].sort()[0]}},US=class extends Nr{constructor(){super(...arguments);x(this,"def",{type:"ref"})}[sn](){return null}},C={string:()=>new RS,uint8:()=>new lo("uint8"),uint16:()=>new lo("uint16"),uint32:()=>new lo("uint32"),int8:()=>new lo("int8"),int16:()=>new lo("int16"),int32:()=>new lo("int32"),float32:()=>new lo("float32"),float64:()=>new lo("float64"),boolean:()=>new zS,binary:()=>new $S,enum:t=>new jS(t),array:(t,e)=>new LS(t,e),tuple:(t,e)=>new VS(t,e),buffer:t=>new FS(t),ref:()=>new US},Br=class{constructor(t){x(this,"fieldDef");this.fieldDef=t}getDefaultValue(){return this.fieldDef.schemaDefault}};function qs(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 WS(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 HS(t){return t!=="float32"&&t!=="float64"}var ZS=class extends Br{constructor(e){super(e);x(this,"useAtomics");this.useAtomics=HS(e.btype)}initializeStorage(e,n){const r=qs(this.fieldDef.btype),o=new n(e*r),s=WS(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}},KS=512,YS=256,Pp=new TextEncoder,Op=new TextDecoder;function Dp(t){switch(t.type){case"number":return qs(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||KS;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||YS;return Math.ceil((e+4)/4)*4}}}function hl(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 Rp=(Ar=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=Dp(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+Ar.LENGTH_BYTES,s=[];switch(this.elementDef.type){case"number":{const i=hl(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(Op.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+Ar.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=hl(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=Pp.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+Ar.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const i=hl(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 Op.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+Ar.LENGTH_BYTES;switch(this.elementDef.type){case"number":{const a=hl(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=Pp.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(Ar,"LENGTH_BYTES",4),Ar),qS=class extends Br{initializeStorage(t,e){const n=Dp(this.fieldDef.elementDef),r=this.fieldDef.maxLength*n+Rp.LENGTH_BYTES,o=Math.ceil(r/8)*8,s=new e(t*o),i=new Rp(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)}},JS=256,zp=(ro=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+ro.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-ro.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+ro.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(ro,"LENGTH_BYTES",4),ro),GS=class extends Br{initializeStorage(t,e){const r=(this.fieldDef.maxLength||JS)+zp.LENGTH_BYTES,o=new e(t*r),s=new zp(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)}},XS=class extends Br{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 QS(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 eE=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=qs(r.btype),this.capacity=e,this.bufferSize=o,this.elementsPerEntry=n/this.bytesPerElement,this.numberTypedArray=QS(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}},tE=class extends Br{initializeStorage(t,e){const n=qs(this.fieldDef.elementDef.btype),r=this.fieldDef.size*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new eE(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??[])}},nE=class extends Br{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)}},cr=4294967295,$p=33554431,Lp=25;function Vp(t,e){return t&$p|e<<Lp}function rE(t){return t&$p}function oE(t){return t>>>Lp}function Wu(t,e,n=!0){if(t===cr)return null;const r=rE(t),o=oE(t);return n&&!e.has(r)||e.getGeneration(r)!==o?null:r}var sE=class extends Br{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(cr),{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=Wu(l,s);return l!==cr&&c===null&&Atomics.store(i,a,cr),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=Wu(l,s);return l!==cr&&c===null&&Atomics.store(i,a,cr),c},set:i=>{const a=r[n],l=o();if(i===null||i===cr)Atomics.store(a,l,cr);else{const c=s.getGeneration(i);Atomics.store(a,l,Vp(i,c))}}})}setValue(e,n,r){if(r===null||r===cr)Atomics.store(e,n,cr);else{const o=this.entityBuffer.getGeneration(r);Atomics.store(e,n,Vp(r,o))}}},iE=512,aE=new TextEncoder,lE=new TextDecoder,Fp=(oo=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+oo.LENGTH_BYTES,c=new Uint8Array(a);for(let u=0;u<a;u++)c[u]=Atomics.load(this.buffer,l+u);return lE.decode(c)}set(e,n){const r=e*this.bytesPerString,o=aE.encode(n),s=this.bytesPerString-oo.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+oo.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(oo,"LENGTH_BYTES",4),oo),cE=class extends Br{initializeStorage(t,e){const r=(this.fieldDef.maxLength||iE)+Fp.LENGTH_BYTES,o=new e(t*r),s=new Fp(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)}},uE=512,dE=256,fE=new TextEncoder,hE=new TextDecoder;function jp(t){switch(t.type){case"number":return qs(t.btype);case"boolean":return 1;case"string":{const e=t.maxLength||uE;return Math.ceil((e+4)/4)*4}case"binary":{const e=t.maxLength||dE;return Math.ceil((e+4)/4)*4}}}function pE(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 mE=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=jp(r),this.capacity=e,this.elementDef=r,this.tupleLength=o,r.type==="number"){const s=qs(r.btype);this.elementsPerEntry=n/s,this.numberTypedArray=pE(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(hE.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=fE.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}},gE=class extends Br{initializeStorage(t,e){const n=jp(this.fieldDef.elementDef),r=this.fieldDef.length*n,o=Math.ceil(r/8)*8,s=new e(t*o),i=new mE(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)}},yE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,wE={string:cE,number:ZS,boolean:XS,binary:GS,array:qS,tuple:gE,buffer:tE,enum:nE},Js=4294967295,Gs=0,Hu=Symbol.for("__woven_ecs_def_id_counter__");function Up(){const t=globalThis;return t[Hu]||(t[Hu]={value:0}),t[Hu]}var vE=(Wn=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[sn]&&i.schemaDefault===void 0&&(i.schemaDefault=s[sn]()),this.schema[r]=i,this.fieldNames.push(r)}}static fromDef(e){return new Wn(e.schema,e.isSingleton)}static fromTransfer(e,n,r,o){const s=new Wn(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,yE);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 sE(e,this.entityBuffer);const n=wE[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,Gs,s)}}initializeMasters(){if(this._buffer===null)throw new Error("Component buffers not initialized");for(let e=0;e<Wn.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<Wn.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?Js: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?Js:e;(o=this.eventBuffer)==null||o.pushChanged(r,this.componentId)}read(e){const n=this.readonlyPool[this.readPoolIndex];return this.readPoolIndex=(this.readPoolIndex+1)%Wn.POOL_SIZE,n.entityId=e,n.view}write(e){var o;const n=this.writablePool[this.writePoolIndex];this.writePoolIndex=(this.writePoolIndex+1)%Wn.POOL_SIZE,n.entityId=e;const r=this.isSingleton?Js: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(Wn,"POOL_SIZE",8),Wn),Wp=class{constructor(t,e=!1){x(this,"_defId");x(this,"schema");x(this,"isSingleton");this._defId=Up().value++,this.schema=t,this.isSingleton=e}_getInstance(t){const e=t.components[this._defId];if(!e){const n=this.name??this.constructor.name,r=Object.keys(t.components).join(", ");throw new Error(`Component "${n}" (defId=${this._defId}) is not registered with this World. Registered defIds: [${r}]`)}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[sn]();return t}};function Hp(t){return new Wp(t,!1)}var kE=class{constructor(t){x(this,"_defId");x(this,"schema");x(this,"isSingleton",!0);this._defId=Up().value++,this.schema=t}_getInstance(t){const e=t.components[this._defId],n=this.name??this.constructor.name;if(!e)throw new Error(`Singleton "${n}" is not registered with this World.`);if(!e.isSingleton)throw new Error(`Component "${n}" 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(Gs)}write(t){return this._getInstance(t).write(Gs)}copy(t,e){this._getInstance(t).copy(Gs,e)}patch(t,e){this._getInstance(t).patch(Gs,e)}snapshot(t){return this._getInstance(t).snapshot(Gs)}default(){const t={};for(const[e,n]of Object.entries(this.schema))t[e]=n[sn]();return t}},bE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,Le={ADDED:1,REMOVED:2,CHANGED:4,COMPONENT_ADDED:8,COMPONENT_REMOVED:16},SE=8,Zu=4,Ku=0,EE=class wS{constructor(e){x(this,"buffer");x(this,"headerView");x(this,"dataView");x(this,"maxEvents");x(this,"reusableSet",new Set);this.maxEvents=e;const n=Zu+e*SE;this.buffer=new bE(n),this.headerView=new Uint32Array(this.buffer,0,1),this.dataView=new Uint32Array(this.buffer,Zu),Atomics.store(this.headerView,Ku,0)}static fromTransfer(e,n){const r=Object.create(wS.prototype);return r.buffer=e,r.headerView=new Uint32Array(e,0,1),r.dataView=new Uint32Array(e,Zu),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,Ku,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,Le.ADDED,0)}pushRemoved(e){this.push(e,Le.REMOVED,0)}pushChanged(e,n){this.push(e,Le.CHANGED,n)}pushComponentAdded(e,n){this.push(e,Le.COMPONENT_ADDED,n)}pushComponentRemoved(e,n){this.push(e,Le.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,Ku)}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===Le.CHANGED){const v=g>>16&65535,b=v>>3,S=v&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}}},CE=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}},Yu=Symbol.for("__woven_ecs_build_query__");function pl(t){return new Uint8Array(t)}function Hi(t,e){const n=Math.floor(e/8),r=e%8;n<t.length&&(t[n]|=1<<r)}var Zp=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=pl(n),this.withoutMask=pl(n),this.anyMask=pl(n),this.trackingMask=pl(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)Hi(this.withMask,this._getComponentId(e));return this}without(...t){for(const e of t)Hi(this.withoutMask,this._getComponentId(e));return this}any(...t){for(const e of t)Hi(this.anyMask,this._getComponentId(e));return this}tracking(...t){for(const e of t){const n=this._getComponentId(e);Hi(this.withMask,n),Hi(this.trackingMask,n)}return this}[Yu](){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 CE(this.trackingMask,this.withMask,this.withoutMask,this.anyMask,t,e,n,r)}},Kp=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,ur=0,co=1,Xs=4294967295,Yp=class{constructor(t){x(this,"denseBuffer");x(this,"sparseBuffer");x(this,"dense");x(this,"sparse");x(this,"maxEntities");this.maxEntities=t,this.denseBuffer=new Kp((co+t)*4),this.dense=new Uint32Array(this.denseBuffer),this.dense[ur]=0,this.sparseBuffer=new Kp(t*4),this.sparse=new Uint32Array(this.sparseBuffer),this.sparse.fill(Xs)}get count(){return this.dense[ur]}add(t){const e=this.sparse;if(e[t]!==Xs)return;const n=this.dense,r=n[ur];if(r>=this.maxEntities)throw new Error("QueryCache is full");n[co+r]=t,e[t]=r,n[ur]=r+1}remove(t){const e=this.sparse,n=e[t];if(n===Xs)return;const r=this.dense,s=r[ur]-1;if(n!==s){const i=r[co+s];r[co+n]=i,e[i]=n}e[t]=Xs,r[ur]=s}has(t){return this.sparse[t]!==Xs}clear(){const t=this.dense[ur];for(let e=0;e<t;e++){const n=this.dense[co+e];this.sparse[n]=Xs}this.dense[ur]=0}toArray(){const t=this.dense[ur],e=new Array(t);for(let n=0;n<t;n++)e[n]=this.dense[co+n];return e}getDenseView(){const t=this.dense[ur];return this.dense.subarray(co,co+t)}},_E=class{constructor(t,e){x(this,"cache");x(this,"lastIndex",0);x(this,"masks");this.masks=e,this.cache=new Yp(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===Le.REMOVED)i.remove(m);else if(y===Le.ADDED||y===Le.COMPONENT_ADDED||y===Le.COMPONENT_REMOVED){const v=r.has(m)&&r.matches(m,s),b=i.has(m);v&&!b?i.add(m):!v&&b&&i.remove(m)}}}},xE=(Us=class{constructor(e){x(this,"builder");x(this,"instances",{});x(this,"id");this.builder=e,this.id=`current_query_${Us.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 Zp(e.componentCount,e),i=this.builder(o)[Yu]();return r=new _E(e,i),this.instances[n]=r,r}current(e){return this._getInstance(e).current(e)}},x(Us,"queryCounter",0),Us);function TE(t){return new xE(t)}var qp=new Map;function ME(t){const e=t._defId;let n=qp.get(e);return n||(n=TE(r=>r.with(t)),qp.set(e,n)),n}function Bt(t){const e=t.pool.get();return t.entityBuffer.create(e),t.eventBuffer.pushAdded(e),e}function dr(t,e,n,r,o=!0){const s=n._getInstance(t),i=ME(n),a=s.buffer[r],l=[];for(const c of i.current(t))Wu(a[c],t.entityBuffer,o)===e&&l.push(c);return l}function st(t,e){t.entityBuffer.has(e)&&(t.eventBuffer.pushRemoved(e),t.entityBuffer.markDead(e))}function ee(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 mn(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 R(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 Je(t){return t.resources}function AE(t,e){return t.entityBuffer.has(e)}var IE=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,Le.CHANGED,e.tracking).entities.size>0&&this.changed.push(Js)}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 v={},b=1,S=2,k=3,E=n.hasTracking,_=n.tracking;for(let M=0;M<m;M++){const P=(h+M)%r*2,Z=f+M>=l,A=Atomics.load(s,P),F=Atomics.load(s,P+1),Y=F&255,ce=e.has(A),se=v[A];if(Y===Le.REMOVED){if(!c&&ce&&e.remove(A),Z)if(se===b){const j=g.indexOf(A);j!==-1&&(g[j]=g[g.length-1],g.length--),v[A]=S}else if(se===k&&ce){const j=w.indexOf(A);j!==-1&&(w[j]=w[w.length-1],w.length--),v[A]=S,y.push(A)}else!se&&ce&&(v[A]=S,y.push(A))}else if(Y===Le.ADDED){const j=o.matches(A,n);!c&&!ce&&j&&e.add(A),Z&&!se&&!ce&&j&&(v[A]=b,g.push(A))}else if(Y===Le.COMPONENT_ADDED||Y===Le.COMPONENT_REMOVED){const X=o.has(A)&&o.matches(A,n);c||(X&&!ce?e.add(A):!X&&ce&&e.remove(A)),Z&&!se&&(!ce&&X?(v[A]=b,g.push(A)):ce&&!X&&(v[A]=S,y.push(A)))}else if(Y===Le.CHANGED&&E&&Z&&!se&&ce){const j=F>>16&65535,X=j>>3,he=j&7;X<_.length&&_[X]&1<<he&&(v[A]=k,w.push(A))}}}},qu=[],NE=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 Yp(t.maxEntities)),this.reader=new IE(0)}current(t,e){if(this.isSingletonQuery)return[Js];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 qu;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 qu;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:qu}},BE=(Ws=class{constructor(e){x(this,"builder");x(this,"instances",{});x(this,"id");this.builder=e,this.id=`query_${Ws.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 NE(e,o),this.instances[n]=r,r}_getMasks(e){const n=new Zp(e.componentCount,e);return this.builder(n)[Yu]()}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(Ws,"queryCounter",0),Ws);function ie(t){return new BE(t)}var Jp=(Hs=class{constructor(){x(this,"id");this.id=Hs.systemCounter++}},x(Hs,"systemCounter",0),Hs),PE=class extends Jp{constructor(e){super();x(this,"type","main");x(this,"execute");this.execute=e}},OE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer,DE=(Ut=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 OE(o),this.view=new Uint8Array(this.buffer)}static fromTransfer(e,n){const r=Object.create(Ut.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)&Ut.GENERATION_MASK)>>Ut.GENERATION_SHIFT)+1&127;for(let l=0;l<o;l++)Atomics.store(r,n+l,0);Atomics.store(r,n,Ut.ALIVE_FLAG|a<<Ut.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)&Ut.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)&Ut.ALIVE_FLAG)!==0}getGeneration(e){const n=e*this.bytesPerEntity;return(Atomics.load(this.view,n)&Ut.GENERATION_MASK)>>Ut.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(Ut,"ALIVE_FLAG",1),x(Ut,"GENERATION_MASK",254),x(Ut,"GENERATION_SHIFT",1),Ut),RE=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function zE(t){return t===0?-1:31-Math.clz32(t&-t)}var $E=(We=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 RE((n+1)*4),o=new Int32Array(r);for(let i=We.DATA_OFFSET;i<n+We.DATA_OFFSET;i++)o[i]=-1;const s=e%32;if(s!==0){const i=n-1+We.DATA_OFFSET,a=(1<<s)-1;o[i]=a}return o[We.HINT_INDEX]=0,new We(r,n,e)}static fromTransfer(e,n,r){return new We(e,n,r)}getBuffer(){return this.buffer}getBucketCount(){return this.bucketCount}getSize(){return this.size}free(e){const n=(e>>5)+We.DATA_OFFSET,r=1<<(e&31);Atomics.or(this.view,n,r);const o=Atomics.load(this.view,We.HINT_INDEX),s=n-We.DATA_OFFSET;(o===-1||s<o)&&Atomics.store(this.view,We.HINT_INDEX,s)}get(){for(let e=0;e<this.bucketCount*2;e++){let n=Atomics.load(this.view,We.HINT_INDEX);n===-1&&(n=0);for(let r=0;r<this.bucketCount;r++){const o=(n+r)%this.bucketCount+We.DATA_OFFSET,s=Atomics.load(this.view,o);if(s===0)continue;const i=zE(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-We.DATA_OFFSET),(o-We.DATA_OFFSET<<5)+i}}throw Atomics.store(this.view,We.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+We.DATA_OFFSET;if(Atomics.load(this.view,r)!==0){Atomics.store(this.view,We.HINT_INDEX,r-We.DATA_OFFSET);return}}Atomics.store(this.view,We.HINT_INDEX,-1)}},x(We,"HINT_INDEX",0),x(We,"DATA_OFFSET",1),We),Gp=3,LE=.75,VE=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>Gp&&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>LE;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<Gp){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()}},FE=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()}},Xp={high:2,medium:1,low:0},jE=(Zs=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 FE(r);const a=new EE(s),l=new DE(o,i),c={};for(const u of e){const f=vE.fromDef(u);f.initialize(this.componentIndex++,o,a,l),c[u._defId]=f,this.componentIdToDef.set(this.componentIndex-1,u)}this.worldId=Zs.worldCounter++,this.history=new VE(s),this.context={entityBuffer:l,eventBuffer:a,components:c,maxEntities:o,maxEvents:s,componentCount:i,pool:$E.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 Jp?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)=>Xp[h.priority]-Xp[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,Le.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(Zs,"worldCounter",0),Zs),an={ECS:1,History:2,Persistence:3,Websocket:4},UE=1;function Qp(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 Ju(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=WE(c,l??null,i.migrations);u.changed&&(n||(n={...t}),n[r]={...u.data,_exists:!0,_version:u.version})}return n??t}function WE(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 Gu(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(!Gu(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=>Gu(n[i],r[i]))}return!1}function gn(...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 em(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 HE=1e3;async function tm(t,e,n){const r=await Tp(t,1,{upgrade(o){o.objectStoreNames.contains(e)||o.createObjectStore(e)}});return new ZE(r,e,n)}var ZE=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)??HE}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)}},KE=1e3/30,YE=1e3,qE=(Ir=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 tm(`${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:UE,...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!==an.Websocket&&o.origin!==an.Persistence&&o.syncBehavior!=="local"&&(o.syncBehavior==="ephemeral"?r.push(o.patch):n.push(o.patch));if(!this.isOnline){n.length>0&&(this.offlineBuffer=gn(this.offlineBuffer,...n),this.persistOfflineBuffer()),r.length>0&&(this.localEphemeralState=gn(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?KE:YE}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=gn(this.localEphemeralState,...n)),e.length===0&&n.length===0)return;const r=`${this.clientId}-${++this.messageCounter}`;e.length>0&&this.inFlight.set(r,gn(...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=gn(...this.pendingDocumentPatches);this.pendingDocumentPatches=[];const r=Ju(n,this.componentsByName),o=Ju(this.offlineBuffer,this.componentsByName),s=em(r,o);this.clearPersistedOfflineBuffer(),Object.keys(s).length>0&&e.push({patch:s,origin:an.Websocket,syncBehavior:"document"})}if(this.pendingEphemeralPatches.length>0){const n=gn(...this.pendingEphemeralPatches);this.pendingEphemeralPatches=[],e.push({patch:n,origin:an.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=Ir.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=Ir.MIN_RECONNECT_DELAY}catch{this.reconnectDelay=Math.min(this.reconnectDelay*2,Ir.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=gn(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=gn(...Array.from(this.inFlight.values())),r=[];for(const o of e){const s=em(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(Ir,"MIN_RECONNECT_DELAY",500),x(Ir,"MAX_RECONNECT_DELAY",1e4),Ir),qt=class extends Wp{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&&Qp(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 Qe(t,e){return new qt(t,e)}var vt=class extends kE{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&&Qp(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 Zi(t,e){return new vt(t,e)}var me=Hp({id:C.string().max(36)}),Xu="SINGLETON";function JE(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];Gu(s,i)||(n[o]=i,r=!0)}return r?n:null}var GE=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===Le.REMOVED){const y=this.entityToStableId.get(l);if(!y)continue;const w=`${y}/`;for(const v of Object.keys(this.prevState))if(v.startsWith(w)){const b=v.slice(w.length),S=this.componentsByName.get(b),k=s(S==null?void 0:S.sync);k[v]={_exists:!1},this.prevState[v]={_exists:!1}}this.stableIdToEntity.delete(y),this.entityToStableId.delete(l);continue}const f=this.componentMap.get(u);if(!f||!f.isSingleton&&!R(t,l,me,!1))continue;const h=me.read(t,l);let p;f.isSingleton?p=Xu:(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 Le.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 Le.COMPONENT_REMOVED:{if(f.isSingleton)continue;g[m]={_exists:!1},this.prevState[m]={_exists:!1};break}case Le.CHANGED:{const y=f.isSingleton?f.snapshot(t):f.snapshot(t,l),w=this.translateRefsOutbound(f,y),v=this.prevState[m]??{_exists:!1},b=JE(v,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:an.ECS,syncBehavior:"document"}),Object.keys(r).length>0&&i.push({patch:r,origin:an.ECS,syncBehavior:"ephemeral"}),Object.keys(o).length>0&&i.push({patch:o,origin:an.ECS,syncBehavior:"local"}),i}push(t){const e=this.ctx;for(const{patch:n,origin:r}of t)if(r!==an.ECS){for(const[o,s]of Object.entries(n)){if(!s._exists)continue;const i=o.indexOf("/"),a=o.slice(0,i);if(a!==Xu&&!this.stableIdToEntity.has(a)){const l=Bt(e);ee(e,l,me,{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===Xu){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)R(e,u,c,!1)&&mn(e,u,c),this.prevState[o]={_exists:!1};else if(s._exists){const f=this.translateRefsInbound(c,s);R(e,u,c,!1)?c.copy(e,u,f):ee(e,u,c,f),this.prevState[o]={...s}}else if(u!==void 0&&R(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(){}},XE=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===an.ECS&&r.syncBehavior!=="ephemeral"&&r.syncBehavior!=="local");for(const r of t)if(r.syncBehavior!=="ephemeral")if(r.origin===an.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=gn(this.pendingForward,s),this.pendingInverse=gn(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=gn(...this.pendingPullPatches);return this.pendingPullPatches=[],[{patch:t,origin:an.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=gn(...n.map(s=>s.forward)),o=gn(...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}},QE=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 tm(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=Ju(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!==an.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:an.Persistence,syncBehavior:"document"}),this.pendingDocumentPatch=null),this.pendingLocalPatch&&(t.push({patch:this.pendingLocalPatch,origin:an.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()}},nm=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 GE({components:t,singletons:e}),this.adapters.push(this.ecsAdapter),this.options.persistence&&(this.persistenceAdapter=new QE({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 XE({components:t,singletons:e,commitCheckpointAfterFrames:n.commitCheckpointAfterFrames,maxHistoryStackSize:n.maxHistoryStackSize}),this.adapters.push(this.historyAdapter)}this.options.websocket&&(this.websocketAdapter=new qE({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()}},Ae=0,Ie=1,Ne=2,Be=3,ne;(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[Ae],t.top=e=>e[Ie],t.right=e=>e[Ne],t.bottom=e=>e[Be],t.width=e=>e[Ne]-e[Ae],t.height=e=>e[Be]-e[Ie],t.center=e=>[(e[Ae]+e[Ne])/2,(e[Ie]+e[Be])/2],t.size=e=>[(0,t.width)(e),(0,t.height)(e)],t.corners=e=>[[e[Ae],e[Ie]],[e[Ne],e[Ie]],[e[Ne],e[Be]],[e[Ae],e[Be]]],t.containsPoint=(e,n,r=!0)=>r?n[0]>=e[Ae]&&n[0]<=e[Ne]&&n[1]>=e[Ie]&&n[1]<=e[Be]:n[0]>e[Ae]&&n[0]<e[Ne]&&n[1]>e[Ie]&&n[1]<e[Be],t.intersects=(e,n)=>!(e[Ne]<n[Ae]||e[Ae]>n[Ne]||e[Be]<n[Ie]||e[Ie]>n[Be]),t.contains=(e,n)=>e[Ae]<=n[Ae]&&e[Ie]<=n[Ie]&&e[Ne]>=n[Ne]&&e[Be]>=n[Be],t.distanceToPoint=(e,n)=>{const r=Math.max(e[Ae]-n[0],0,n[0]-e[Ne]),o=Math.max(e[Ie]-n[1],0,n[1]-e[Be]);return Math.hypot(r,o)},t.set=(e,n,r,o,s)=>{e[Ae]=n,e[Ie]=r,e[Ne]=o,e[Be]=s},t.copy=(e,n)=>{e[Ae]=n[Ae],e[Ie]=n[Ie],e[Ne]=n[Ne],e[Be]=n[Be]},t.expand=(e,n)=>{e[Ae]=Math.min(e[Ae],n[0]),e[Ie]=Math.min(e[Ie],n[1]),e[Ne]=Math.max(e[Ne],n[0]),e[Be]=Math.max(e[Be],n[1])},t.union=(e,n)=>{e[Ae]=Math.min(e[Ae],n[Ae]),e[Ie]=Math.min(e[Ie],n[Ie]),e[Ne]=Math.max(e[Ne],n[Ne]),e[Be]=Math.max(e[Be],n[Be])},t.intersection=(e,n)=>{e[Ae]=Math.max(e[Ae],n[Ae]),e[Ie]=Math.max(e[Ie],n[Ie]),e[Ne]=Math.min(e[Ne],n[Ne]),e[Be]=Math.min(e[Be],n[Be])},t.pad=(e,n)=>{e[Ae]-=n,e[Ie]-=n,e[Ne]+=n,e[Be]+=n},t.setFromPoints=(e,n)=>{if(n.length===0){e[Ae]=0,e[Ie]=0,e[Ne]=0,e[Be]=0;return}e[Ae]=n[0][0],e[Ie]=n[0][1],e[Ne]=n[0][0],e[Be]=n[0][1];for(let r=1;r<n.length;r++){const[o,s]=n[r];o<e[Ae]&&(e[Ae]=o),s<e[Ie]&&(e[Ie]=s),o>e[Ne]&&(e[Ne]=o),s>e[Be]&&(e[Be]=s)}},t.translate=(e,n)=>{e[Ae]+=n[0],e[Ie]+=n[1],e[Ne]+=n[0],e[Be]+=n[1]},t.scale=(e,n)=>{e[Ae]*=n,e[Ie]*=n,e[Ne]*=n,e[Be]*=n}})(ne||(ne={}));var yn=0,wn=1,Pr=2,Or=3,vn=4,kn=5,fr=6,Re;(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[yn],e[wn]],t.b=e=>[e[Pr],e[Or]],t.c=e=>[e[vn],e[kn]],t.thickness=e=>e[fr],t.isCollinear=e=>{const n=(e[yn]-e[vn])*(e[Or]-e[kn])-(e[Pr]-e[vn])*(e[wn]-e[kn]);return Math.abs(n)<1e-8},t.computeCenter=e=>{const n=e[yn],r=e[wn],o=e[Pr],s=e[Or],i=e[vn],a=e[kn],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[yn],o=e[wn],s=e[Pr],i=e[Or],a=e[vn],l=e[kn],c=Math.hypot(s-n[0],i-n[1]),u=(s-r)*(l-o)-(i-o)*(a-r)<0,f=eC(e,n);let h=Math.atan2(o-n[1],r-n[0]);h=es(h);let p=h+f*(u?-1:1);return p=es(p),{center:n,radius:c,clockwise:u,arcAngle:f,startAngle:h,endAngle:p}},t.inArcAngle=(e,n,r,o)=>(e=es(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[fr]/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[fr]/2,u=(0,t.a)(e),f=(0,t.b)(e),h=(0,t.c)(e);if(Qu(n,u)||Qu(n,f)||Qu(n,h))return!0;const p=s-c,m=s+c;if(!tC(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 v=g[w],b=g[(w+1)%g.length],S=om(v,b,o,y);for(const k of S){const E=Math.atan2(k[1]-o[1],k[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[fr]/2,h=a-f,p=a+f;for(const m of[p,h]){const g=rm(i,m,n),y=rm(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 om(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=es(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[yn]+n*(e[vn]-e[yn]),e[wn]+n*(e[kn]-e[wn])];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[vn]-e[yn],e[kn]-e[wn])},t.directionAt=(e,n)=>{const r=(0,t.compute)(e);if(!r){const c=e[vn]-e[yn],u=e[kn]-e[wn],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[fr]/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[yn]=n,e[wn]=r,e[Pr]=o,e[Or]=s,e[vn]=i,e[kn]=a,e[fr]=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[yn]=n,e[wn]=r},t.setB=(e,n,r)=>{e[Pr]=n,e[Or]=r},t.setC=(e,n,r)=>{e[vn]=n,e[kn]=r},t.setThickness=(e,n)=>{e[fr]=n},t.setFromPoints=(e,n,r,o,s)=>{e[yn]=n[0],e[wn]=n[1],e[Pr]=r[0],e[Or]=r[1],e[vn]=o[0],e[kn]=o[1],e[fr]=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[fr];e[yn]=o[0],e[wn]=o[1],e[Pr]=s[0],e[Or]=s[1],e[vn]=i[0],e[kn]=i[1],e[fr]=a}})(Re||(Re={}));function es(t){for(;t<0;)t+=2*Math.PI;for(;t>=2*Math.PI;)t-=2*Math.PI;return t}function eC(t,e){const n=t[yn],r=t[wn],o=t[Pr],s=t[Or],i=t[vn],a=t[kn],l=es(Math.atan2(r-e[1],n-e[0])),c=es(Math.atan2(s-e[1],o-e[0])),u=es(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 Qu(t,e){return e[0]>=t[0]&&e[0]<=t[2]&&e[1]>=t[1]&&e[1]<=t[3]}function rm(t,e,n){const r=n[0]-t[0],o=n[1]-t[1];return r*r+o*o<=e*e}function tC(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 om(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 $;(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)}})($||($={}));var it=0,at=1,Pt=2,Ot=3,hr=4,ht;(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[it],e[at]],t.pointB=e=>[e[Pt],e[Ot]],t.radius=e=>e[hr],t.center=e=>[(e[it]+e[Pt])/2,(e[at]+e[Ot])/2],t.length=e=>{const n=e[Pt]-e[it],r=e[Ot]-e[at];return Math.hypot(n,r)},t.bounds=e=>{const n=e[hr];return[Math.min(e[it],e[Pt])-n,Math.min(e[at],e[Ot])-n,Math.max(e[it],e[Pt])+n,Math.max(e[at],e[Ot])+n]},t.getExtrema=e=>{const n=e[it],r=e[at],o=e[Pt],s=e[Ot],i=e[hr];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[it],e[at],e[Pt],e[Ot],n[0],n[1]);return[e[it]+r*(e[Pt]-e[it]),e[at]+r*(e[Ot]-e[at])]},t.distanceToPoint=(e,n)=>{const r=(0,t.closestPointOnCenterLine)(e,n);return $.distance(r,n)},t.containsPoint=(e,n)=>(0,t.distanceToPoint)(e,n)<=e[hr],t.intersectsAabb=(e,n)=>{const r=e[hr],o=(0,t.bounds)(e);if(!ne.intersects(o,n))return!1;const s=e[Pt]-e[it],i=e[Ot]-e[at],a=s*s+i*i;if(a===0)return ne.distanceToPoint(n,[e[it],e[at]])<=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[it]+u*s,h=e[at]+u*i;if(ne.distanceToPoint(n,[f,h])<=r)return!0}return!1},t.intersectsCapsule=(e,n)=>(0,t.segmentToSegmentDistance)(e[it],e[at],e[Pt],e[Ot],n[it],n[at],n[Pt],n[Ot])<=e[hr]+n[hr],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,v=c*p+u*m,b=f*p+h*m,S=g*w-y*y;let k,E;S<1e-10?(k=0,E=b/w):(k=(y*b-w*v)/S,E=(g*b-y*v)/S),k=Math.max(0,Math.min(1,k)),E=Math.max(0,Math.min(1,E)),(k<0||k>1)&&(E=(y*k+b)/w,E=Math.max(0,Math.min(1,E)),k=(y*E-v)/g,k=Math.max(0,Math.min(1,k)));const _=e+k*c,M=n+k*u,I=s+E*f,P=i+E*h;return Math.hypot(I-_,P-M)},t.set=(e,n,r,o,s,i)=>{e[it]=n,e[at]=r,e[Pt]=o,e[Ot]=s,e[hr]=i},t.copy=(e,n)=>{e[it]=n[it],e[at]=n[at],e[Pt]=n[Pt],e[Ot]=n[Ot],e[hr]=n[hr]},t.translate=(e,n)=>{e[it]+=n[0],e[at]+=n[1],e[Pt]+=n[0],e[Ot]+=n[1]},t.trim=(e,n,r)=>{const o=e[it],s=e[at],i=e[Pt],a=e[Ot],l=i-o,c=a-s;e[it]=o+n*l,e[at]=s+n*c,e[Pt]=o+r*l,e[Ot]=s+r*c}})(ht||(ht={}));var ze;(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}})(ze||(ze={}));var J=0,G=1,pt;(t=>{t.getCenter=(e,n,r)=>{r[J]=e[J]+n[J]/2,r[G]=e[G]+n[G]/2},t.getCorners=(e,n,r,o)=>{const s=n[J]/2,i=n[G]/2,a=e[J]+s,l=e[G]+i,c=Math.cos(r),u=Math.sin(r);o[0][J]=a+-s*c- -i*u,o[0][G]=l+-s*u+-i*c,o[1][J]=a+s*c- -i*u,o[1][G]=l+s*u+-i*c,o[2][J]=a+s*c-i*u,o[2][G]=l+s*u+i*c,o[3][J]=a+-s*c-i*u,o[3][G]=l+-s*u+i*c},t.getAabb=(e,n,r,o)=>{const s=n[J]/2,i=n[G]/2,a=e[J]+s,l=e[G]+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,v=l+-s*u+i*c;o[0]=Math.min(f,p,g,w),o[1]=Math.min(h,m,y,v),o[2]=Math.max(f,p,g,w),o[3]=Math.max(h,m,y,v)},t.uvToWorld=(e,n,r,o)=>{const s=[(o[J]-.5)*n[J],(o[G]-.5)*n[G]];$.rotate(s,r);const i=[0,0];return(0,t.getCenter)(e,n,i),$.add(s,i),s},t.worldToUv=(e,n,r,o)=>{const s=[0,0];(0,t.getCenter)(e,n,s);const i=$.clone(o);return $.sub(i,s),$.rotate(i,-r),$.divide(i,n),$.addScalar(i,.5),i},t.getUvToWorldMatrix=(e,n,r,o)=>{const s=Math.cos(r),i=Math.sin(r),a=n[J],l=n[G],c=e[J]+a/2,u=e[G]+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[J]/2,i=n[G]/2,a=e[J]+s,l=e[G]+i,c=o[J]-a,u=o[G]-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[J]/2,c=n[G]/2,u=e[J]+l,f=e[G]+c,h=Math.cos(r),p=Math.sin(r);i[0][J]=o[0],i[0][G]=o[1],i[1][J]=o[2],i[1][G]=o[1],i[2][J]=o[2],i[2][G]=o[3],i[3][J]=o[0],i[3][G]=o[3],s[0][J]=u+-l*h- -c*p,s[0][G]=f+-l*p+-c*h,s[1][J]=u+l*h- -c*p,s[1][G]=f+l*p+-c*h,s[2][J]=u+l*h-c*p,s[2][G]=f+l*p+c*h,s[3][J]=u+-l*h-c*p,s[3][G]=f+-l*p+c*h;const m=s[1][J]-s[0][J],g=s[1][G]-s[0][G],y=Math.sqrt(m*m+g*g);y>0&&(a[0][J]=-g/y,a[0][G]=m/y);const w=s[2][J]-s[1][J],v=s[2][G]-s[1][G],b=Math.sqrt(w*w+v*v);return b>0&&(a[1][J]=-v/b,a[1][G]=w/b),!(ml(i,s,1,0)||ml(i,s,0,1)||ml(i,s,a[0][J],a[0][G])||ml(i,s,a[1][J],a[1][G]))},t.setCenter=(e,n,r)=>{e[J]=r[J]-n[J]/2,e[G]=r[G]-n[G]/2},t.translate=(e,n)=>{e[J]+=n[J],e[G]+=n[G]},t.scaleBy=(e,n,r)=>{const o=e[J]+n[J]/2,s=e[G]+n[G]/2;n[J]*=r,n[G]*=r,e[J]=o-n[J]/2,e[G]=s-n[G]/2},t.scaleAround=(e,n,r,o)=>{const s=e[J]+n[J]/2,i=e[G]+n[G]/2,a=r[J]+(s-r[J])*o,l=r[G]+(i-r[G])*o;n[J]*=o,n[G]*=o,e[J]=a-n[J]/2,e[G]=l-n[G]/2},t.rotateAround=(e,n,r,o,s)=>{const i=e[J]+n[J]/2,a=e[G]+n[G]/2,l=i-o[J],c=a-o[G],u=Math.cos(s),f=Math.sin(s),h=o[J]+l*u-c*f,p=o[G]+l*f+c*u;return e[J]=h-n[J]/2,e[G]=p-n[G]/2,r+s},t.boundPoints=(e,n,r,o)=>{if(o.length===0)return;if(r===0){let b=o[0][J],S=o[0][G],k=b,E=S;for(let _=1;_<o.length;_++){const M=o[_][J],I=o[_][G];M<b&&(b=M),I<S&&(S=I),M>k&&(k=M),I>E&&(E=I)}e[J]=b,e[G]=S,n[J]=k-b,n[G]=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[J]*s-b[G]*i,k=b[J]*i+b[G]*s;S<a&&(a=S),k<l&&(l=k),S>c&&(c=S),k>u&&(u=k)}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,v=f*y+h*g;e[J]=w-p/2,e[G]=v-m/2,n[J]=p,n[G]=m}})(pt||(pt={}));function ml(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 Dr=0,Rr=1,uo=2,fo=3,kt;(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[Dr],n[Rr]],t.direction=n=>[n[uo],n[fo]],t.set=(n,r,o,s,i)=>{n[Dr]=r,n[Rr]=o,n[uo]=s,n[fo]=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[Dr]=r[0],n[Rr]=r[1]},t.setDirection=(n,r)=>{n[uo]=r[0],n[fo]=r[1]},t.pointAt=(n,r)=>[n[Dr]+n[uo]*r,n[Rr]+n[fo]*r],t.intersectSegment=(n,r,o)=>{const s=n[Dr],i=n[Rr],a=n[uo],l=n[fo],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 nC(n,r,o);const y=c-s,w=u-i,v=(y*m-w*p)/g,b=(y*l-w*a)/g;if(v>=0&&b>=0&&b<=1){const S=s+v*a,k=i+v*l;return{point:[S,k],distance:v*Math.sqrt(a*a+l*l)}}return null},t.intersectAabb=(n,r)=>{const o=[],s=n[Dr],i=n[Rr],a=n[uo],l=n[fo],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)=>{pt.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}})(kt||(kt={}));function nC(t,e,n){const r=t[Dr],o=t[Rr],s=t[uo],i=t[fo];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]?sm(t,e,n,0):s===0&&e[0]===n[0]&&r===e[0]?sm(t,e,n,1):null}function sm(t,e,n,r){const o=r===0?t[Dr]:t[Rr],s=r===0?t[uo]:t[fo],i=Math.min(e[r],n[r]),a=Math.max(e[r],n[r]);if(o>=i&&o<=a)return{point:[t[Dr],t[Rr]],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 ed=Math.PI*2,Dt;(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%ed;return n<0?n+ed:n},t.normalizeAngleSigned=e=>{const n=(0,t.normalizeAngle)(e);return n>Math.PI?n-ed: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})(Dt||(Dt={}));function N(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 Qs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class im extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const am={};function ho(t){return am}function lm(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 td(t,e){return typeof e=="bigint"?e.toString():e}function nd(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function rd(t){return t==null}function od(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function rC(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 cm=Symbol("evaluating");function Oe(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==cm)return r===void 0&&(r=cm,r=n()),r},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function ts(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function po(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function um(t){return JSON.stringify(t)}function oC(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const dm="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function gl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const sC=nd(()=>{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 ei(t){if(gl(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(gl(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function fm(t){return ei(t)?{...t}:Array.isArray(t)?[...t]:t}const iC=new Set(["string","number","symbol"]);function yl(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mo(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 re(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 aC(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const lC={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 cC(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=po(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 ts(this,"shape",i),i},checks:[]});return mo(t,s)}function uC(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=po(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 ts(this,"shape",i),i},checks:[]});return mo(t,s)}function dC(t,e){if(!ei(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=po(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return ts(this,"shape",s),s}});return mo(t,o)}function fC(t,e){if(!ei(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=po(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return ts(this,"shape",r),r}});return mo(t,n)}function hC(t,e){const n=po(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return ts(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return mo(t,n)}function pC(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=po(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 ts(this,"shape",l),l},checks:[]});return mo(e,i)}function mC(t,e,n){const r=po(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 ts(this,"shape",s),s}});return mo(e,r)}function ti(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 ns(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function wl(t){return typeof t=="string"?t:t==null?void 0:t.message}function go(t,e,n){var o,s,i,a,l,c;const r={...t,path:t.path??[]};if(!t.message){const u=wl((i=(s=(o=t.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:i.call(s,t))??wl((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??wl((l=n.customError)==null?void 0:l.call(n,t))??wl((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 sd(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ki(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const hm=(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,td,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},pm=N("$ZodError",hm),vl=N("$ZodError",hm,{Parent:Error});function gC(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 yC(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 kl=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 Qs;if(i.issues.length){const a=new((o==null?void 0:o.Err)??t)(i.issues.map(l=>go(l,s,ho())));throw dm(a,o==null?void 0:o.callee),a}return i.value},mm=kl(vl),bl=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=>go(l,s,ho())));throw dm(a,o==null?void 0:o.callee),a}return i.value},gm=bl(vl),Sl=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 Qs;return s.issues.length?{success:!1,error:new(t??pm)(s.issues.map(i=>go(i,o,ho())))}:{success:!0,data:s.value}},wC=Sl(vl),El=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=>go(i,o,ho())))}:{success:!0,data:s.value}},vC=El(vl),kC=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return kl(t)(e,n,o)},bC=t=>(e,n,r)=>kl(t)(e,n,r),SC=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return bl(t)(e,n,o)},EC=t=>async(e,n,r)=>bl(t)(e,n,r),CC=t=>(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Sl(t)(e,n,o)},_C=t=>(e,n,r)=>Sl(t)(e,n,r),xC=t=>async(e,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return El(t)(e,n,o)},TC=t=>async(e,n,r)=>El(t)(e,n,r),MC=/^[cC][^\s-]{8,}$/,AC=/^[0-9a-z]+$/,IC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,NC=/^[0-9a-vA-V]{20}$/,BC=/^[A-Za-z0-9]{27}$/,PC=/^[a-zA-Z0-9_-]{21}$/,OC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,DC=/^([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})$/,ym=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)$/,RC=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,zC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $C(){return new RegExp(zC,"u")}const LC=/^(?:(?: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])$/,VC=/^(([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}|:))$/,FC=/^((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])$/,jC=/^(([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])$/,UC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wm=/^[A-Za-z0-9_-]*$/,WC=/^\+[1-9]\d{6,14}$/,vm="(?:(?:\\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])))",HC=new RegExp(`^${vm}$`);function km(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 ZC(t){return new RegExp(`^${km(t)}$`)}function KC(t){const e=km({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(`^${vm}T(?:${r})$`)}const YC=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}$`)},qC=/^-?\d+$/,bm=/^-?\d+(?:\.\d+)?$/,JC=/^(?:true|false)$/i,GC=/^[^A-Z]*$/,XC=/^[^a-z]*$/,ln=N("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Sm={number:"number",bigint:"bigint",object:"date"},Em=N("$ZodCheckLessThan",(t,e)=>{ln.init(t,e);const n=Sm[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})}}),Cm=N("$ZodCheckGreaterThan",(t,e)=>{ln.init(t,e);const n=Sm[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})}}),QC=N("$ZodCheckMultipleOf",(t,e)=>{ln.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):rC(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})}}),e_=N("$ZodCheckNumberFormat",(t,e)=>{var i;ln.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]=lC[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=qC)}),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})}}),t_=N("$ZodCheckMaxLength",(t,e)=>{var n;ln.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!rd(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=sd(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),n_=N("$ZodCheckMinLength",(t,e)=>{var n;ln.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!rd(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=sd(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),r_=N("$ZodCheckLengthEquals",(t,e)=>{var n;ln.init(t,e),(n=t._zod.def).when??(n.when=r=>{const o=r.value;return!rd(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=sd(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})}}),Cl=N("$ZodCheckStringFormat",(t,e)=>{var n,r;ln.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=()=>{})}),o_=N("$ZodCheckRegex",(t,e)=>{Cl.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})}}),s_=N("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=GC),Cl.init(t,e)}),i_=N("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=XC),Cl.init(t,e)}),a_=N("$ZodCheckIncludes",(t,e)=>{ln.init(t,e);const n=yl(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})}}),l_=N("$ZodCheckStartsWith",(t,e)=>{ln.init(t,e);const n=new RegExp(`^${yl(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})}}),c_=N("$ZodCheckEndsWith",(t,e)=>{ln.init(t,e);const n=new RegExp(`.*${yl(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})}}),u_=N("$ZodCheckOverwrite",(t,e)=>{ln.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class d_{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
|
|
4
|
-
if (${
|
|
3
|
+
`))}}const f_={major:4,minor:3,patch:6},He=N("$ZodType",(t,e)=>{var o;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=f_;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=ti(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 Qs;if(f||m instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await m,a.issues.length!==p&&(u||(u=ti(a,p)))});else{if(a.issues.length===p)continue;u||(u=ti(a,p))}}return f?f.then(()=>a):a},i=(a,l,c)=>{if(ti(a))return a.aborted=!0,a;const u=s(l,r,c);if(u instanceof Promise){if(c.async===!1)throw new Qs;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 Qs;return c.then(u=>s(u,r,l))}return s(c,r,l)}}Oe(t,"~standard",()=>({validate:s=>{var i;try{const a=wC(t,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return vC(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}))}),id=N("$ZodString",(t,e)=>{var n;He.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??YC(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}}),Ge=N("$ZodStringFormat",(t,e)=>{Cl.init(t,e),id.init(t,e)}),h_=N("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=DC),Ge.init(t,e)}),p_=N("$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=ym(r))}else e.pattern??(e.pattern=ym());Ge.init(t,e)}),m_=N("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=RC),Ge.init(t,e)}),g_=N("$ZodURL",(t,e)=>{Ge.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})}}}),y_=N("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=$C()),Ge.init(t,e)}),w_=N("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=PC),Ge.init(t,e)}),v_=N("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=MC),Ge.init(t,e)}),k_=N("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=AC),Ge.init(t,e)}),b_=N("$ZodULID",(t,e)=>{e.pattern??(e.pattern=IC),Ge.init(t,e)}),S_=N("$ZodXID",(t,e)=>{e.pattern??(e.pattern=NC),Ge.init(t,e)}),E_=N("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=BC),Ge.init(t,e)}),C_=N("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=KC(e)),Ge.init(t,e)}),__=N("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=HC),Ge.init(t,e)}),x_=N("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ZC(e)),Ge.init(t,e)}),T_=N("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=OC),Ge.init(t,e)}),M_=N("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=LC),Ge.init(t,e),t._zod.bag.format="ipv4"}),A_=N("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=VC),Ge.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})}}}),I_=N("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=FC),Ge.init(t,e)}),N_=N("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=jC),Ge.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 _m(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const B_=N("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=UC),Ge.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{_m(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function P_(t){if(!wm.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return _m(n)}const O_=N("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=wm),Ge.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{P_(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),D_=N("$ZodE164",(t,e)=>{e.pattern??(e.pattern=WC),Ge.init(t,e)});function R_(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 z_=N("$ZodJWT",(t,e)=>{Ge.init(t,e),t._zod.check=n=>{R_(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),xm=N("$ZodNumber",(t,e)=>{He.init(t,e),t._zod.pattern=t._zod.bag.pattern??bm,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}}),$_=N("$ZodNumberFormat",(t,e)=>{e_.init(t,e),xm.init(t,e)}),L_=N("$ZodBoolean",(t,e)=>{He.init(t,e),t._zod.pattern=JC,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}}),V_=N("$ZodUnknown",(t,e)=>{He.init(t,e),t._zod.parse=n=>n}),F_=N("$ZodNever",(t,e)=>{He.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Tm(t,e,n){t.issues.length&&e.issues.push(...ns(n,t.issues)),e.value[n]=t.value}const j_=N("$ZodArray",(t,e)=>{He.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=>Tm(c,n,i))):Tm(l,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function _l(t,e,n,r,o){if(t.issues.length){if(o&&!(n in r))return;e.issues.push(...ns(n,t.issues))}t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function Mm(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=aC(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function Am(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=>_l(p,n,f,e,u))):_l(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 U_=N("$ZodObject",(t,e)=>{He.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=nd(()=>Mm(e));Oe(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=gl,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=>_l(y,a,h,c,m))):_l(g,a,h,c,m)}return s?Am(u,c,a,l,r.value,t):u.length?Promise.all(u).then(()=>a):a}}),W_=N("$ZodObjectJIT",(t,e)=>{U_.init(t,e);const n=t._zod.parse,r=nd(()=>Mm(e)),o=h=>{var b;const p=new d_(["shape","payload","ctx"]),m=r.value,g=S=>{const k=um(S);return`shape[${k}]._zod.run({ value: input[${k}], 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 k=y[S],E=um(S),_=h[S],M=((b=_==null?void 0:_._zod)==null?void 0:b.optout)==="optional";p.write(`const ${k} = ${g(S)};`),M?p.write(`
|
|
4
|
+
if (${k}.issues.length) {
|
|
5
5
|
if (${E} in input) {
|
|
6
|
-
payload.issues = payload.issues.concat(${
|
|
6
|
+
payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
7
7
|
...iss,
|
|
8
8
|
path: iss.path ? [${E}, ...iss.path] : [${E}]
|
|
9
9
|
})));
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
if (${
|
|
13
|
+
if (${k}.value === undefined) {
|
|
14
14
|
if (${E} in input) {
|
|
15
15
|
newResult[${E}] = undefined;
|
|
16
16
|
}
|
|
17
17
|
} else {
|
|
18
|
-
newResult[${E}] = ${
|
|
18
|
+
newResult[${E}] = ${k}.value;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
`):p.write(`
|
|
22
|
-
if (${
|
|
23
|
-
payload.issues = payload.issues.concat(${
|
|
22
|
+
if (${k}.issues.length) {
|
|
23
|
+
payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
24
24
|
...iss,
|
|
25
25
|
path: iss.path ? [${E}, ...iss.path] : [${E}]
|
|
26
26
|
})));
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
if (${
|
|
29
|
+
if (${k}.value === undefined) {
|
|
30
30
|
if (${E} in input) {
|
|
31
31
|
newResult[${E}] = undefined;
|
|
32
32
|
}
|
|
33
33
|
} else {
|
|
34
|
-
newResult[${E}] = ${
|
|
34
|
+
newResult[${E}] = ${k}.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=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>
|
|
37
|
+
`)}p.write("payload.value = newResult;"),p.write("return payload;");const v=p.compile();return(S,k)=>v(h,S,k)};let s;const i=gl,a=!am.jitless,c=a&&sC.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?Am([],m,h,p,f,t):h):n(h,p):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),h)}});function Im(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=>!ti(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=>go(i,r,ho())))}),e)}const H_=N("$ZodUnion",(t,e)=>{He.init(t,e),Oe(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Oe(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Oe(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),Oe(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=>od(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=>Im(l,o,t,s)):Im(a,o,t,s)}}),Z_=N("$ZodIntersection",(t,e)=>{He.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])=>Nm(n,l,c)):Nm(n,s,i)}});function ad(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(ei(t)&&ei(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=ad(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=ad(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 Nm(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}),ti(t))return t;const i=ad(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 Bm=N("$ZodTuple",(t,e)=>{He.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=>xl(h,r,c))):xl(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=>xl(p,r,c))):xl(h,r,c)}}return i.length?Promise.all(i).then(()=>r):r}});function xl(t,e,n){t.issues.length&&e.issues.push(...ns(n,t.issues)),e.value[n]=t.value}const K_=N("$ZodRecord",(t,e)=>{He.init(t,e),t._zod.parse=(n,r)=>{const o=n.value;if(!ei(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(...ns(c,f.issues)),n.value[c]=f.value})):(u.issues.length&&n.issues.push(...ns(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"&&bm.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=>go(f,r,ho())),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(...ns(a,f.issues)),n.value[l.value]=f.value})):(u.issues.length&&n.issues.push(...ns(a,u.issues)),n.value[l.value]=u.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Y_=N("$ZodEnum",(t,e)=>{He.init(t,e);const n=lm(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(o=>iC.has(typeof o)).map(o=>typeof o=="string"?yl(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}}),q_=N("$ZodTransform",(t,e)=>{He.init(t,e),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new im(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 Qs;return n.value=o,n}});function Pm(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const Om=N("$ZodOptional",(t,e)=>{He.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Oe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Oe(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${od(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=>Pm(s,n.value)):Pm(o,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),J_=N("$ZodExactOptional",(t,e)=>{Om.init(t,e),Oe(t._zod,"values",()=>e.innerType._zod.values),Oe(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),G_=N("$ZodNullable",(t,e)=>{He.init(t,e),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${od(n.source)}|null)$`):void 0}),Oe(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)}),X_=N("$ZodDefault",(t,e)=>{He.init(t,e),t._zod.optin="optional",Oe(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=>Dm(s,e)):Dm(o,e)}});function Dm(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Q_=N("$ZodPrefault",(t,e)=>{He.init(t,e),t._zod.optin="optional",Oe(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))}),ex=N("$ZodNonOptional",(t,e)=>{He.init(t,e),Oe(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=>Rm(s,t)):Rm(o,t)}});function Rm(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 tx=N("$ZodCatch",(t,e)=>{He.init(t,e),Oe(t._zod,"optin",()=>e.innerType._zod.optin),Oe(t._zod,"optout",()=>e.innerType._zod.optout),Oe(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=>go(i,r,ho()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>go(s,r,ho()))},input:n.value}),n.issues=[]),n)}}),nx=N("$ZodPipe",(t,e)=>{He.init(t,e),Oe(t._zod,"values",()=>e.in._zod.values),Oe(t._zod,"optin",()=>e.in._zod.optin),Oe(t._zod,"optout",()=>e.out._zod.optout),Oe(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=>Tl(i,e.in,r)):Tl(s,e.in,r)}const o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Tl(s,e.out,r)):Tl(o,e.out,r)}});function Tl(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const rx=N("$ZodReadonly",(t,e)=>{He.init(t,e),Oe(t._zod,"propValues",()=>e.innerType._zod.propValues),Oe(t._zod,"values",()=>e.innerType._zod.values),Oe(t._zod,"optin",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Oe(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(zm):zm(o)}});function zm(t){return t.value=Object.freeze(t.value),t}const ox=N("$ZodFunction",(t,e)=>(He.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?mm(t._def.input,r):r,s=Reflect.apply(n,this,o);return t._def.output?mm(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 gm(t._def.input,r):r,s=await Reflect.apply(n,this,o);return t._def.output?await gm(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 Bm({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)),sx=N("$ZodCustom",(t,e)=>{ln.init(t,e),He.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=>$m(s,n,r,t));$m(o,n,r,t)}});function $m(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(Ki(o))}}var Lm;class ix{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 ax(){return new ix}(Lm=globalThis).__zod_globalRegistry??(Lm.__zod_globalRegistry=ax());const Yi=globalThis.__zod_globalRegistry;function lx(t,e){return new t({type:"string",...re(e)})}function cx(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...re(e)})}function Vm(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...re(e)})}function ux(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...re(e)})}function dx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(e)})}function fx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(e)})}function hx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(e)})}function px(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...re(e)})}function mx(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...re(e)})}function gx(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(e)})}function yx(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...re(e)})}function wx(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(e)})}function vx(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...re(e)})}function kx(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...re(e)})}function bx(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(e)})}function Sx(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(e)})}function Ex(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(e)})}function Cx(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(e)})}function _x(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(e)})}function xx(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...re(e)})}function Tx(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...re(e)})}function Mx(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...re(e)})}function Ax(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...re(e)})}function Ix(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(e)})}function Nx(t,e){return new t({type:"string",format:"date",check:"string_format",...re(e)})}function Bx(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...re(e)})}function Px(t,e){return new t({type:"string",format:"duration",check:"string_format",...re(e)})}function Ox(t,e){return new t({type:"number",checks:[],...re(e)})}function Dx(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...re(e)})}function Rx(t,e){return new t({type:"boolean",...re(e)})}function zx(t){return new t({type:"unknown"})}function $x(t,e){return new t({type:"never",...re(e)})}function Fm(t,e){return new Em({check:"less_than",...re(e),value:t,inclusive:!1})}function ld(t,e){return new Em({check:"less_than",...re(e),value:t,inclusive:!0})}function jm(t,e){return new Cm({check:"greater_than",...re(e),value:t,inclusive:!1})}function cd(t,e){return new Cm({check:"greater_than",...re(e),value:t,inclusive:!0})}function Um(t,e){return new QC({check:"multiple_of",...re(e),value:t})}function Wm(t,e){return new t_({check:"max_length",...re(e),maximum:t})}function Ml(t,e){return new n_({check:"min_length",...re(e),minimum:t})}function Hm(t,e){return new r_({check:"length_equals",...re(e),length:t})}function Lx(t,e){return new o_({check:"string_format",format:"regex",...re(e),pattern:t})}function Vx(t){return new s_({check:"string_format",format:"lowercase",...re(t)})}function Fx(t){return new i_({check:"string_format",format:"uppercase",...re(t)})}function jx(t,e){return new a_({check:"string_format",format:"includes",...re(e),includes:t})}function Ux(t,e){return new l_({check:"string_format",format:"starts_with",...re(e),prefix:t})}function Wx(t,e){return new c_({check:"string_format",format:"ends_with",...re(e),suffix:t})}function ni(t){return new u_({check:"overwrite",tx:t})}function Hx(t){return ni(e=>e.normalize(t))}function Zx(){return ni(t=>t.trim())}function Kx(){return ni(t=>t.toLowerCase())}function Yx(){return ni(t=>t.toUpperCase())}function qx(){return ni(t=>oC(t))}function Jx(t,e,n){return new t({type:"array",element:e,...re(n)})}function Gx(t,e,n){const r=re(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Xx(t,e,n){return new t({type:"custom",check:"custom",fn:e,...re(n)})}function Qx(t){const e=eT(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ki(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(Ki(o))}},t(n.value,n)));return e}function eT(t,e){const n=new ln({check:"custom",...re(e)});return n._zod.check=t,n}function Zm(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)??Yi,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 rt(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),rt(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"&&Jt(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 Km(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 v=u[1].defId??u[1].schema.id??`schema${t.counter++}`;return u[1].defId=v,{defId:v,ref:`${w("__shared")}#/${f}/${v}`}}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 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=`
|
|
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 Ym(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 v in f)v==="$ref"||v==="allOf"||v in h||delete f[v];if(y.$ref&&g.def)for(const v in f)v==="$ref"||v==="allOf"||v in g.def&&JSON.stringify(f[v])===JSON.stringify(g.def[v])&&delete f[v]}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:Al(e,"input",t.processors),output:Al(e,"output",t.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function Jt(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 Jt(r.element,n);if(r.type==="set")return Jt(r.valueType,n);if(r.type==="lazy")return Jt(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 Jt(r.innerType,n);if(r.type==="intersection")return Jt(r.left,n)||Jt(r.right,n);if(r.type==="record"||r.type==="map")return Jt(r.keyType,n)||Jt(r.valueType,n);if(r.type==="pipe")return Jt(r.in,n)||Jt(r.out,n);if(r.type==="object"){for(const o in r.shape)if(Jt(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(const o of r.options)if(Jt(o,n))return!0;return!1}if(r.type==="tuple"){for(const o of r.items)if(Jt(o,n))return!0;return!!(r.rest&&Jt(r.rest,n))}return!1}const tT=(t,e={})=>n=>{const r=Zm({...n,processors:e});return rt(t,r),Km(r,t),Ym(r,t)},Al=(t,e,n={})=>r=>{const{libraryOptions:o,target:s}=r??{},i=Zm({...o??{},target:s,io:e,processors:n});return rt(t,i),Km(i,t),Ym(i,t)},nT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rT=(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=nT[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}))])}},oT=(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)},sT=(t,e,n,r)=>{n.type="boolean"},iT=(t,e,n,r)=>{n.not={}},aT=(t,e,n,r)=>{},lT=(t,e,n,r)=>{const o=t._zod.def,s=lm(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},cT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},uT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},dT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},fT=(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=rt(s.element,e,{...r,path:[...r.path,"items"]})},hT=(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]=rt(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=rt(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},pT=(t,e,n,r)=>{const o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,l)=>rt(a,e,{...r,path:[...r.path,s?"oneOf":"anyOf",l]}));s?n.oneOf=i:n.anyOf=i},mT=(t,e,n,r)=>{const o=t._zod.def,s=rt(o.left,e,{...r,path:[...r.path,"allOf",0]}),i=rt(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},gT=(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)=>rt(h,e,{...r,path:[...r.path,i,p]})),c=s.rest?rt(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)},yT=(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=rt(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=rt(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=rt(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)}},wT=(t,e,n,r)=>{const o=t._zod.def,s=rt(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"}]},vT=(t,e,n,r)=>{const o=t._zod.def;rt(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},kT=(t,e,n,r)=>{const o=t._zod.def;rt(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},bT=(t,e,n,r)=>{const o=t._zod.def;rt(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)))},ST=(t,e,n,r)=>{const o=t._zod.def;rt(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},ET=(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;rt(s,e,r);const i=e.seen.get(t);i.ref=s},CT=(t,e,n,r)=>{const o=t._zod.def;rt(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType,n.readOnly=!0},qm=(t,e,n,r)=>{const o=t._zod.def;rt(o.innerType,e,r);const s=e.seen.get(t);s.ref=o.innerType},_T=N("ZodISODateTime",(t,e)=>{C_.init(t,e),et.init(t,e)});function xT(t){return Ix(_T,t)}const TT=N("ZodISODate",(t,e)=>{__.init(t,e),et.init(t,e)});function MT(t){return Nx(TT,t)}const AT=N("ZodISOTime",(t,e)=>{x_.init(t,e),et.init(t,e)});function IT(t){return Bx(AT,t)}const NT=N("ZodISODuration",(t,e)=>{T_.init(t,e),et.init(t,e)});function BT(t){return Px(NT,t)}const Tn=N("ZodError",(t,e)=>{pm.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>yC(t,n)},flatten:{value:n=>gC(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,td,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,td,2)}},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),PT=kl(Tn),OT=bl(Tn),DT=Sl(Tn),RT=El(Tn),zT=kC(Tn),$T=bC(Tn),LT=SC(Tn),VT=EC(Tn),FT=CC(Tn),jT=_C(Tn),UT=xC(Tn),WT=TC(Tn),Xe=N("ZodType",(t,e)=>(He.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Al(t,"input"),output:Al(t,"output")}}),t.toJSONSchema=tT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone(po(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)=>mo(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>PT(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>DT(t,n,r),t.parseAsync=async(n,r)=>OT(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>RT(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>zT(t,n,r),t.decode=(n,r)=>$T(t,n,r),t.encodeAsync=async(n,r)=>LT(t,n,r),t.decodeAsync=async(n,r)=>VT(t,n,r),t.safeEncode=(n,r)=>FT(t,n,r),t.safeDecode=(n,r)=>jT(t,n,r),t.safeEncodeAsync=async(n,r)=>UT(t,n,r),t.safeDecodeAsync=async(n,r)=>WT(t,n,r),t.refine=(n,r)=>t.check(VM(n,r)),t.superRefine=n=>t.check(FM(n)),t.overwrite=n=>t.check(ni(n)),t.optional=()=>tg(t),t.exactOptional=()=>xM(t),t.nullable=()=>ng(t),t.nullish=()=>tg(ng(t)),t.nonoptional=n=>BM(t,n),t.array=()=>Mn(t),t.or=n=>yM([t,n]),t.and=n=>vM(t,n),t.transform=n=>og(t,CM(n)),t.default=n=>AM(t,n),t.prefault=n=>NM(t,n),t.catch=n=>OM(t,n),t.pipe=n=>og(t,n),t.readonly=()=>zM(t),t.describe=n=>{const r=t.clone();return Yi.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){var n;return(n=Yi.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Yi.get(t);const r=t.clone();return Yi.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=n=>n(t),t)),Jm=N("_ZodString",(t,e)=>{id.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(r,o,s)=>rT(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(Lx(...r)),t.includes=(...r)=>t.check(jx(...r)),t.startsWith=(...r)=>t.check(Ux(...r)),t.endsWith=(...r)=>t.check(Wx(...r)),t.min=(...r)=>t.check(Ml(...r)),t.max=(...r)=>t.check(Wm(...r)),t.length=(...r)=>t.check(Hm(...r)),t.nonempty=(...r)=>t.check(Ml(1,...r)),t.lowercase=r=>t.check(Vx(r)),t.uppercase=r=>t.check(Fx(r)),t.trim=()=>t.check(Zx()),t.normalize=(...r)=>t.check(Hx(...r)),t.toLowerCase=()=>t.check(Kx()),t.toUpperCase=()=>t.check(Yx()),t.slugify=()=>t.check(qx())}),HT=N("ZodString",(t,e)=>{id.init(t,e),Jm.init(t,e),t.email=n=>t.check(cx(ZT,n)),t.url=n=>t.check(px(KT,n)),t.jwt=n=>t.check(Ax(lM,n)),t.emoji=n=>t.check(mx(YT,n)),t.guid=n=>t.check(Vm(Gm,n)),t.uuid=n=>t.check(ux(Il,n)),t.uuidv4=n=>t.check(dx(Il,n)),t.uuidv6=n=>t.check(fx(Il,n)),t.uuidv7=n=>t.check(hx(Il,n)),t.nanoid=n=>t.check(gx(qT,n)),t.guid=n=>t.check(Vm(Gm,n)),t.cuid=n=>t.check(yx(JT,n)),t.cuid2=n=>t.check(wx(GT,n)),t.ulid=n=>t.check(vx(XT,n)),t.base64=n=>t.check(xx(sM,n)),t.base64url=n=>t.check(Tx(iM,n)),t.xid=n=>t.check(kx(QT,n)),t.ksuid=n=>t.check(bx(eM,n)),t.ipv4=n=>t.check(Sx(tM,n)),t.ipv6=n=>t.check(Ex(nM,n)),t.cidrv4=n=>t.check(Cx(rM,n)),t.cidrv6=n=>t.check(_x(oM,n)),t.e164=n=>t.check(Mx(aM,n)),t.datetime=n=>t.check(xT(n)),t.date=n=>t.check(MT(n)),t.time=n=>t.check(IT(n)),t.duration=n=>t.check(BT(n))});function bt(t){return lx(HT,t)}const et=N("ZodStringFormat",(t,e)=>{Ge.init(t,e),Jm.init(t,e)}),ZT=N("ZodEmail",(t,e)=>{m_.init(t,e),et.init(t,e)}),Gm=N("ZodGUID",(t,e)=>{h_.init(t,e),et.init(t,e)}),Il=N("ZodUUID",(t,e)=>{p_.init(t,e),et.init(t,e)}),KT=N("ZodURL",(t,e)=>{g_.init(t,e),et.init(t,e)}),YT=N("ZodEmoji",(t,e)=>{y_.init(t,e),et.init(t,e)}),qT=N("ZodNanoID",(t,e)=>{w_.init(t,e),et.init(t,e)}),JT=N("ZodCUID",(t,e)=>{v_.init(t,e),et.init(t,e)}),GT=N("ZodCUID2",(t,e)=>{k_.init(t,e),et.init(t,e)}),XT=N("ZodULID",(t,e)=>{b_.init(t,e),et.init(t,e)}),QT=N("ZodXID",(t,e)=>{S_.init(t,e),et.init(t,e)}),eM=N("ZodKSUID",(t,e)=>{E_.init(t,e),et.init(t,e)}),tM=N("ZodIPv4",(t,e)=>{M_.init(t,e),et.init(t,e)}),nM=N("ZodIPv6",(t,e)=>{A_.init(t,e),et.init(t,e)}),rM=N("ZodCIDRv4",(t,e)=>{I_.init(t,e),et.init(t,e)}),oM=N("ZodCIDRv6",(t,e)=>{N_.init(t,e),et.init(t,e)}),sM=N("ZodBase64",(t,e)=>{B_.init(t,e),et.init(t,e)}),iM=N("ZodBase64URL",(t,e)=>{O_.init(t,e),et.init(t,e)}),aM=N("ZodE164",(t,e)=>{D_.init(t,e),et.init(t,e)}),lM=N("ZodJWT",(t,e)=>{z_.init(t,e),et.init(t,e)}),Xm=N("ZodNumber",(t,e)=>{xm.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(r,o,s)=>oT(t,r,o),t.gt=(r,o)=>t.check(jm(r,o)),t.gte=(r,o)=>t.check(cd(r,o)),t.min=(r,o)=>t.check(cd(r,o)),t.lt=(r,o)=>t.check(Fm(r,o)),t.lte=(r,o)=>t.check(ld(r,o)),t.max=(r,o)=>t.check(ld(r,o)),t.int=r=>t.check(Qm(r)),t.safe=r=>t.check(Qm(r)),t.positive=r=>t.check(jm(0,r)),t.nonnegative=r=>t.check(cd(0,r)),t.negative=r=>t.check(Fm(0,r)),t.nonpositive=r=>t.check(ld(0,r)),t.multipleOf=(r,o)=>t.check(Um(r,o)),t.step=(r,o)=>t.check(Um(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 Gt(t){return Ox(Xm,t)}const cM=N("ZodNumberFormat",(t,e)=>{$_.init(t,e),Xm.init(t,e)});function Qm(t){return Dx(cM,t)}const uM=N("ZodBoolean",(t,e)=>{L_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>sT(t,n,r)});function cn(t){return Rx(uM,t)}const dM=N("ZodUnknown",(t,e)=>{V_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>aT()});function Nl(){return zx(dM)}const fM=N("ZodNever",(t,e)=>{F_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>iT(t,n,r)});function hM(t){return $x(fM,t)}const pM=N("ZodArray",(t,e)=>{j_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>fT(t,n,r,o),t.element=e.element,t.min=(n,r)=>t.check(Ml(n,r)),t.nonempty=n=>t.check(Ml(1,n)),t.max=(n,r)=>t.check(Wm(n,r)),t.length=(n,r)=>t.check(Hm(n,r)),t.unwrap=()=>t.element});function Mn(t,e){return Jx(pM,t,e)}const mM=N("ZodObject",(t,e)=>{W_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>hT(t,n,r,o),Oe(t,"shape",()=>e.shape),t.keyof=()=>dd(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Nl()}),t.loose=()=>t.clone({...t._zod.def,catchall:Nl()}),t.strict=()=>t.clone({...t._zod.def,catchall:hM()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>dC(t,n),t.safeExtend=n=>fC(t,n),t.merge=n=>hC(t,n),t.pick=n=>cC(t,n),t.omit=n=>uC(t,n),t.partial=(...n)=>pC(eg,t,n[0]),t.required=(...n)=>mC(rg,t,n[0])});function Hn(t,e){const n={type:"object",shape:t??{},...re(e)};return new mM(n)}const gM=N("ZodUnion",(t,e)=>{H_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>pT(t,n,r,o),t.options=e.options});function yM(t,e){return new gM({type:"union",options:t,...re(e)})}const wM=N("ZodIntersection",(t,e)=>{Z_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>mT(t,n,r,o)});function vM(t,e){return new wM({type:"intersection",left:t,right:e})}const kM=N("ZodTuple",(t,e)=>{Bm.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>gT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function Bl(t,e,n){const r=e instanceof He,o=r?n:e,s=r?e:null;return new kM({type:"tuple",items:t,rest:s,...re(o)})}const bM=N("ZodRecord",(t,e)=>{K_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>yT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function SM(t,e,n){return new bM({type:"record",keyType:t,valueType:e,...re(n)})}const ud=N("ZodEnum",(t,e)=>{Y_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(r,o,s)=>lT(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 ud({...e,checks:[],...re(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 ud({...e,checks:[],...re(o),entries:s})}});function dd(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ud({type:"enum",entries:n,...re(e)})}const EM=N("ZodTransform",(t,e)=>{q_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>dT(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new im(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Ki(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(Ki(i))}};const o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function CM(t){return new EM({type:"transform",transform:t})}const eg=N("ZodOptional",(t,e)=>{Om.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qm(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function tg(t){return new eg({type:"optional",innerType:t})}const _M=N("ZodExactOptional",(t,e)=>{J_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qm(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function xM(t){return new _M({type:"optional",innerType:t})}const TM=N("ZodNullable",(t,e)=>{G_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function ng(t){return new TM({type:"nullable",innerType:t})}const MM=N("ZodDefault",(t,e)=>{X_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>kT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function AM(t,e){return new MM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():fm(e)}})}const IM=N("ZodPrefault",(t,e)=>{Q_.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function NM(t,e){return new IM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():fm(e)}})}const rg=N("ZodNonOptional",(t,e)=>{ex.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>vT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function BM(t,e){return new rg({type:"nonoptional",innerType:t,...re(e)})}const PM=N("ZodCatch",(t,e)=>{tx.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ST(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function OM(t,e){return new PM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const DM=N("ZodPipe",(t,e)=>{nx.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ET(t,n,r,o),t.in=e.in,t.out=e.out});function og(t,e){return new DM({type:"pipe",in:t,out:e})}const RM=N("ZodReadonly",(t,e)=>{rx.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>CT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function zM(t){return new RM({type:"readonly",innerType:t})}const $M=N("ZodFunction",(t,e)=>{ox.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>uT(t,n)});function LM(t){return new $M({type:"function",input:Array.isArray(t==null?void 0:t.input)?Bl(t==null?void 0:t.input):(t==null?void 0:t.input)??Mn(Nl()),output:(t==null?void 0:t.output)??Nl()})}const sg=N("ZodCustom",(t,e)=>{sx.init(t,e),Xe.init(t,e),t._zod.processJSONSchema=(n,r,o)=>cT(t,n)});function An(t,e){return Gx(sg,()=>!0,e)}function VM(t,e={}){return Xx(sg,t,e)}function FM(t){return Qx(t)}function jM(t){const e=UM(t.chars),n=WM(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=HM(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 UM(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 WM(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 HM(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var fd=null;function ig(){return fd||(fd=jM({chars:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",firstPositive:"a",mostPositive:"z",mostNegative:"A"}))}function yo(t,e,n){const r=n.byChar[t],o=n.byChar[e];return Math.abs(r-o)}function hd(t,e){const n=t[0];if(n>e.mostPositive||n<e.mostNegative)throw new Error("invalid firstChar on key");return n===e.mostPositive?yo(n,e.firstPositive,e)+1+Pl(t.slice(1),"positive",e):n===e.mostNegative?yo(n,e.firstNegative,e)+1+Pl(t.slice(1),"negative",e):n>=e.firstPositive?yo(n,e.firstPositive,e)+2:yo(n,e.firstNegative,e)+2}function Pl(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"?yo(r,n.mostNegative,n)+1+Pl(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?yo(r,n.mostPositive,n)+1+Pl(t.slice(1),e,n):e==="positive"?yo(r,n.mostNegative,n)+2:yo(r,n.mostPositive,n)+2}function Ol(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 ZM(t,e,n){let[r,o]=Ol(t,e,"end",n.first),s=pd(r,o,n);s===1&&(r=r.padEnd(r.length+1,n.first),s=n.length);const i=cg(Math.floor(s/2),n);return md(r,i,n)}function pd(t,e,n){const[r,o]=Ol(t,e,"end",n.first).sort(),s=ag(o,r,n);return KM(s,n)}function md(t,e,n){const r=n.length,[o,s]=Ol(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 ag(t,e,n,r=!0){const o=n.length,[s,i]=Ol(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 lg(t,e){return md(t,e.byCode[1],e)}function gd(t,e){return ag(t,e.byCode[1],e,!1)}function cg(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 KM(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 YM(t){return t.firstPositive+t.byCode[0]}function qM(t,e){return hd(t,e)===t.length}function ug(t,e){Dl(t,e)}function Dl(t,e){const n=hg(t,e),r=hd(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function dg(t,e){if(!qM(t,e))throw new Error("invalid integer length: "+t)}function fg(t,e){dg(t,e);const[n,r]=pg(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=lg(r,e);return n+i}const s=GM(n,e);return mg(s,"lower",e)}function JM(t,e){dg(t,e);const[n,r]=pg(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=gd(r,e);return n+i}const s=XM(n,e);return mg(s,"upper",e)}function hg(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 pg(t,e){const n=hg(t,e),r=t.slice(n.length);return[n,r]}function GM(t,e){const n=t>=e.firstPositive,r=lg(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 XM(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 gd(o,e)}return!n&&r?t+e.mostPositive:gd(t,e)}function mg(t,e,n){const r=hd(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function gg(t,e){const n=cg(Math.floor(Math.random()*e.jitterRange),e);return md(t,n,e)}function QM(t,e,n){const r=t.padEnd(t.length+e,n.first);return gg(r,n)}function eA(t,e,n){const r=Dl(t,n),o=fg(r,n);let s=0;if(e!==null){const a=pd(t,e,n);a<n.jitterRange+1&&(s=Math.max(s,yg(a,n)))}const i=pd(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,yg(i,n))),s}function yg(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function tA(t,e,n=ig()){if(t!==null&&ug(t,n),e!==null&&ug(e,n),t===null&&e===null)return YM(n);if(t===null){const r=Dl(e,n);return JM(r,n)}if(e===null){const r=Dl(t,n);return fg(r,n)}if(t>=e)throw new Error(t+" >= "+e);return ZM(t,e,n)}function Rl(t,e,n=ig()){const r=tA(t,e,n),o=eA(r,e,n);return o?QM(r,o,n):gg(r,n)}function nA(){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 rA(){const t=nA();if(t.__xstate__)return t.__xstate__}const oA=t=>{if(typeof window>"u")return;const e=rA();e&&e.register(t)};class wg{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 vg=".",sA="",kg="",iA="#",aA="*",bg="xstate.init",lA="xstate.error",yd="xstate.stop";function cA(t,e){return{type:`xstate.after.${t}.${e}`}}function wd(t,e){return{type:`xstate.done.state.${t}`,output:e}}function uA(t,e){return{type:`xstate.done.actor.${t}`,output:e,actorId:t}}function Sg(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function Eg(t){return{type:bg,input:t}}function pr(t){setTimeout(()=>{throw t})}const dA=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Cg(t,e){const n=_g(t),r=_g(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?Cg(n[o],r[o]):!1)}function vd(t){if(Mg(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 _g(t){if(YA(t))return t.value;if(typeof t!="string")return t;const e=vd(t);return fA(e)}function fA(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 xg(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 Tg(t){return Mg(t)?t:[t]}function wo(t){return t===void 0?[]:Tg(t)}function kd(t,e,n,r){return typeof t=="function"?t({context:e,event:n,self:r}):t}function Mg(t){return Array.isArray(t)}function hA(t){return t.type.startsWith("xstate.error.actor")}function ri(t){return Tg(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function Ag(t){if(!(t===void 0||t===sA))return wo(t)}function bd(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 Ig(t,e){return`${e}.${t}`}function Sd(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 pA(t,e){if(e===t||e===aA)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 Ng(t,e){return`${t.sessionId}.${e}`}let mA=0;function gA(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()},v=Ng(h,y);f._snapshot._scheduledEvents[v]=w;const b=a.setTimeout(()=>{delete i[v],delete f._snapshot._scheduledEvents[v],f._relay(h,p,m)},g);i[v]=b},cancel:(h,p)=>{const m=Ng(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:${mA++}`,_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=bd(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:v}=h[p];c.schedule(m,g,y,w,v)}},_clock:a,_logger:l};return f}let Ed=!1;const Cd=1;let un=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const yA={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class wA{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 wg(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=un.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={...yA,...n},{clock:o,logger:s,parent:i,syncSnapshot:a,id:l,systemId:c,inspect:u}=r;this.system=i?i.system:gA(this,{clock:o,logger:s}),u&&!i&&this.system.inspect(bd(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){pr(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=Ed;try{Ed=!0,f.exec(f.info,f.params)}finally{Ed=p}};this._processingStatus===un.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){pr(a)}break;case"done":for(const i of this.observers)try{(s=i.next)==null||s.call(i,e)}catch(a){pr(a)}this._stopProcedure(),this._complete(),this._doneEvent=uA(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=bd(e,n,r);if(this._processingStatus!==un.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{(s=o.complete)==null||s.call(o)}catch(i){pr(i)}break;case"error":{const i=this._snapshot.error;if(!o.error)pr(i);else try{o.error(i)}catch(a){pr(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===un.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=un.Running;const e=Eg(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===yd&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===un.Stopped?this:(this.mailbox.clear(),this._processingStatus===un.NotStarted?(this._processingStatus=un.Stopped,this):(this.mailbox.enqueue({type:yd}),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){pr(r)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){this._parent||pr(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){pr(s)}}this.observers.clear(),this.eventListeners.clear(),n&&pr(e)}_error(e){this._stopProcedure(),this._reportError(e),this._parent&&this.system._relay(this,this._parent,Sg(this.id,e))}_stopProcedure(){return this._processingStatus!==un.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new wg(this._process.bind(this)),this._processingStatus=un.Stopped,this.system._unregister(this),this)}_send(e){this._processingStatus!==un.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:oA)(this)}toJSON(){return{xstate$$type:Cd,id:this.id}}getPersistedSnapshot(e){return this.logic.getPersistedSnapshot(this._snapshot,e)}[dA](){return this}getSnapshot(){return this._snapshot}}function qi(t,...[e]){return new wA(t,e)}function vA(t,e,n,r,{sendId:o}){const s=typeof o=="function"?o(n,r):o;return[e,{sendId:s},void 0]}function kA(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function _d(t){function e(n,r){}return e.type="xstate.cancel",e.sendId=t,e.resolve=vA,e.execute=kA,e}function bA(t,e,n,r,{id:o,systemId:s,src:i,input:a,syncSnapshot:l}){const c=typeof i=="string"?Sd(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=qi(c,{id:u,src:i,parent:t.self,syncSnapshot:l,systemId:s,input:h})),[is(e,{children:{...e.children,[u]:f}}),{id:o,systemId:s,actorRef:f,src:i,input:h},void 0]}function SA(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==un.Stopped&&e.start()})}function xd(...[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=bA,s.execute=SA,s}function EA(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]),[is(e,{children:a}),i,void 0]}function Bg(t,e){const n=e.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))Bg(t,r);t.system._unregister(e)}function CA(t,e){if(e){if(Bg(t,e),e._processingStatus!==un.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function zl(t){function e(n,r){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=EA,e.execute=CA,e}function _A(t,{context:e,event:n},{guards:r}){return!oi(r[0],e,n,t)}function rs(t){function e(n,r){return!1}return e.check=_A,e.guards=[t],e}function xA(t,{context:e,event:n},{guards:r}){return r.every(o=>oi(o,e,n,t))}function Ji(t){function e(n,r){return!1}return e.check=xA,e.guards=t,e}function oi(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 oi(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)}function Td(t){return t.type==="atomic"||t.type==="final"}function si(t){return Object.values(t.states).filter(e=>e.type!=="history")}function Gi(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 $l(t){const e=new Set(t),n=Og(e);for(const r of e)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))zg(r).forEach(o=>e.add(o));else if(r.type==="parallel"){for(const o of si(r))if(o.type!=="history"&&!e.has(o)){const s=zg(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 Pg(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const o=n[0];if(o){if(Td(o))return o.key}else return{}}const r={};for(const o of n)r[o.key]=Pg(o,e);return r}function Og(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 Dg(t,e){const n=$l(e);return Pg(t,Og(n))}function Md(t,e){return e.type==="compound"?si(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?si(e).every(n=>Md(t,n)):e.type==="final"}const Ll=t=>t[0]===iA;function TA(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(r=>pA(e,r)).sort((r,o)=>o.length-r.length).flatMap(r=>t.transitions.get(r))}function MA(t){const e=t.config.after;if(!e)return[];const n=o=>{const s=cA(o,t.id),i=s.type;return t.entry.push(Ul(s,{id:i,delay:o})),t.exit.push(_d(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 wo(i).map(c=>({...c,event:l,delay:a}))}).map(o=>{const{delay:s}=o;return{...vo(t,o.event,o),delay:s}})}function vo(t,e,n){const r=Ag(n.target),o=n.reenter??!1,s=BA(t,r),i={...n,actions:wo(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 AA(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===kg)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=t.config.on[n];e.set(n,ri(r).map(o=>vo(t,n,o)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,ri(t.config.onDone).map(r=>vo(t,n,r)))}for(const n of t.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;e.set(r,ri(n.onDone).map(o=>vo(t,r,o)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;e.set(r,ri(n.onError).map(o=>vo(t,r,o)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;e.set(r,ri(n.onSnapshot).map(o=>vo(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 IA(t){const e=[],n=r=>{Object.values(r).forEach(o=>{if(o.config.route&&o.config.id){const s=o.config.id,i=o.config.route.guard,a=(c,u)=>c.event.to!==`#${s}`?!1:i&&typeof i=="function"?i(c,u):!0,l={...o.config.route,guard:a,target:`#${s}`};e.push(vo(t,"xstate.route",l))}o.states&&n(o.states)})};n(t.states),e.length>0&&t.transitions.set("xstate.route",e)}function NA(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"?[]:wo(e.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${t.id}`,target:n?[`#${n.id}`]:[]})};return r}function BA(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if(Ll(n))return t.machine.getStateNodeById(n);const r=n[0]===vg;if(r&&!t.parent)return Vl(t,n.slice(1));const o=r?t.key+n:n;if(t.parent)try{return Vl(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 Rg(t){const e=Ag(t.config.target);return e?{target:e.map(n=>typeof n=="string"?Vl(t.parent,n):n)}:t.parent.initial}function ss(t){return t.type==="history"}function zg(t){const e=$g(t);for(const n of e)for(const r of Gi(n,t))e.add(r);return e}function $g(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 si(r))n(o)}}return n(t),e}function ii(t,e){if(Ll(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 Vl(t,e){if(typeof e=="string"&&Ll(e))try{return t.machine.getStateNodeById(e)}catch{}const n=vd(e).slice();let r=t;for(;n.length;){const o=n.shift();if(!o.length)break;r=ii(r,o)}return r}function Fl(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=>ii(t,o)).filter(Boolean);return[t.machine.root,t].concat(r,n.reduce((o,s)=>{const i=ii(t,s);if(!i)return o;const a=Fl(i,e[s]);return o.concat(a)},[]))}function PA(t,e,n,r){const s=ii(t,e).next(n,r);return!s||!s.length?t.next(n,r):s}function OA(t,e,n,r){const o=Object.keys(e),s=ii(t,o[0]),i=Ad(s,e[o[0]],n,r);return!i||!i.length?t.next(n,r):i}function DA(t,e,n,r){const o=[];for(const s of Object.keys(e)){const i=e[s];if(!i)continue;const a=ii(t,s),l=Ad(a,i,n,r);l&&o.push(...l)}return o.length?o:t.next(n,r)}function Ad(t,e,n,r){return typeof e=="string"?PA(t,e,n,r):Object.keys(e).length===1?OA(t,e,n,r):DA(t,e,n,r)}function RA(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function ko(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function zA(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 Lg(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(zA(Nd([o],e,n),Nd([a],e,n)))if(ko(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 $A(t){const[e,...n]=t;for(const r of Gi(e,void 0))if(n.every(o=>ko(o,r)))return r}function Id(t,e){if(!t.target)return[];const n=new Set;for(const r of t.target)if(ss(r))if(e[r.id])for(const o of e[r.id])n.add(o);else for(const o of Id(Rg(r),e))n.add(o);else n.add(r);return[...n]}function Vg(t,e){const n=Id(t,e);if(!n)return;if(!t.reenter&&n.every(o=>o===t.source||ko(o,t.source)))return t.source;const r=$A(n.concat(t.source));if(r)return r;if(!t.reenter)return t.source.machine.root}function Nd(t,e,n){var o;const r=new Set;for(const s of t)if((o=s.target)!=null&&o.length){const i=Vg(s,n);s.reenter&&s.source===i&&r.add(i);for(const a of e)ko(a,i)&&r.add(a)}return[...r]}function LA(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function VA(t,e,n,r,o){return Bd([{target:[...$g(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,n,r,!0,o)}function Bd(t,e,n,r,o,s){const i=[];if(!t.length)return[e,i];const a=n.actionExecutor;n.actionExecutor=l=>{i.push(l),a(l)};try{const l=new Set(e._nodes);let c=e.historyValue;const u=Lg(t,l,c);let f=e;o||([f,c]=WA(f,r,n,u,l,c,s,n.actionExecutor)),f=li(f,r,n,u.flatMap(p=>p.actions),s,void 0),f=jA(f,r,n,u,l,s,c,o);const h=[...l];f.status==="done"&&(f=li(f,r,n,h.sort((p,m)=>m.order-p.order).flatMap(p=>p.exit),s,void 0));try{return c===e.historyValue&&LA(e._nodes,l)?[f,i]:[is(f,{_nodes:h,historyValue:c}),i]}catch(p){throw p}}finally{n.actionExecutor=a}}function FA(t,e,n,r,o){if(r.output===void 0)return;const s=wd(o.id,o.output!==void 0&&o.parent?kd(o.output,t.context,e,n.self):void 0);return kd(r.output,t.context,s,n.self)}function jA(t,e,n,r,o,s,i,a){let l=t;const c=new Set,u=new Set;UA(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(xd(m.src,{...m,syncSnapshot:!!m.onSnapshot}));if(u.has(h)){const m=h.initial.actions;p.push(...m)}if(l=li(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(wd(m.id,h.output!==void 0?kd(h.output,l.context,e,n.self):void 0));(g==null?void 0:g.type)==="parallel"&&!f.has(g)&&Md(o,g);)f.add(g),s.push(wd(g.id)),y=g,g=g.parent;if(g)continue;l=is(l,{status:"done",output:FA(l,e,n,l.machine.root,y)})}}return l}function UA(t,e,n,r){for(const o of t){const s=Vg(o,e);for(const a of o.target||[])!ss(a)&&(o.source!==a||o.source!==s||o.reenter)&&(r.add(a),n.add(a)),ai(a,e,n,r);const i=Id(o,e);for(const a of i){const l=Gi(a,s);(s==null?void 0:s.type)==="parallel"&&l.push(s),Fg(r,e,n,l,!o.source.parent&&o.reenter?void 0:s)}}}function ai(t,e,n,r){var o;if(ss(t))if(e[t.id]){const s=e[t.id];for(const i of s)r.add(i),ai(i,e,n,r);for(const i of s)Pd(i,t.parent,r,e,n)}else{const s=Rg(t);for(const i of s.target)r.add(i),s===((o=t.parent)==null?void 0:o.initial)&&n.add(t.parent),ai(i,e,n,r);for(const i of s.target)Pd(i,t.parent,r,e,n)}else if(t.type==="compound"){const[s]=t.initial.target;ss(s)||(r.add(s),n.add(s)),ai(s,e,n,r),Pd(s,t,r,e,n)}else if(t.type==="parallel")for(const s of si(t).filter(i=>!ss(i)))[...r].some(i=>ko(i,s))||(ss(s)||(r.add(s),n.add(s)),ai(s,e,n,r))}function Fg(t,e,n,r,o){for(const s of r)if((!o||ko(s,o))&&t.add(s),s.type==="parallel")for(const i of si(s).filter(a=>!ss(a)))[...t].some(a=>ko(a,i))||(t.add(i),ai(i,e,n,t))}function Pd(t,e,n,r,o){Fg(n,r,o,Gi(t,e))}function WA(t,e,n,r,o,s,i,a){let l=t;const c=Nd(r,o,s);c.sort((f,h)=>h.order-f.order);let u;for(const f of c)for(const h of RA(f)){let p;h.history==="deep"?p=m=>Td(m)&&ko(m,f):p=m=>m.parent===f,u??(u={...s}),u[h.id]=Array.from(o).filter(p)}for(const f of c)l=li(l,e,n,[...f.exit,...f.invoke.map(h=>zl(h.id))],i,void 0),o.delete(f);return[l,u||s]}function HA(t,e){return t.implementations.actions[e]}function jg(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:HA(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=jg(a,e,n,y,o,s))}return a}function li(t,e,n,r,o,s){const i=s?[]:void 0,a=jg(t,e,n,r,{internalQueue:o,deferredActorIds:s},i);return i==null||i.forEach(([l,c])=>{l.retryResolve(n,a,c)}),a}function Od(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[0],_transitions:f}),s.push(c)}if(e.type===yd)return o=is(Ug(o,e,n),{status:"stopped"}),i([o,[]],e,[]),{snapshot:o,microsteps:s};let a=e;if(a.type!==bg){const c=a,u=hA(c),f=Wg(c,o);if(u&&!f.length)return o=is(t,{status:"error",error:c.error}),i([o,[]],c,[]),{snapshot:o,microsteps:s};const h=Bd(f,t,n,a,!1,r);o=h[0],i(h,c,f)}let l=!0;for(;o.status==="active";){let c=l?ZA(o,a):[];const u=c.length?o:void 0;if(!c.length){if(!r.length)break;a=r.shift(),c=Wg(a,o)}const f=Bd(c,o,n,a,!1,r);o=f[0],l=o!==u,i(f,a,c)}return o.status!=="active"&&Ug(o,a,n),{snapshot:o,microsteps:s}}function Ug(t,e,n){return li(t,e,n,Object.values(t.children).map(r=>zl(r)),[],void 0)}function Wg(t,e){return e.machine.getTransitionData(e,t)}function ZA(t,e){const n=new Set,r=t._nodes.filter(Td);for(const o of r)e:for(const s of[o].concat(Gi(o,void 0)))if(s.always){for(const i of s.always)if(i.guard===void 0||oi(i.guard,t.context,e,t)){n.add(i);break e}}return Lg(Array.from(n),new Set(t._nodes),t.historyValue)}function KA(t,e){const n=$l(Fl(t,e));return Dg(t,[...n])}function YA(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const qA=function(e){return Cg(e,this.value)},JA=function(e){return this.tags.has(e)},GA=function(e){const n=this.machine.getTransitionData(this,e);return!!(n!=null&&n.length)&&n.some(r=>r.target!==void 0||r.actions.length)},XA=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)}},QA=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function jl(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:Dg(e.root,t._nodes),tags:new Set(t._nodes.flatMap(n=>n.tags)),children:t.children,historyValue:t.historyValue||{},matches:qA,hasTag:JA,can:GA,getMeta:QA,toJSON:XA}}function is(t,e={}){return jl({...t,...e},t.machine)}function eI(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 tI(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:Hg(i),children:p,historyValue:eI(h.historyValue)}}function Hg(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:Cd,id:r.id};else{const o=Hg(r);o!==r&&(e??(e=Array.isArray(t)?t.slice():{...t}),e[n]=o)}}return e??t}function nI(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 rI(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 Ul(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=nI,n.execute=rI,n}function oI(t,{machine:e,context:n},r,o){const s=(i,a)=>{if(typeof i=="string"){const l=Sd(e,i);if(!l)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=qi(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 qi(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!==un.Stopped&&l.start()}),l}}function sI(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:oI(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[is(e,{context:l,children:Object.keys(s).length?{...e.children,...s}:e.children}),void 0,void 0]}function Ze(t){function e(n,r){}return e.type="xstate.assign",e.assignment=t,e.resolve=sI,e}const Zg=new WeakMap;function ci(t,e,n){let r=Zg.get(t);return r?e in r||(r[e]=n()):(r={[e]:n()},Zg.set(t,r)),r[e]}const iI={},Xi=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class Wl{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(vg),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?xg(this.config.states,(r,o)=>new Wl(r,{_parent:this,_key:o,_machine:this.machine})):iI,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=wo(this.config.entry).slice(),this.exit=wo(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=wo(e.tags).slice()}_initialize(){this.transitions=AA(this),this.config.always&&(this.always=ri(this.config.always).map(e=>vo(this,kg,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(Xi),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Xi),eventType:null})}:void 0,history:this.history,states:xg(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(Xi)})),entry:this.entry.map(Xi),exit:this.exit.map(Xi),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 ci(this,"invoke",()=>wo(this.config.invoke).map((e,n)=>{const{src:r,systemId:o}=e,s=e.id??Ig(this.id,n),i=typeof r=="string"?r:`xstate.invoke.${Ig(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 ci(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 ci(this,"delayedTransitions",()=>MA(this))}get initial(){return ci(this,"initial",()=>NA(this,this.config.initial))}next(e,n){const r=n.type,o=[];let s;const i=ci(this,`candidates-${r}`,()=>TA(this,r));for(const a of i){const{guard:l}=a,c=e.context;let u=!1;try{u=!l||oi(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 ci(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 aI="#";class Dd{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 Wl(e,{_key:this.id,_machine:this}),this.root._initialize(),IA(this.root),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 Dd(this.config,{actions:{...n,...e.actions},guards:{...r,...e.guards},actors:{...o,...e.actors},delays:{...s,...e.delays}})}resolveState(e){const n=KA(this.root,e.value),r=$l(Fl(this.root,n));return jl({_nodes:[...r],context:e.context||{},children:{},status:Md(r,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,r){return Od(e,n,r,[]).snapshot}microstep(e,n,r){return Od(e,n,r,[]).microsteps.map(([o])=>o)}getTransitionData(e,n){return Ad(this.root,e.value,e,n)||[]}_getPreInitialState(e,n,r){const{context:o}=this.config,s=jl({context:typeof o!="function"&&o?o:{},_nodes:[this.root],children:{},status:"active"},this);return typeof o=="function"?li(s,n,e,[Ze(({spawn:a,event:l,self:c})=>o({spawn:a,input:l.input,self:c}))],r,void 0):s}getInitialSnapshot(e,n){const r=Eg(n),o=[],s=this._getPreInitialState(e,r,o),[i]=VA(this.root,s,e,r,o),{snapshot:a}=Od(i,r,e,o);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=vd(e),r=n.slice(1),o=Ll(n[0])?n[0].slice(aI.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 Vl(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(e,n){return tI(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"?Sd(this,m):m;if(!g)return;const y=qi(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 Wl)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=jl({...e,children:r,_nodes:Array.from($l(Fl(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===Cd){f[p]=h[m.id];continue}u(m,h)}}}}return u(l.context,r),l}}function lI(t,e,n,r,{event:o}){const s=typeof o=="function"?o(n,r):o;return[e,{event:s},void 0]}function cI(t,{event:e}){t.defer(()=>t.emit(e))}function Kg(t){function e(n,r){}return e.type="xstate.emit",e.event=t,e.resolve=lI,e.execute=cI,e}let Rd=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function uI(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===Rd.Parent?p=t.self._parent:h===Rd.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 dI(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function fI(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===lA?Sg(t.self.id,r.data):r)})}function zd(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=uI,r.retryResolve=dI,r.execute=fI,r}function hI(t,e){return zd(Rd.Parent,t,e)}function pI(t,e,n,r,{collect:o}){const s=[],i=function(l){s.push(l)};return i.assign=(...a)=>{s.push(Ze(...a))},i.cancel=(...a)=>{s.push(_d(...a))},i.raise=(...a)=>{s.push(Ul(...a))},i.sendTo=(...a)=>{s.push(zd(...a))},i.sendParent=(...a)=>{s.push(hI(...a))},i.spawnChild=(...a)=>{s.push(xd(...a))},i.stopChild=(...a)=>{s.push(zl(...a))},i.emit=(...a)=>{s.push(Kg(...a))},o({context:n.context,event:n.event,enqueue:i,check:a=>oi(a,e.context,n.event,e),self:t.self,system:t.system},r),[e,void 0,s]}function mI(t){function e(n,r){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=pI,e}function gI(t,e,n,r,{value:o,label:s}){return[e,{value:typeof o=="function"?o(n,r):o,label:s},void 0]}function yI({logger:t},{value:e,label:n}){n?t(n,e):t(e)}function wI(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=gI,n.execute=yI,n}function vI(t,e){return new Dd(t,e)}function kI(t){const e=qi(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}function zr({schemas:t,actors:e,actions:n,guards:r,delays:o}){return{assign:Ze,sendTo:zd,raise:Ul,log:wI,cancel:_d,stopChild:zl,enqueueActions:mI,emit:Kg,spawnChild:xd,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>vI({...s,schemas:t},{actors:e,actions:n,guards:r,delays:o}),extend:s=>zr({schemas:t,actors:e,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...o,...s.delays}})}}function bI(t,e,n){const r=[],o=kI(t);return o.actionExecutor=i=>{r.push(i)},[t.transition(e,n,o),r]}var SI=Object.defineProperty,Yg=(t,e)=>{for(var n in e)SI(t,n,{get:e[n],enumerable:!0})},qg={};Yg(qg,{Aabb:()=>Ve,Asset:()=>as,Block:()=>T,Color:()=>In,Connector:()=>Ke,Edited:()=>$r,Held:()=>Rt,HitGeometry:()=>Me,Hovered:()=>bo,Image:()=>Qi,MAX_HIT_ARCS:()=>Zl,MAX_HIT_CAPSULES:()=>ui,Opacity:()=>lt,Pointer:()=>Et,PointerButton:()=>bn,PointerType:()=>Lr,ScaleWithZoom:()=>So,Shape:()=>Nn,StrokeKind:()=>Ct,Text:()=>gt,UploadState:()=>mr,User:()=>Fr,VerticalAlign:()=>cs,addPointerSample:()=>Yl});var EI=[[0,0],[0,0],[0,0],[0,0]],CI=[[0,0],[0,0],[0,0],[0,0]],_I=[[0,0],[0,0]],xI={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("")},TI=class extends qt{constructor(){super({name:"block",sync:"document"},xI)}getCenter(t,e,n){const{position:r,size:o}=this.read(t,e),s=n??[0,0];return pt.getCenter(r,o,s),s}setCenter(t,e,n){const r=this.write(t,e);pt.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 pt.getCorners(r,o,s,i),i}containsPoint(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return pt.containsPoint(r,o,s,n)}translate(t,e,n){const r=this.write(t,e);pt.translate(r.position,n)}setPosition(t,e,n){const r=this.write(t,e);$.copy(r.position,n)}setSize(t,e,n){const r=this.write(t,e);$.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=pt.rotateAround(o.position,o.size,o.rotateZ,n,r)}scaleBy(t,e,n){const r=this.write(t,e);pt.scaleBy(r.position,r.size,n)}scaleAround(t,e,n,r){const o=this.write(t,e);pt.scaleAround(o.position,o.size,n,r)}intersectsAabb(t,e,n){const{position:r,size:o,rotateZ:s}=this.read(t,e);return pt.intersectsAabb(r,o,s,n,CI,EI,_I)}worldToUv(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e),a=pt.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 pt.uvToWorld(r,o,s,a)}getUvToWorldMatrix(t,e,n){const{position:r,size:o,rotateZ:s,flip:i}=this.read(t,e);pt.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))}},T=new TI,Jg=0,Gg=1,Xg=2,Qg=3,MI={value:C.tuple(C.float32(),4).default([0,0,0,0])},AI=class extends qt{constructor(){super({name:"aabb"},MI)}containsPoint(t,e,n,r=!0){const{value:o}=this.read(t,e);return ne.containsPoint(o,n,r)}expandByPoint(t,e,n){const{value:r}=this.write(t,e);ne.expand(r,n)}expandByBlock(t,e,n){const r=T.getCorners(t,n),{value:o}=this.write(t,e);for(const s of r)ne.expand(o,s)}expandByAabb(t,e,n){const{value:r}=this.write(t,e);ne.union(r,n)}copyFrom(t,e,n){const{value:r}=this.read(t,n),{value:o}=this.write(t,e);ne.copy(o,r)}setByPoints(t,e,n){if(n.length===0)return;const{value:r}=this.write(t,e);ne.setFromPoints(r,n)}getCenter(t,e){const{value:n}=this.read(t,e);return ne.center(n)}getWidth(t,e){const{value:n}=this.read(t,e);return ne.width(n)}getHeight(t,e){const{value:n}=this.read(t,e);return ne.height(n)}distanceToPoint(t,e,n){const{value:r}=this.read(t,e);return ne.distanceToPoint(r,n)}intersectsEntity(t,e,n){const{value:r}=this.read(t,e),{value:o}=this.read(t,n);return ne.intersects(r,o)}surroundsEntity(t,e,n){const{value:r}=this.read(t,e),{value:o}=this.read(t,n);return ne.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[Jg],o[0][1]=r[Gg],o[1][0]=r[Xg],o[1][1]=r[Gg],o[2][0]=r[Xg],o[2][1]=r[Qg],o[3][0]=r[Jg],o[3][1]=r[Qg],o}applyPadding(t,e,n){const{value:r}=this.write(t,e);ne.pad(r,n)}},Ve=new AI,mr={Pending:"pending",Uploading:"uploading",Complete:"complete",Failed:"failed"},as=Qe({name:"asset",sync:"document",excludeFromHistory:["uploadState"]},{identifier:C.string().max(512).default(""),uploadState:C.enum(mr).default(mr.Pending)}),II={red:C.uint8().default(0),green:C.uint8().default(0),blue:C.uint8().default(0),alpha:C.uint8().default(255)},NI=class extends qt{constructor(){super({name:"color",sync:"document"},II)}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}},In=new NI,Ke=Qe({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])}),$r=Qe({name:"edited"},{}),Rt=Qe({name:"held",sync:"ephemeral"},{sessionId:C.string().max(36).default("")}),St=[1,0,0,1,0,0],ui=64,Hl=5,Zl=2,Kl=7,BI={hitCapsules:C.buffer(C.float32()).size(ui*Hl),capsuleCount:C.uint16().default(0),hitArcs:C.buffer(C.float32()).size(Zl*Kl),arcCount:C.uint16().default(0)},PI=class extends qt{constructor(){super({name:"hitHeometry"},BI)}getCapsuleAt(t,e,n){const r=this.read(t,e),o=n*Hl;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*Hl;for(let i=0;i<Hl;i++)o.hitCapsules[s+i]=r[i]}getArcAt(t,e,n){const r=this.read(t,e),o=n*Kl;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*Kl;for(let i=0;i<Kl;i++)o.hitArcs[s+i]=r[i]}containsPointWorld(t,e,n){const r=this.read(t,e);T.getUvToWorldMatrix(t,e,St);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(St,i);const a=[s[2],s[3]];ze.transformPoint(St,a);const l=[s[4],s[5]];ze.transformPoint(St,l);const c=s[6],u=Re.create(i[0],i[1],a[0],a[1],l[0],l[1],c);if(Re.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]];ze.transformPoint(St,i);const a=[s[2],s[3]];ze.transformPoint(St,a);const l=s[4],c=ht.create(i[0],i[1],a[0],a[1],l);if(ht.containsPoint(c,n))return!0}return!1}intersectsAabbWorld(t,e,n){const r=this.read(t,e);T.getUvToWorldMatrix(t,e,St);for(let o=0;o<r.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(St,i);const a=[s[2],s[3]];ze.transformPoint(St,a);const l=[s[4],s[5]];ze.transformPoint(St,l);const c=s[6],u=Re.create(i[0],i[1],a[0],a[1],l[0],l[1],c);if(Re.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]];ze.transformPoint(St,i);const a=[s[2],s[3]];ze.transformPoint(St,a);const l=s[4],c=ht.create(i[0],i[1],a[0],a[1],l);if(ht.intersectsAabb(c,n))return!0}return!1}getExtremaWorld(t,e){const n=this.read(t,e),r=[];T.getUvToWorldMatrix(t,e,St);for(let o=0;o<n.capsuleCount;o++){const s=this.getCapsuleAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(St,i);const a=[s[2],s[3]];ze.transformPoint(St,a);const l=s[4],c=ht.create(i[0],i[1],a[0],a[1],l);r.push(...ht.getExtrema(c))}for(let o=0;o<n.arcCount;o++){const s=this.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(St,i);const a=[s[2],s[3]];ze.transformPoint(St,a);const l=[s[4],s[5]];ze.transformPoint(St,l);const c=s[6],u=Re.create(i[0],i[1],a[0],a[1],l[0],l[1],c);r.push(...Re.getExtrema(u))}return r}addCapsule(t,e,n){const r=this.write(t,e),o=r.capsuleCount;if(o>=ui){console.warn(`HitGeometry: Max capsules (${ui}) 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=T.worldToUv(t,e,n),i=T.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>=Zl){console.warn(`HitGeometry: Max arcs (${Zl}) 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=T.worldToUv(t,e,n),a=T.worldToUv(t,e,r),l=T.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}},Me=new PI,bo=Qe({name:"hovered"},{}),Qi=Qe({name:"image",sync:"document"},{width:C.uint16().default(0),height:C.uint16().default(0),alt:C.string().max(256).default("")}),lt=Qe({name:"opacity"},{value:C.uint8().default(255)}),bn={None:"none",Left:"left",Middle:"middle",Right:"right",Back:"back",Forward:"forward"},Lr={Mouse:"mouse",Pen:"pen",Touch:"touch"},Vr=6,OI={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(bn).default(bn.None),pointerType:C.enum(Lr).default(Lr.Mouse),pressure:C.float32().default(0),obscured:C.boolean().default(!1),_prevPositions:C.array(C.float32(),Vr*2),_prevTimes:C.array(C.float32(),Vr),_sampleCount:C.int32().default(0),_velocity:C.tuple(C.float32(),2).default([0,0])},DI=class extends qt{constructor(){super({name:"pointer"},OI)}getVelocity(t,e){const n=this.read(t,e);return[n._velocity[0],n._velocity[1]]}getButton(t){switch(t){case 0:return bn.Left;case 1:return bn.Middle;case 2:return bn.Right;case 3:return bn.Back;case 4:return bn.Forward;default:return bn.None}}getType(t){switch(t){case"pen":return Lr.Pen;case"touch":return Lr.Touch;default:return Lr.Mouse}}},Et=new DI;function Yl(t,e,n){const r=t._sampleCount%Vr,o=t._prevTimes[r]||0;if(Math.abs(o-n)<.001)return;t.position=e,t._sampleCount++;const s=t._sampleCount%Vr;t._prevPositions[s*2]=e[0],t._prevPositions[s*2+1]=e[1],t._prevTimes[s]=n;const i=Math.min(t._sampleCount,Vr);if(i<=1){t._velocity=[0,0];return}const a=S=>(S%Vr+Vr)%Vr,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 k=a(t._sampleCount-i+1+S),_=(t._prevTimes[k]||0)-n,M=-_;if(M>5*l)continue;const I=Math.exp(-M/l),P=t._prevPositions[k*2]||0,V=t._prevPositions[k*2+1]||0;u+=I,f+=I*_,h+=I*_*_,p+=I*P,m+=I*V,g+=I*_*P,y+=I*_*V}const w=u*h-f*f;if(Math.abs(w)<=c){const S=t._sampleCount%Vr,k=a(t._sampleCount-1),E=(t._prevTimes[S]||0)-(t._prevTimes[k]||0);if(E>c){const _=(t._prevPositions[S*2]||0)-(t._prevPositions[k*2]||0),M=(t._prevPositions[S*2+1]||0)-(t._prevPositions[k*2+1]||0);t._velocity=[_/E,M/E]}else t._velocity=[0,0];return}const v=(u*g-f*p)/w,b=(u*y-f*m)/w;t._velocity=[v,b]}var So=Qe({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])}),Ct={Solid:"solid",Dashed:"dashed",None:"none"},Nn=Qe({name:"shape",sync:"document"},{kind:C.string().default("rectangle"),strokeKind:C.enum(Ct).default(Ct.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 RI(){const t=["#f43f5e","#ec4899","#a855f7","#6366f1","#3b82f6","#0ea5e9","#14b8a6","#22c55e","#eab308","#f97316"];return t[Math.floor(Math.random()*t.length)]}var ey=Hn({userId:bt().max(36).default(()=>crypto.randomUUID()),sessionId:bt().max(36).default(()=>crypto.randomUUID()),color:bt().max(7).default(RI),name:bt().max(100).default("Anonymous"),avatar:bt().max(500).default("")});function ls(t,e){return t.resources.pluginResources[e]}var zI=Hn({enabled:cn().default(!0),strict:cn().default(!1),colWidth:Gt().nonnegative().default(20),rowHeight:Gt().nonnegative().default(20),snapAngleRad:Gt().nonnegative().default(Math.PI/36),shiftSnapAngleRad:Gt().nonnegative().default(Math.PI/12)}),$I=Hn({leftMouseTool:bt().max(32).default("select"),middleMouseTool:bt().max(32).default("hand"),rightMouseTool:bt().max(32).default("menu"),wheelTool:bt().max(32).default("scroll"),modWheelTool:bt().max(32).default("zoom")}),LI=Hn({plugins:Mn(An()).default([]),maxEntities:Gt().default(5e3),user:An().default({}),grid:An().default({}),blockDefs:Mn(An()).default([]),keybinds:Mn(An()).default([]),cursors:SM(bt(),An()).default({}),components:Mn(An()).default([]),singletons:Mn(An()).default([]),systems:Mn(An()).default([]),fonts:Mn(An()).default([]),omitPluginKeybinds:cn().default(!1),omitPluginCursors:cn().default(!1),omitPluginFonts:cn().default(!1),controls:An().optional()});Hn({command:bt(),key:Gt(),mod:cn().optional(),shift:cn().optional()}),Hn({makeSvg:LM({input:Bl([Gt()]),output:bt()}),hotspot:Bl([Gt(),Gt()]),rotationOffset:Gt()});var mt={Top:"top",Center:"center",Bottom:"bottom"},Bn={Left:"left",Center:"center",Right:"right",Justify:"justify"},ty=Hn({canEdit:cn().default(!1),removeWhenTextEmpty:cn().default(!1)}),ny=Hn({enabled:cn().default(!0),terminals:Mn(Bl([Gt(),Gt()])).default([[.5,0],[.5,1],[.5,.5],[0,.5],[1,.5]])}),VI=dd(["background","content","overlay"]),$d=Hn({tag:bt(),stratum:VI.default("content"),editOptions:ty.default(ty.parse({})),components:Mn(An()).default([]),resizeMode:dd(["scale","text","free","groupOnly"]).default("scale"),canRotate:cn().default(!0),canScale:cn().default(!0),connectors:ny.default(ny.parse({}))}),gt=Qe({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(Bn).default(Bn.Left)}),Fr=Qe({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])}),cs=Qe({name:"verticalAlign",sync:"document"},{value:C.enum(mt).default(mt.Top)}),FI="core",Ld={background:0,content:1,overlay:2},ry={};Yg(ry,{Camera:()=>we,Controls:()=>ct,Cursor:()=>Pn,Frame:()=>di,Grid:()=>Wt,Intersect:()=>us,Key:()=>dn,Keyboard:()=>Sn,Mouse:()=>On,RankBounds:()=>Zn,ScaleWithZoomState:()=>jd,Screen:()=>_t,clearBits:()=>ds,codeToIndex:()=>O,setBit:()=>ea});var jI={width:C.float64().default(0),height:C.float64().default(0),left:C.float64().default(0),top:C.float64().default(0)},UI=class extends vt{constructor(){super({name:"screen"},jI)}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]}},_t=new UI,WI={top:C.float64().default(0),left:C.float64().default(0),zoom:C.float64().default(1),canSeeBlocks:C.boolean().default(!0),lastSeenBlock:C.ref()},HI=class extends vt{constructor(){super({name:"camera",sync:"local"},WI)}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=_t.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=_t.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=_t.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}},we=new HI,ZI={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("")},KI=class extends vt{constructor(){super({name:"controls"},ZI)}getButtons(t,...e){const n=this.read(t),r=[];return e.includes(n.leftMouseTool)&&r.push(bn.Left),e.includes(n.middleMouseTool)&&r.push(bn.Middle),e.includes(n.rightMouseTool)&&r.push(bn.Right),r}wheelActive(t,e,n){const r=this.read(t);return r.wheelTool===e&&!n||r.modWheelTool===e&&n}},ct=new KI,YI={cursorKind:C.string().max(64).default("select"),rotation:C.float64().default(0),contextCursorKind:C.string().max(64).default(""),contextRotation:C.float64().default(0)},qI=class extends vt{constructor(){super({name:"cursor"},YI)}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}},Pn=new qI,di=Zi({name:"frame"},{number:C.uint32().default(0),delta:C.float64().default(0),time:C.float64().default(0),lastTime:C.float64().default(0)}),JI={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)},GI=class extends vt{constructor(){super({name:"grid"},JI)}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}},Wt=new GI,XI={entity1:C.ref(),entity2:C.ref(),entity3:C.ref(),entity4:C.ref(),entity5:C.ref()},QI=class extends vt{constructor(){super({name:"intersect"},XI)}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}},us=new QI,Vd=32,e2={keysDown:C.buffer(C.uint8()).size(Vd),keysDownTrigger:C.buffer(C.uint8()).size(Vd),keysUpTrigger:C.buffer(C.uint8()).size(Vd),shiftDown:C.boolean().default(!1),altDown:C.boolean().default(!1),modDown:C.boolean().default(!1)};function Fd(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 t2=class extends vt{constructor(){super({name:"keyboard"},e2)}isKeyDown(t,e){return Fd(this.read(t).keysDown,e)}isKeyDownTrigger(t,e){return Fd(this.read(t).keysDownTrigger,e)}isKeyUpTrigger(t,e){return Fd(this.read(t).keysUpTrigger,e)}reset(t){const e=this.write(t);ds(e.keysDown),ds(e.keysDownTrigger),ds(e.keysUpTrigger),e.shiftDown=!1,e.altDown=!1,e.modDown=!1}},Sn=new t2;function ea(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 ds(t){for(let e=0;e<t.length;e++)t[e]=0}var O={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},dn={A:O.KeyA,B:O.KeyB,C:O.KeyC,D:O.KeyD,E:O.KeyE,F:O.KeyF,G:O.KeyG,H:O.KeyH,I:O.KeyI,J:O.KeyJ,K:O.KeyK,L:O.KeyL,M:O.KeyM,N:O.KeyN,O:O.KeyO,P:O.KeyP,Q:O.KeyQ,R:O.KeyR,S:O.KeyS,T:O.KeyT,U:O.KeyU,V:O.KeyV,W:O.KeyW,X:O.KeyX,Y:O.KeyY,Z:O.KeyZ,Digit0:O.Digit0,Digit1:O.Digit1,Digit2:O.Digit2,Digit3:O.Digit3,Digit4:O.Digit4,Digit5:O.Digit5,Digit6:O.Digit6,Digit7:O.Digit7,Digit8:O.Digit8,Digit9:O.Digit9,F1:O.F1,F2:O.F2,F3:O.F3,F4:O.F4,F5:O.F5,F6:O.F6,F7:O.F7,F8:O.F8,F9:O.F9,F10:O.F10,F11:O.F11,F12:O.F12,ShiftLeft:O.ShiftLeft,ShiftRight:O.ShiftRight,ControlLeft:O.ControlLeft,ControlRight:O.ControlRight,AltLeft:O.AltLeft,AltRight:O.AltRight,MetaLeft:O.MetaLeft,MetaRight:O.MetaRight,Escape:O.Escape,Space:O.Space,Enter:O.Enter,Tab:O.Tab,Backspace:O.Backspace,Delete:O.Delete,ArrowLeft:O.ArrowLeft,ArrowUp:O.ArrowUp,ArrowRight:O.ArrowRight,ArrowDown:O.ArrowDown,Home:O.Home,End:O.End,PageUp:O.PageUp,PageDown:O.PageDown,Insert:O.Insert,Semicolon:O.Semicolon,Equal:O.Equal,Comma:O.Comma,Minus:O.Minus,Period:O.Period,Slash:O.Slash,Backquote:O.Backquote,BracketLeft:O.BracketLeft,Backslash:O.Backslash,BracketRight:O.BracketRight,Quote:O.Quote,Numpad0:O.Numpad0,Numpad1:O.Numpad1,Numpad2:O.Numpad2,Numpad3:O.Numpad3,Numpad4:O.Numpad4,Numpad5:O.Numpad5,Numpad6:O.Numpad6,Numpad7:O.Numpad7,Numpad8:O.Numpad8,Numpad9:O.Numpad9,NumpadAdd:O.NumpadAdd,NumpadSubtract:O.NumpadSubtract,NumpadMultiply:O.NumpadMultiply,NumpadDivide:O.NumpadDivide,NumpadDecimal:O.NumpadDecimal,NumpadEnter:O.NumpadEnter},n2={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)},r2=class extends vt{constructor(){super({name:"mouse"},n2)}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]}},On=new r2,o2={minRank:C.string().max(36).default(""),maxRank:C.string().max(36).default("")},s2=class extends vt{constructor(){super({name:"rankBounds"},o2)}genNext(t){const e=this.write(t),n=Rl(e.maxRank||null,null);return e.maxRank=n,e.minRank||(e.minRank=n),n}genPrev(t){const e=this.write(t),n=Rl(null,e.minRank||null);return e.minRank=n,e.maxRank||(e.maxRank=n),n}genBetween(t,e){return Rl(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)}},Zn=new s2,jd=Zi({name:"scaleWithZoomState"},{lastZoom:C.float64().default(1)}),fi=Hp({name:C.string().max(128)}),oy=new WeakMap;function Ud(t){const{editor:e}=Je(t);let n=oy.get(e);return n||(n=new Map,oy.set(e,n)),n}var Wd=ie(t=>t.with(fi));function pe(t){return{name:t,spawn(e,n){const r=Bt(e);return ee(e,r,fi,{name:t}),Ud(e).set(r,n),r},*iter(e){const n=Ud(e);for(const r of Wd.current(e))if(fi.read(e,r).name===t){const s=n.get(r);yield{eid:r,payload:s}}},didSpawnLastFrame(e){for(const n of Wd.removed(e))if(fi.read(e,n).name===t)return!0;return!1}}}function i2(t){const e=Ud(t);for(const n of Wd.current(t))e.delete(n),st(t,n)}function fe(t,e,n){for(const{payload:r}of e.iter(t))n(t,r)}var Hd=pe("undo"),ql=pe("redo"),sy=pe("reset-keyboard"),a2=0;function Se(t,e){return{_system:new PE(e),phase:t.phase,priority:t.priority??a2}}var l2=Se({phase:"capture"},t=>{const e=Sn.read(t),{editor:n}=Je(t);for(const r of n.keybinds){let o=Sn.isKeyDownTrigger(t,r.key);if(o&&(o=!!r.mod===e.modDown),o&&(o=!!r.shift===e.shiftDown),o){const s=Bt(t);ee(t,s,fi,{name:r.command});break}}}),c2=Se({phase:"input",priority:100},t=>{const e=performance.now(),n=di._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)}),ta=new WeakMap;function u2(t){if(ta.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"})}};ta.set(t,e),t.addEventListener("keydown",e.onKeyDown),t.addEventListener("keyup",e.onKeyUp),t.addEventListener("blur",e.onBlur)}function d2(t){const e=ta.get(t);e&&(t.removeEventListener("keydown",e.onKeyDown),t.removeEventListener("keyup",e.onKeyUp),t.removeEventListener("blur",e.onBlur),ta.delete(t))}var f2=Se({phase:"input"},t=>{const e=Je(t),n=ta.get(e.domElement);if(!n)return;fe(t,sy,()=>{Sn.reset(t)});const r=n.eventsBuffer.length>0,o=Sn.read(t),s=!iy(o.keysDownTrigger)||!iy(o.keysUpTrigger);if(!r&&!s)return;const i=Sn.write(t);ds(i.keysDownTrigger),ds(i.keysUpTrigger);for(const a of n.eventsBuffer){if(a.type==="blur"){ds(i.keysDown),i.shiftDown=!1,i.altDown=!1,i.modDown=!1;continue}const l=O[a.code];l!==void 0&&(a.type==="keydown"?(h2(i.keysDown,l)||ea(i.keysDownTrigger,l,!0),ea(i.keysDown,l,!0)):a.type==="keyup"&&(ea(i.keysDown,l,!1),ea(i.keysUpTrigger,l,!0)),i.shiftDown=a.shiftKey,i.altDown=a.altKey,i.modDown=a.ctrlKey||a.metaKey)}n.eventsBuffer.length=0});function h2(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 iy(t){for(let e=0;e<t.length;e++)if(t[e]!==0)return!1;return!0}var na=new WeakMap;function p2(t){if(na.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"})}};na.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 m2(t){const e=na.get(t);e&&(window.removeEventListener("mousemove",e.onMouseMove),t.removeEventListener("wheel",e.onWheel),t.removeEventListener("mouseenter",e.onMouseEnter),t.removeEventListener("mouseleave",e.onMouseLeave),na.delete(t))}var g2=Se({phase:"input"},t=>{const e=Je(t),n=na.get(e.domElement);if(!n)return;const r=On.read(t),o=r.moveTrigger||r.wheelTrigger||r.enterTrigger||r.leaveTrigger,s=n.eventsBuffer.length>0;if(!o&&!s)return;const i=On.write(t),a=_t.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=y2(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 y2(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 ra=new WeakMap;function w2(t){if(ra.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})}};ra.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 v2(t){const e=ra.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),ra.delete(t))}var k2=Se({phase:"input"},t=>{const e=Je(t),{domElement:n}=e,r=ra.get(n);if(!r)return;r.frameCount++;const o=_t.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);ee(t,l,Et,{pointerId:i.pointerId,position:a,downPosition:a,downFrame:r.frameCount,button:Et.getButton(i.button),pointerType:Et.getType(i.pointerType),pressure:i.pressure,obscured:i.target!==n});const c=Et.write(t,l);Yl(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=Et.write(t,a);Yl(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=Et.write(t,a);Yl(c,l,s),st(t,a),r.pointerEntityMap.delete(i.pointerId);break}}r.eventsBuffer.length=0}),oa=new WeakMap;function b2(t){if(oa.has(t))return;const e={needsUpdate:!1,resizeObserver:new ResizeObserver(()=>{e.needsUpdate=!0}),onScroll:()=>{e.needsUpdate=!0}};oa.set(t,e),e.resizeObserver.observe(t),window.addEventListener("scroll",e.onScroll,!0)}function S2(t){const e=oa.get(t);e&&(e.resizeObserver.disconnect(),window.removeEventListener("scroll",e.onScroll,!0),oa.delete(t))}var E2=Se({phase:"input"},t=>{const e=Je(t),{domElement:n}=e,r=oa.get(n);if(!r||(di.read(t).number===1&&(r.needsUpdate=!0),!r.needsUpdate))return;const s=_t.write(t),i=n.getBoundingClientRect();s.left=i.left,s.top=i.top,s.width=i.width,s.height=i.height,r.needsUpdate=!1}),C2=ie(t=>t.tracking(Pn));function _2(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 x2=Se({phase:"render",priority:-100},t=>{const e=C2.changed(t),n=di.read(t);if(e.length===0&&n.number!==1)return;const{cursorKind:r,rotation:o}=Pn.getEffective(t);if(!r){document.body.style.cursor="default";return}const{editor:s}=Je(t),i=_2(s.cursors,r,o);document.body.style.cursor=i});function T2(t){const{editor:e}=Je(t);return e.blockDefs}function Xt(t,e){return T2(t)[e]??$d.parse({tag:e})}function ay(t,e){return Xt(t,e).editOptions.canEdit}function ly(t,e,n){if(R(t,e,Me)){const r=Me.getExtremaWorld(t,e);ne.setFromPoints(n,r)}else{const r=T.getCorners(t,e);ne.setFromPoints(n,r)}}function Zd(t,e){if(!R(t,e,Rt))return!1;const{sessionId:n}=Je(t),r=Rt.read(t,e);return r.sessionId!==""&&r.sessionId!==n}var cy=ie(t=>t.with(T,Ve));function uy(t,e,n){const r=[],o=cy.current(t);for(const s of o)if(Ve.containsPoint(t,s,e)){if(R(t,s,Me)){if(!Me.containsPointWorld(t,s,e))continue}else if(!T.containsPoint(t,s,e))continue;r.push(s)}return A2(t,r)}function M2(t,e,n){const r=[],o=n??cy.current(t);for(const s of o){const{value:i}=Ve.read(t,s);if(ne.intersects(e,i)){if(ne.contains(e,i)){r.push(s);continue}R(t,s,Me)?Me.intersectsAabbWorld(t,s,e)&&r.push(s):T.intersectsAabb(t,s,e)&&r.push(s)}}return r}function A2(t,e){return e.sort((n,r)=>{const o=T.read(t,n),s=T.read(t,r),i=Xt(t,o.tag).stratum,a=Xt(t,s.tag).stratum,l=Ld[i],c=Ld[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 hi=[1,0,0,1,0,0];function I2(t,e,n){const r=[],o=ht.bounds(e);for(const s of n){const i=Ve.read(t,s);ne.intersects(o,i.value)&&(R(t,s,Me)?N2(t,s,e)&&r.push(s):ht.intersectsAabb(e,i.value)&&r.push(s))}return r}function N2(t,e,n){const r=Me.read(t,e);T.getUvToWorldMatrix(t,e,hi);for(let o=0;o<r.arcCount;o++){const s=Me.getArcAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(hi,i);const a=[s[2],s[3]];ze.transformPoint(hi,a);const l=[s[4],s[5]];ze.transformPoint(hi,l);const c=s[6],u=Re.create(i[0],i[1],a[0],a[1],l[0],l[1],c),f=ht.pointA(n),h=ht.pointB(n);if(Re.intersectsCapsule(u,f,h,ht.radius(n)))return!0}for(let o=0;o<r.capsuleCount;o++){const s=Me.getCapsuleAt(t,e,o),i=[s[0],s[1]];ze.transformPoint(hi,i);const a=[s[2],s[3]];ze.transformPoint(hi,a);const l=s[4],c=ht.create(i[0],i[1],a[0],a[1],l);if(ht.intersectsCapsule(n,c))return!0}return!1}var B2=ie(t=>t.with(Fr));function P2(t){const e=Je(t).sessionId;for(const n of B2.current(t))if(Fr.read(t,n).sessionId===e)return n;return null}var dy=ie(t=>t.tracking(Et)),O2=Se({phase:"render",priority:-100},t=>{if(On.didMove(t)){const i=On.read(t);fy(t,i.position);return}if(dy.changed(t).length===0)return;const n=dy.current(t);let r=null,o=Number.MAX_SAFE_INTEGER;for(const i of n){const a=Et.read(t,i);a.pointerId<o&&(o=a.pointerId,r=i)}const s=Et.read(t,r);fy(t,s.position)});function fy(t,e){const n=P2(t);if(n===null)return;const r=Fr.write(t,n);r.position=we.toWorld(t,e)}var hy=ie(t=>t.tracking(T)),py=ie(t=>t.tracking(Me)),my=ie(t=>t.with(Rt).tracking(Rt)),D2=ie(t=>t.with(bo)),R2=ie(t=>t.with(Et));function gy(t){for(const e of D2.current(t))R(t,e,bo)&&mn(t,e,bo)}function z2(t,e){for(const n of e)return Zd(t,n)?void 0:n}function $2(t,e){const r=ct.read(t).leftMouseTool==="select";if(gy(t),!r)return;const o=z2(t,e);o!==void 0&&ee(t,o,bo,{})}function L2(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 sa=new Set,ia=new Set,V2=Se({phase:"capture",priority:100},t=>{sa.clear();for(const m of hy.added(t))sa.add(m);for(const m of py.added(t))sa.add(m);ia.clear();for(const m of hy.changed(t))ia.add(m);for(const m of py.changed(t))ia.add(m);for(const m of sa){R(t,m,Ve)||ee(t,m,Ve,{value:[0,0,0,0]});const g=Ve.write(t,m);ly(t,m,g.value)}for(const m of ia){const g=Ve.write(t,m);ly(t,m,g.value)}const e=On.didMove(t),n=On.didLeave(t),r=On.didScroll(t),o=sa.size>0||ia.size>0,s=my.added(t),i=my.removed(t),a=s.length>0||i.length>0;if(!e&&!n&&!r&&!o&&!a)return;if(n){us.clear(t),gy(t);return}const l=On.getPosition(t),c=we.toWorld(t,l),u=uy(t,c),f=us.getAll(t),h=!L2(u,f);h&&us.setAll(t,u),!(R2.current(t).length>0)&&(h||a)&&$2(t,u)}),F2=ie(t=>t.with(me,T)),j2=Se({phase:"input",priority:100},t=>{const e=F2.added(t);for(const n of e){const r=T.read(t,n);if(r.rank===""){const o=T.write(t,n);o.rank=Zn.genNext(t)}else Zn.add(t,r.rank)}}),U2=ie(t=>t.tracking(we)),W2=ie(t=>t.with(me,T,Ve)),H2=ie(t=>t.with(me,T,Ve)),Z2=[0,0,0,0],K2=Se({phase:"render",priority:90},t=>{if(U2.changed(t).length===0&&H2.addedOrRemoved(t).length===0)return;const e=we.read(t),n=we.getAabb(t,Z2);if(e.canSeeBlocks&&e.lastSeenBlock!==null&&R(t,e.lastSeenBlock,Ve)){const i=Ve.read(t,e.lastSeenBlock);if(ne.intersects(n,i.value))return}let r=null;for(const i of W2.current(t)){const a=Ve.read(t,i);if(ne.intersects(n,a.value)){r=i;break}}const o=r!==null;if(o===e.canSeeBlocks){r!==e.lastSeenBlock&&(we.write(t).lastSeenBlock=r);return}const s=we.write(t);s.canSeeBlocks=o,s.lastSeenBlock=r}),yy=ie(t=>t.with(T).tracking(So)),Jl=[0,0],Gl=[0,0],Y2=Se({phase:"render",priority:100},t=>{const e=we.read(t),n=jd.read(t);if(!Dt.approxEqual(e.zoom,n.lastZoom)){for(const o of yy.current(t))wy(t,o,e.zoom);jd.write(t).lastZoom=e.zoom}for(const o of yy.addedOrChanged(t))wy(t,o,e.zoom)});function wy(t,e,n){const r=T.write(t,e),o=So.read(t,e),s=1/n,i=1+(s-1)*o.scaleMultiplier[0],a=1+(s-1)*o.scaleMultiplier[1];Jl[0]=o.startSize[0]*i,Jl[1]=o.startSize[1]*a,$.copy(Gl,o.startSize),$.sub(Gl,Jl),$.multiply(Gl,o.anchor),$.copy(r.position,o.startPosition),$.add(r.position,Gl),$.copy(r.size,Jl)}var q2={name:FI,singletons:Object.values(ry).filter(t=>t instanceof vt),components:Object.values(qg).filter(t=>t instanceof qt),blockDefs:[{tag:"sticky-note",components:[In,gt,cs],editOptions:{canEdit:!0}},{tag:"text",components:[gt],resizeMode:"text",editOptions:{canEdit:!0,removeWhenTextEmpty:!0}},{tag:"image",components:[Qi,as],resizeMode:"scale"},{tag:"shape",components:[Nn,gt,cs],resizeMode:"free",editOptions:{canEdit:!0}}],systems:[c2,j2,f2,g2,E2,k2,V2,l2,Y2,K2,x2,O2],setup(t){const{domElement:e}=Je(t);u2(e),p2(e),b2(e),w2(e)},teardown(t){const{domElement:e}=Je(t);d2(e),m2(e),S2(e),v2(e)}},J2=Hn({name:bt(),displayName:bt(),url:bt(),previewImage:bt().optional(),selectable:cn().default(!0),weights:Mn(Gt()).default([400,700]),italics:cn().default(!0)}),G2=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 X2(t){return typeof t=="function"?t({}):t}function Q2(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 vy=["input","capture","update","render"];function eN(t){const e=new Map;for(const r of vy)e.set(r,[]);for(const r of t)e.get(r.phase).push(r);const n=[];for(const r of vy){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 tN=class{constructor(e,n){this.cursors={},this.blockDefs={},this.fonts=[],this.components=[],this.singletons=[];const r=LI.parse(n??{}),{plugins:o,maxEntities:s}=r,i=ey.parse(r.user??{});this.userData=i,this.gridOptions=zI.parse(r.grid??{}),this.controlsOptions=$I.parse(r.controls??{});const a=o.map(X2),l=Q2([q2,...a]),c=[fi,me];for(const k of l)k.components&&c.push(...k.components),k.singletons&&c.push(...k.singletons);c.push(...r.components),c.push(...r.singletons);const u=r.keybinds;if(!r.omitPluginKeybinds)for(const k of l)k.keybinds&&u.push(...k.keybinds);this.keybinds=u;const f={};for(const k of r.blockDefs){const E=$d.parse(k);f[E.tag]=E}for(const k of l)if(k.blockDefs)for(const E of k.blockDefs){const _=$d.parse(E);f[_.tag]=_}this.blockDefs=f;const h={};if(Object.assign(h,r.cursors),!r.omitPluginCursors)for(const k of l)k.cursors&&Object.assign(h,k.cursors);this.cursors=h,this.fontLoader=new G2;const p=[...r.fonts];if(!r.omitPluginFonts)for(const k of l)k.fonts&&p.push(...k.fonts);this.fonts=p.map(k=>J2.parse(k));const m={};for(const k of l)k.resources!==void 0&&(m[k.name]=k.resources);const g=new Map,y=new Map,w=new Map,v=new Map,b={domElement:e,editor:this,userId:i.userId,sessionId:i.sessionId,pluginResources:m,componentsByName:g,singletonsByName:y,componentsById:w,singletonsById:v};this.world=new jE(c,{maxEntities:s,resources:b});const S=[];for(const k of l)k.systems&&S.push(...k.systems);S.push(...r.systems),this.systemBatches=eN(S),this.plugins=new Map(l.map(k=>[k.name,k]));for(const k of l){if(k.components)for(const E of k.components){const _=E._getComponentId(this.ctx);w.set(_,E),g.set(E.name,E)}if(k.singletons)for(const E of k.singletons){const _=E._getComponentId(this.ctx);v.set(_,E),y.set(E.name,E)}}for(const k of r.components){const E=k._getComponentId(this.ctx);w.set(E,k),g.set(k.name,k)}for(const k of r.singletons){const E=k._getComponentId(this.ctx);v.set(E,k),y.set(k.name,k)}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),Wt.copy(this.ctx,this.gridOptions),ct.copy(this.ctx,this.controlsOptions),this.nextTick(e=>{const n=Bt(e);ee(e,n,me,{id:crypto.randomUUID()}),ee(e,n,Fr,{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,i2(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 nN(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]=bI(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 rN=class extends vt{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=nN(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 Eo(t,e){return new rN(t,e)}function oN(t){const e=di.read(t);return{type:"frame",ctx:t,delta:e.delta,frameNumber:e.number,time:e.time}}function sN(t,e){const n=[];for(const r of e)Sn.isKeyDownTrigger(t,r)&&n.push({type:"keyDown",key:r,ctx:t}),Sn.isKeyUpTrigger(t,r)&&n.push({type:"keyUp",key:r,ctx:t});return n}function ky(t){const e=[],n=On.read(t),r=[n.position[0],n.position[1]],o=we.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 iN=3,aN=30,Xl=ie(t=>t.tracking(Et)),by=new Map;function lN(t){const e=t.readerId;let n=by.get(e);return n||(n={prevPositions:new Map,prevModifiers:{shiftDown:!1,altDown:!1,modDown:!1},prevCamera:{left:0,top:0,zoom:1}},by.set(e,n)),n}function jr(t,e,n={}){if(e.length===0)return[];const{includeFrameEvent:r=!1,clickMoveThreshold:o=iN,clickFrameThreshold:s=aN}=n,i=lN(t),a=di.read(t).number,l=[],c=Sn.read(t),u={shiftDown:c.shiftDown,altDown:c.altDown,modDown:c.modDown},f=we.read(t),h=P=>{const V=Et.read(t,P);return e.includes(V.button)},p=(P,V)=>{const Z=Et.read(t,V),A=[Z.position[0],Z.position[1]],F=we.toWorld(t,A),Y=uy(t,F);return{type:P,ctx:t,screenPosition:A,worldPosition:F,velocity:[Z._velocity[0],Z._velocity[1]],pressure:Z.pressure,button:Z.button,pointerType:Z.pointerType,obscured:Z.obscured,shiftDown:u.shiftDown,altDown:u.altDown,modDown:u.modDown,cameraLeft:f.left,cameraTop:f.top,cameraZoom:f.zoom,pointerId:V,intersects:Y}},m=Xl.added(t),g=Xl.removed(t),y=Xl.changed(t),w=Xl.current(t),v=m.filter(h),b=g.filter(h),S=y.filter(h),k=Array.from(w).filter(h),E=Sn.isKeyDownTrigger(t,dn.Escape),_=k.length>1&&v.length>0;if((E||_)&&k.length>0)return l.push(p("cancel",k[0])),l;if(v.length>0&&k.length===1){const P=k[0],V=Et.read(t,P);V.obscured||(l.push(p("pointerDown",P)),i.prevPositions.set(P,[V.position[0],V.position[1]]))}if(b.length>0&&k.length===0){const P=b[0],V=Et.read(t,P);l.push(p("pointerUp",P));const Z=i.prevPositions.get(P);if(Z){const A=[V.position[0],V.position[1]],F=$.distance(Z,A),Y=a-V.downFrame;F<o&&Y<s&&l.push(p("click",P)),i.prevPositions.delete(P)}}const M=u.shiftDown!==i.prevModifiers.shiftDown||u.altDown!==i.prevModifiers.altDown||u.modDown!==i.prevModifiers.modDown,I=f.left!==i.prevCamera.left||f.top!==i.prevCamera.top||f.zoom!==i.prevCamera.zoom;return(S.length>0||M||I)&&k.length===1&&l.push(p("pointerMove",k[0])),r&&k.length===1&&l.push(p("frame",k[0])),i.prevModifiers={...u},i.prevCamera={left:f.left,top:f.top,zoom:f.zoom},l}var Ee;(function(t){t.assertEqual=o=>o;function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},t.getValidEnumValues=o=>{const s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(const a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(const i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ee||(Ee={}));var Kd;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Kd||(Kd={}));const q=Ee.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ur=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}},z=Ee.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),cN=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class En extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof En))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ee.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const o of this.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}}get formErrors(){return this.flatten()}}En.create=t=>new En(t);const pi=(t,e)=>{let n;switch(t.code){case z.invalid_type:t.received===q.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Ee.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ee.joinValues(t.keys,", ")}`;break;case z.invalid_union:n="Invalid input";break;case z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ee.joinValues(t.options)}`;break;case z.invalid_enum_value:n=`Invalid enum value. Expected ${Ee.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:n="Invalid function arguments";break;case z.invalid_return_type:n="Invalid function return type";break;case z.invalid_date:n="Invalid date";break;case z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Ee.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case z.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case z.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case z.custom:n="Invalid input";break;case z.invalid_intersection_types:n="Intersection results could not be merged";break;case z.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:n="Number must be finite";break;default:n=e.defaultError,Ee.assertNever(t)}return{message:n}};let Sy=pi;function uN(t){Sy=t}function Ql(){return Sy}const ec=t=>{const{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)a=c(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},dN=[];function H(t,e){const n=Ql(),r=ec({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===pi?void 0:pi].filter(o=>!!o)});t.common.issues.push(r)}class Ht{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const o of n){if(o.status==="aborted")return de;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const o of n){const s=await o.key,i=await o.value;r.push({key:s,value:i})}return Ht.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const o of n){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return de;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}}const de=Object.freeze({status:"aborted"}),mi=t=>({status:"dirty",value:t}),Qt=t=>({status:"valid",value:t}),Yd=t=>t.status==="aborted",qd=t=>t.status==="dirty",fs=t=>t.status==="valid",aa=t=>typeof Promise<"u"&&t instanceof Promise;function tc(t,e,n,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function Ey(t,e,n,r,o){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}typeof SuppressedError=="function"&&SuppressedError;var te;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(te||(te={}));var la,ca;class gr{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Cy=(t,e)=>{if(fs(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new En(t.common.issues);return this._error=n,this._error}}};function ge(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{var l,c;const{message:u}=t;return i.code==="invalid_enum_value"?{message:u??a.defaultError}:typeof a.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:(c=u??n)!==null&&c!==void 0?c:a.defaultError}},description:o}}class ve{get description(){return this._def.description}_getType(e){return Ur(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ur(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ht,ctx:{common:e.parent.common,data:e.data,parsedType:Ur(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(aa(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ur(e)},s=this._parseSync({data:e,path:o.path,parent:o});return Cy(o,s)}"~validate"(e){var n,r;const o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ur(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:o});return fs(s)?{value:s.value}:{issues:o.common.issues}}catch(s){!((r=(n=s==null?void 0:s.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:o}).then(s=>fs(s)?{value:s.value}:{issues:o.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ur(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(aa(o)?o:Promise.resolve(o));return Cy(r,s)}refine(e,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const i=e(o),a=()=>s.addIssue({code:z.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new qn({schema:this,typeName:ue.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return wr.create(this,this._def)}nullable(){return To.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yn.create(this)}promise(){return vi.create(this,this._def)}or(e){return ha.create([this,e],this._def)}and(e){return pa.create(this,e,this._def)}transform(e){return new qn({...ge(this._def),schema:this,typeName:ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new va({...ge(this._def),innerType:this,defaultValue:n,typeName:ue.ZodDefault})}brand(){return new Xd({typeName:ue.ZodBranded,type:this,...ge(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new ka({...ge(this._def),innerType:this,catchValue:n,typeName:ue.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ba.create(this,e)}readonly(){return Sa.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const fN=/^c[^\s-]{8,}$/i,hN=/^[0-9a-z]+$/,pN=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mN=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gN=/^[a-z0-9_-]{21}$/i,yN=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wN=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,vN=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Jd;const bN=/^(?:(?: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])$/,SN=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,EN=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,CN=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_N=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xN=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_y="((\\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])))",TN=new RegExp(`^${_y}$`);function xy(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function MN(t){return new RegExp(`^${xy(t)}$`)}function Ty(t){let e=`${_y}T${xy(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function AN(t,e){return!!((e==="v4"||!e)&&bN.test(t)||(e==="v6"||!e)&&EN.test(t))}function IN(t,e){if(!yN.test(t))return!1;try{const[n]=t.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||e&&o.alg!==e)}catch{return!1}}function NN(t,e){return!!((e==="v4"||!e)&&SN.test(t)||(e==="v6"||!e)&&CN.test(t))}class Kn extends ve{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_type,expected:q.string,received:s.parsedType}),de}const r=new Ht;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),H(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),H(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?H(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&H(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")vN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"email",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Jd||(Jd=new RegExp(kN,"u")),Jd.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"emoji",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")mN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"uuid",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")gN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"nanoid",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")fN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"cuid",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")hN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"cuid2",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")pN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"ulid",code:z.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),H(o,{validation:"url",code:z.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"regex",code:z.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Ty(s).test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?TN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?MN(s).test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{code:z.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?wN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"duration",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?AN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"ip",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?IN(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"jwt",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?NN(e.data,s.version)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"cidr",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?_N.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"base64",code:z.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?xN.test(e.data)||(o=this._getOrReturnCtx(e,o),H(o,{validation:"base64url",code:z.invalid_string,message:s.message}),r.dirty()):Ee.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:z.invalid_string,...te.errToObj(r)})}_addCheck(e){return new Kn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...te.errToObj(e)})}url(e){return this._addCheck({kind:"url",...te.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...te.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...te.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...te.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...te.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...te.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...te.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...te.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...te.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...te.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...te.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...te.errToObj(e)})}datetime(e){var n,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(n=e==null?void 0:e.offset)!==null&&n!==void 0?n:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...te.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...te.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...te.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...te.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...te.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...te.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...te.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...te.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...te.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...te.errToObj(n)})}nonempty(e){return this.min(1,te.errToObj(e))}trim(){return new Kn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Kn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Kn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Kn.create=t=>{var e;return new Kn({checks:[],typeName:ue.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...ge(t)})};function BN(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=parseInt(t.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}class Co extends ve{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==q.number){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_type,expected:q.number,received:s.parsedType}),de}let r;const o=new Ht;for(const s of this._def.checks)s.kind==="int"?Ee.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:z.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),H(r,{code:z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),H(r,{code:z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?BN(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),H(r,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:z.not_finite,message:s.message}),o.dirty()):Ee.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,te.toString(n))}gt(e,n){return this.setLimit("min",e,!1,te.toString(n))}lte(e,n){return this.setLimit("max",e,!0,te.toString(n))}lt(e,n){return this.setLimit("max",e,!1,te.toString(n))}setLimit(e,n,r,o){return new Co({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:te.toString(o)}]})}_addCheck(e){return new Co({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:te.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:te.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:te.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:te.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:te.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:te.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:te.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:te.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:te.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ee.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Co.create=t=>new Co({checks:[],typeName:ue.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class _o extends ve{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==q.bigint)return this._getInvalidInput(e);let r;const o=new Ht;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),H(r,{code:z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),H(r,{code:z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),H(r,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Ee.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return H(n,{code:z.invalid_type,expected:q.bigint,received:n.parsedType}),de}gte(e,n){return this.setLimit("min",e,!0,te.toString(n))}gt(e,n){return this.setLimit("min",e,!1,te.toString(n))}lte(e,n){return this.setLimit("max",e,!0,te.toString(n))}lt(e,n){return this.setLimit("max",e,!1,te.toString(n))}setLimit(e,n,r,o){return new _o({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:te.toString(o)}]})}_addCheck(e){return new _o({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:te.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:te.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:te.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:te.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:te.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}_o.create=t=>{var e;return new _o({checks:[],typeName:ue.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...ge(t)})};class ua extends ve{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:q.boolean,received:r.parsedType}),de}return Qt(e.data)}}ua.create=t=>new ua({typeName:ue.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ge(t)});class hs extends ve{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_type,expected:q.date,received:s.parsedType}),de}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return H(s,{code:z.invalid_date}),de}const r=new Ht;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),H(o,{code:z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),H(o,{code:z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):Ee.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new hs({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:te.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:te.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}hs.create=t=>new hs({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:ue.ZodDate,...ge(t)});class nc extends ve{_parse(e){if(this._getType(e)!==q.symbol){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:q.symbol,received:r.parsedType}),de}return Qt(e.data)}}nc.create=t=>new nc({typeName:ue.ZodSymbol,...ge(t)});class da extends ve{_parse(e){if(this._getType(e)!==q.undefined){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:q.undefined,received:r.parsedType}),de}return Qt(e.data)}}da.create=t=>new da({typeName:ue.ZodUndefined,...ge(t)});class fa extends ve{_parse(e){if(this._getType(e)!==q.null){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:q.null,received:r.parsedType}),de}return Qt(e.data)}}fa.create=t=>new fa({typeName:ue.ZodNull,...ge(t)});class gi extends ve{constructor(){super(...arguments),this._any=!0}_parse(e){return Qt(e.data)}}gi.create=t=>new gi({typeName:ue.ZodAny,...ge(t)});class ps extends ve{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Qt(e.data)}}ps.create=t=>new ps({typeName:ue.ZodUnknown,...ge(t)});class Wr extends ve{_parse(e){const n=this._getOrReturnCtx(e);return H(n,{code:z.invalid_type,expected:q.never,received:n.parsedType}),de}}Wr.create=t=>new Wr({typeName:ue.ZodNever,...ge(t)});class rc extends ve{_parse(e){if(this._getType(e)!==q.undefined){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:q.void,received:r.parsedType}),de}return Qt(e.data)}}rc.create=t=>new rc({typeName:ue.ZodVoid,...ge(t)});class Yn extends ve{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==q.array)return H(n,{code:z.invalid_type,expected:q.array,received:n.parsedType}),de;if(o.exactLength!==null){const i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(H(n,{code:i?z.too_big:z.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(H(n,{code:z.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(H(n,{code:z.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new gr(n,i,n.path,a)))).then(i=>Ht.mergeArray(r,i));const s=[...n.data].map((i,a)=>o.type._parseSync(new gr(n,i,n.path,a)));return Ht.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new Yn({...this._def,minLength:{value:e,message:te.toString(n)}})}max(e,n){return new Yn({...this._def,maxLength:{value:e,message:te.toString(n)}})}length(e,n){return new Yn({...this._def,exactLength:{value:e,message:te.toString(n)}})}nonempty(e){return this.min(1,e)}}Yn.create=(t,e)=>new Yn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ue.ZodArray,...ge(e)});function yi(t){if(t instanceof tt){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=wr.create(yi(r))}return new tt({...t._def,shape:()=>e})}else return t instanceof Yn?new Yn({...t._def,type:yi(t.element)}):t instanceof wr?wr.create(yi(t.unwrap())):t instanceof To?To.create(yi(t.unwrap())):t instanceof yr?yr.create(t.items.map(e=>yi(e))):t}class tt extends ve{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Ee.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==q.object){const c=this._getOrReturnCtx(e);return H(c,{code:z.invalid_type,expected:q.object,received:c.parsedType}),de}const{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Wr&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||a.push(c);const l=[];for(const c of i){const u=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new gr(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Wr){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(H(o,{code:z.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const f=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new gr(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,h=await u.value;c.push({key:f,value:h,alwaysSet:u.alwaysSet})}return c}).then(c=>Ht.mergeObjectSync(r,c)):Ht.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return te.errToObj,new tt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var o,s,i,a;const l=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,n,r).message)!==null&&i!==void 0?i:r.defaultError;return n.code==="unrecognized_keys"?{message:(a=te.errToObj(e).message)!==null&&a!==void 0?a:l}:{message:l}}}:{}})}strip(){return new tt({...this._def,unknownKeys:"strip"})}passthrough(){return new tt({...this._def,unknownKeys:"passthrough"})}extend(e){return new tt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new tt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ue.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new tt({...this._def,catchall:e})}pick(e){const n={};return Ee.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new tt({...this._def,shape:()=>n})}omit(e){const n={};return Ee.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new tt({...this._def,shape:()=>n})}deepPartial(){return yi(this)}partial(e){const n={};return Ee.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}),new tt({...this._def,shape:()=>n})}required(e){const n={};return Ee.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof wr;)s=s._def.innerType;n[r]=s}}),new tt({...this._def,shape:()=>n})}keyof(){return My(Ee.objectKeys(this.shape))}}tt.create=(t,e)=>new tt({shape:()=>t,unknownKeys:"strip",catchall:Wr.create(),typeName:ue.ZodObject,...ge(e)}),tt.strictCreate=(t,e)=>new tt({shape:()=>t,unknownKeys:"strict",catchall:Wr.create(),typeName:ue.ZodObject,...ge(e)}),tt.lazycreate=(t,e)=>new tt({shape:t,unknownKeys:"strip",catchall:Wr.create(),typeName:ue.ZodObject,...ge(e)});class ha extends ve{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const i=s.map(a=>new En(a.ctx.common.issues));return H(n,{code:z.invalid_union,unionErrors:i}),de}if(n.common.async)return Promise.all(r.map(async s=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s;const i=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const a=i.map(l=>new En(l));return H(n,{code:z.invalid_union,unionErrors:a}),de}}get options(){return this._def.options}}ha.create=(t,e)=>new ha({options:t,typeName:ue.ZodUnion,...ge(e)});const Hr=t=>t instanceof ga?Hr(t.schema):t instanceof qn?Hr(t.innerType()):t instanceof ya?[t.value]:t instanceof xo?t.options:t instanceof wa?Ee.objectValues(t.enum):t instanceof va?Hr(t._def.innerType):t instanceof da?[void 0]:t instanceof fa?[null]:t instanceof wr?[void 0,...Hr(t.unwrap())]:t instanceof To?[null,...Hr(t.unwrap())]:t instanceof Xd||t instanceof Sa?Hr(t.unwrap()):t instanceof ka?Hr(t._def.innerType):[];class oc extends ve{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==q.object)return H(n,{code:z.invalid_type,expected:q.object,received:n.parsedType}),de;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(H(n,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),de)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const o=new Map;for(const s of n){const i=Hr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new oc({typeName:ue.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...ge(r)})}}function Gd(t,e){const n=Ur(t),r=Ur(e);if(t===e)return{valid:!0,data:t};if(n===q.object&&r===q.object){const o=Ee.objectKeys(e),s=Ee.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(const a of s){const l=Gd(t[a],e[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===q.array&&r===q.array){if(t.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<t.length;s++){const i=t[s],a=e[s],l=Gd(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===q.date&&r===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class pa extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Yd(s)||Yd(i))return de;const a=Gd(s.value,i.value);return a.valid?((qd(s)||qd(i))&&n.dirty(),{status:n.value,value:a.data}):(H(r,{code:z.invalid_intersection_types}),de)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pa.create=(t,e,n)=>new pa({left:t,right:e,typeName:ue.ZodIntersection,...ge(n)});class yr extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==q.array)return H(r,{code:z.invalid_type,expected:q.array,received:r.parsedType}),de;if(r.data.length<this._def.items.length)return H(r,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),de;!this._def.rest&&r.data.length>this._def.items.length&&(H(r,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((i,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new gr(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Ht.mergeArray(n,i)):Ht.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new yr({...this._def,rest:e})}}yr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yr({items:t,typeName:ue.ZodTuple,rest:null,...ge(e)})};class ma extends ve{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return H(r,{code:z.invalid_type,expected:q.object,received:r.parsedType}),de;const o=[],s=this._def.keyType,i=this._def.valueType;for(const a in r.data)o.push({key:s._parse(new gr(r,a,r.path,a)),value:i._parse(new gr(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ht.mergeObjectAsync(n,o):Ht.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof ve?new ma({keyType:e,valueType:n,typeName:ue.ZodRecord,...ge(r)}):new ma({keyType:Kn.create(),valueType:e,typeName:ue.ZodRecord,...ge(n)})}}class sc extends ve{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==q.map)return H(r,{code:z.invalid_type,expected:q.map,received:r.parsedType}),de;const o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new gr(r,a,r.path,[c,"key"])),value:s._parse(new gr(r,l,r.path,[c,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return de;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of i){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return de;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}}sc.create=(t,e,n)=>new sc({valueType:e,keyType:t,typeName:ue.ZodMap,...ge(n)});class ms extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==q.set)return H(r,{code:z.invalid_type,expected:q.set,received:r.parsedType}),de;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(H(r,{code:z.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(H(r,{code:z.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return de;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}const a=[...r.data.values()].map((l,c)=>s._parse(new gr(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(e,n){return new ms({...this._def,minSize:{value:e,message:te.toString(n)}})}max(e,n){return new ms({...this._def,maxSize:{value:e,message:te.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}ms.create=(t,e)=>new ms({valueType:t,minSize:null,maxSize:null,typeName:ue.ZodSet,...ge(e)});class wi extends ve{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==q.function)return H(n,{code:z.invalid_type,expected:q.function,received:n.parsedType}),de;function r(a,l){return ec({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ql(),pi].filter(c=>!!c),issueData:{code:z.invalid_arguments,argumentsError:l}})}function o(a,l){return ec({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ql(),pi].filter(c=>!!c),issueData:{code:z.invalid_return_type,returnTypeError:l}})}const s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof vi){const a=this;return Qt(async function(...l){const c=new En([]),u=await a._def.args.parseAsync(l,s).catch(p=>{throw c.addIssue(r(l,p)),c}),f=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(f,s).catch(p=>{throw c.addIssue(o(f,p)),c})})}else{const a=this;return Qt(function(...l){const c=a._def.args.safeParse(l,s);if(!c.success)throw new En([r(l,c.error)]);const u=Reflect.apply(i,this,c.data),f=a._def.returns.safeParse(u,s);if(!f.success)throw new En([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new wi({...this._def,args:yr.create(e).rest(ps.create())})}returns(e){return new wi({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new wi({args:e||yr.create([]).rest(ps.create()),returns:n||ps.create(),typeName:ue.ZodFunction,...ge(r)})}}class ga extends ve{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}ga.create=(t,e)=>new ga({getter:t,typeName:ue.ZodLazy,...ge(e)});class ya extends ve{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return H(n,{received:n.data,code:z.invalid_literal,expected:this._def.value}),de}return{status:"valid",value:e.data}}get value(){return this._def.value}}ya.create=(t,e)=>new ya({value:t,typeName:ue.ZodLiteral,...ge(e)});function My(t,e){return new xo({values:t,typeName:ue.ZodEnum,...ge(e)})}class xo extends ve{constructor(){super(...arguments),la.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return H(n,{expected:Ee.joinValues(r),received:n.parsedType,code:z.invalid_type}),de}if(tc(this,la)||Ey(this,la,new Set(this._def.values)),!tc(this,la).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return H(n,{received:n.data,code:z.invalid_enum_value,options:r}),de}return Qt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return xo.create(e,{...this._def,...n})}exclude(e,n=this._def){return xo.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}la=new WeakMap,xo.create=My;class wa extends ve{constructor(){super(...arguments),ca.set(this,void 0)}_parse(e){const n=Ee.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==q.string&&r.parsedType!==q.number){const o=Ee.objectValues(n);return H(r,{expected:Ee.joinValues(o),received:r.parsedType,code:z.invalid_type}),de}if(tc(this,ca)||Ey(this,ca,new Set(Ee.getValidEnumValues(this._def.values))),!tc(this,ca).has(e.data)){const o=Ee.objectValues(n);return H(r,{received:r.data,code:z.invalid_enum_value,options:o}),de}return Qt(e.data)}get enum(){return this._def.values}}ca=new WeakMap,wa.create=(t,e)=>new wa({values:t,typeName:ue.ZodNativeEnum,...ge(e)});class vi extends ve{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==q.promise&&n.common.async===!1)return H(n,{code:z.invalid_type,expected:q.promise,received:n.parsedType}),de;const r=n.parsedType===q.promise?n.data:Promise.resolve(n.data);return Qt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}vi.create=(t,e)=>new vi({type:t,typeName:ue.ZodPromise,...ge(e)});class qn extends ve{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{H(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return de;const l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?de:l.status==="dirty"||n.value==="dirty"?mi(l.value):l});{if(n.value==="aborted")return de;const a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?de:a.status==="dirty"||n.value==="dirty"?mi(a.value):a}}if(o.type==="refinement"){const i=a=>{const l=o.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?de:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?de:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!fs(i))return i;const a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>fs(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):i);Ee.assertNever(o)}}qn.create=(t,e,n)=>new qn({schema:t,typeName:ue.ZodEffects,effect:e,...ge(n)}),qn.createWithPreprocess=(t,e,n)=>new qn({schema:e,effect:{type:"preprocess",transform:t},typeName:ue.ZodEffects,...ge(n)});class wr extends ve{_parse(e){return this._getType(e)===q.undefined?Qt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}wr.create=(t,e)=>new wr({innerType:t,typeName:ue.ZodOptional,...ge(e)});class To extends ve{_parse(e){return this._getType(e)===q.null?Qt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}To.create=(t,e)=>new To({innerType:t,typeName:ue.ZodNullable,...ge(e)});class va extends ve{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===q.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}va.create=(t,e)=>new va({innerType:t,typeName:ue.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ge(e)});class ka extends ve{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return aa(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new En(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new En(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ka.create=(t,e)=>new ka({innerType:t,typeName:ue.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ge(e)});class ic extends ve{_parse(e){if(this._getType(e)!==q.nan){const r=this._getOrReturnCtx(e);return H(r,{code:z.invalid_type,expected:q.nan,received:r.parsedType}),de}return{status:"valid",value:e.data}}}ic.create=t=>new ic({typeName:ue.ZodNaN,...ge(t)});const PN=Symbol("zod_brand");class Xd extends ve{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ba extends ve{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?de:s.status==="dirty"?(n.dirty(),mi(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?de:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new ba({in:e,out:n,typeName:ue.ZodPipeline})}}class Sa extends ve{_parse(e){const n=this._def.innerType._parse(e),r=o=>(fs(o)&&(o.value=Object.freeze(o.value)),o);return aa(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Sa.create=(t,e)=>new Sa({innerType:t,typeName:ue.ZodReadonly,...ge(e)});function Ay(t,e){const n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Iy(t,e={},n){return t?gi.create().superRefine((r,o)=>{var s,i;const a=t(r);if(a instanceof Promise)return a.then(l=>{var c,u;if(!l){const f=Ay(e,r),h=(u=(c=f.fatal)!==null&&c!==void 0?c:n)!==null&&u!==void 0?u:!0;o.addIssue({code:"custom",...f,fatal:h})}});if(!a){const l=Ay(e,r),c=(i=(s=l.fatal)!==null&&s!==void 0?s:n)!==null&&i!==void 0?i:!0;o.addIssue({code:"custom",...l,fatal:c})}}):gi.create()}const ON={object:tt.lazycreate};var ue;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ue||(ue={}));const DN=(t,e={message:`Input not instance of ${t.name}`})=>Iy(n=>n instanceof t,e),Ny=Kn.create,By=Co.create,RN=ic.create,zN=_o.create,Py=ua.create,$N=hs.create,LN=nc.create,VN=da.create,FN=fa.create,jN=gi.create,UN=ps.create,WN=Wr.create,HN=rc.create,ZN=Yn.create,KN=tt.create,YN=tt.strictCreate,qN=ha.create,JN=oc.create,GN=pa.create,XN=yr.create,QN=ma.create,eB=sc.create,tB=ms.create,nB=wi.create,rB=ga.create,oB=ya.create,sB=xo.create,iB=wa.create,aB=vi.create,Oy=qn.create,lB=wr.create,cB=To.create,uB=qn.createWithPreprocess,dB=ba.create;var Zr=Object.freeze({__proto__:null,defaultErrorMap:pi,setErrorMap:uN,getErrorMap:Ql,makeIssue:ec,EMPTY_PATH:dN,addIssueToContext:H,ParseStatus:Ht,INVALID:de,DIRTY:mi,OK:Qt,isAborted:Yd,isDirty:qd,isValid:fs,isAsync:aa,get util(){return Ee},get objectUtil(){return Kd},ZodParsedType:q,getParsedType:Ur,ZodType:ve,datetimeRegex:Ty,ZodString:Kn,ZodNumber:Co,ZodBigInt:_o,ZodBoolean:ua,ZodDate:hs,ZodSymbol:nc,ZodUndefined:da,ZodNull:fa,ZodAny:gi,ZodUnknown:ps,ZodNever:Wr,ZodVoid:rc,ZodArray:Yn,ZodObject:tt,ZodUnion:ha,ZodDiscriminatedUnion:oc,ZodIntersection:pa,ZodTuple:yr,ZodRecord:ma,ZodMap:sc,ZodSet:ms,ZodFunction:wi,ZodLazy:ga,ZodLiteral:ya,ZodEnum:xo,ZodNativeEnum:wa,ZodPromise:vi,ZodEffects:qn,ZodTransformer:qn,ZodOptional:wr,ZodNullable:To,ZodDefault:va,ZodCatch:ka,ZodNaN:ic,BRAND:PN,ZodBranded:Xd,ZodPipeline:ba,ZodReadonly:Sa,custom:Iy,Schema:ve,ZodSchema:ve,late:ON,get ZodFirstPartyTypeKind(){return ue},coerce:{string:t=>Kn.create({...t,coerce:!0}),number:t=>Co.create({...t,coerce:!0}),boolean:t=>ua.create({...t,coerce:!0}),bigint:t=>_o.create({...t,coerce:!0}),date:t=>hs.create({...t,coerce:!0})},any:jN,array:ZN,bigint:zN,boolean:Py,date:$N,discriminatedUnion:JN,effect:Oy,enum:sB,function:nB,instanceof:DN,intersection:GN,lazy:rB,literal:oB,map:eB,nan:RN,nativeEnum:iB,never:WN,null:FN,nullable:cB,number:By,object:KN,oboolean:()=>Py().optional(),onumber:()=>By().optional(),optional:lB,ostring:()=>Ny().optional(),pipeline:dB,preprocess:uB,promise:aB,record:QN,set:tB,strictObject:YN,string:Ny,symbol:LN,transformer:Oy,tuple:XN,undefined:VN,union:qN,unknown:UN,void:HN,NEVER:de,ZodIssueCode:z,quotelessJson:cN,ZodError:En}),fB=Object.defineProperty,ki=(t,e)=>{for(var n in e)fB(t,n,{get:e[n],enumerable:!0})},Ea=pe("drag-block"),hB=pe("remove-block"),Qd=pe("remove-selected"),Dy=pe("bring-forward-selected"),Ry=pe("send-backward-selected"),zy=pe("clone-entities"),ef=pe("unclone-entities"),ac=pe("set-cursor"),$y=pe("cut"),Ly=pe("copy"),Vy=pe("paste"),tf=pe("select-block"),pB=pe("deselect-block"),Fy=pe("toggle-select"),bi=pe("deselect-all"),jy=pe("select-all"),Uy=pe("add-selection-box"),Wy=pe("update-selection-box"),Hy=pe("remove-selection-box"),Zy=pe("add-held"),Ky=pe("remove-held"),Yy=pe("add-transform-box"),nf=pe("update-transform-box"),qy=pe("hide-transform-box"),Jy=pe("show-transform-box"),rf=pe("remove-transform-box"),Gy=pe("start-transform-box-edit"),mB=pe("end-transform-box-edit"),Xy={};ki(Xy,{DragStart:()=>yt,EditAfterPlacing:()=>Ca,Selected:()=>xt,SelectionBox:()=>lc,TransformBox:()=>en,TransformHandle:()=>Ye});var yt=Qe({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)}),Ca=Qe({name:"editAfterPlacing"},{}),xt=Qe({name:"selected"},{}),lc=Qe({name:"selectionBox"},{}),en=Qe({name:"transformBox"},{}),gB=`
|
|
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 @@ ${f.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
|
|
53
|
+
</svg>`;function cc(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 @@ ${f.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
|
|
61
|
+
</svg>`}function uc(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 @@ ${f.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 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;
|
|
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
|
|
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 {
|
|
69
|
+
</svg>`}var yB={drag:{makeSvg:()=>gB,hotspot:[12,12],rotationOffset:0},ns:{makeSvg:cc,hotspot:[12,12],rotationOffset:0},ew:{makeSvg:cc,hotspot:[12,12],rotationOffset:Math.PI/2},nwse:{makeSvg:cc,hotspot:[12,12],rotationOffset:-Math.PI/4},nesw:{makeSvg:cc,hotspot:[12,12],rotationOffset:Math.PI/4},rotateNW:{makeSvg:uc,hotspot:[16,16],rotationOffset:0},rotateNE:{makeSvg:uc,hotspot:[16,16],rotationOffset:Math.PI/2},rotateSW:{makeSvg:uc,hotspot:[16,16],rotationOffset:-Math.PI/2},rotateSE:{makeSvg:uc,hotspot:[16,16],rotationOffset:-Math.PI}},_e={Idle:"idle",Pointing:"pointing",Dragging:"dragging",SelectionBoxPointing:"selectionBoxPointing",SelectionBoxDragging:"selectionBoxDragging"},Jn={None:"none",Idle:"idle",Editing:"editing"},Gn={Scale:"scale",Stretch:"stretch",Rotate:"rotate"},Dn={Idle:"idle",Waiting:"waiting",Scrolling:"scrolling"},Qy=Zr.object({enabled:Zr.boolean().default(!0),edgeSizePx:Zr.number().default(10),edgeScrollSpeedPxPerFrame:Zr.number().default(15),edgeScrollDelayMs:Zr.number().default(250)}),wB=Zr.object({edgeScrolling:Qy.default(Qy.parse({}))}),Ye=Qe({name:"transformHandle"},{kind:C.string().max(16).default(Gn.Scale),vectorX:C.int8().default(0),vectorY:C.int8().default(0),transformBox:C.ref(),cursorKind:C.string().max(16).default("drag")}),e0="selection";function vB(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]=kB(t,a)}return r}function kB(t,e){return e==null||!R(t,e,me)?null:me.read(t,e).id}function bB(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 SB(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 EB=ie(t=>t.with(xt));ie(t=>t.with(T));function Si(t,e){if(R(t,e,xt)||Zd(t,e))return;const{sessionId:n}=Je(t);ee(t,e,xt,{}),R(t,e,Rt)||ee(t,e,Rt,{sessionId:n})}function _a(t,e){R(t,e,xt)&&(mn(t,e,xt),mn(t,e,Rt))}function t0(t){for(const e of EB.current(t))_a(t,e)}function CB(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 _B=class{constructor(t){this.seed=typeof t=="string"?CB(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 of(t,e){const n=t+e,r=new _B(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 n0={};ki(n0,{Clipboard:()=>xa,ScrollEdgesStateSingleton:()=>sf,SelectionStateSingleton:()=>Xn,TransformBoxStateSingleton:()=>af});var xB={count:C.uint32().default(0),center:C.tuple(C.float64(),2).default([0,0])},dc=new WeakMap,TB=class extends vt{constructor(){super({name:"clipboard"},xB)}setEntities(t,e){const{editor:n}=Je(t);dc.set(n,e)}getEntities(t){const{editor:e}=Je(t);return dc.get(e)??[]}clearEntities(t){const{editor:e}=Je(t);dc.delete(e)}hasContent(t){const{editor:e}=Je(t),n=dc.get(e);return n!==void 0&&n.length>0}},xa=new TB,sf=Eo("scrollEdgesState",{state:C.enum(Dn).default(Dn.Idle),edgeEnterStartTime:C.float64().default(0)}),Xn=Eo("selectionState",{state:C.enum(_e).default(_e.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()}),af=Eo("transformBoxState",{state:C.string().max(32).default(Jn.None),transformBoxId:C.ref()}),r0={};ki(r0,{hoverCursorSystem:()=>AB,scrollEdgesSystem:()=>NB,transformBoxSystem:()=>OB});var lf=ie(t=>t.with(bo,Ye).tracking(bo)),MB=ie(t=>t.with(T,en).tracking(T)),AB=Se({phase:"capture"},t=>{const e=lf.added(t),n=lf.removed(t),r=lf.current(t),o=MB.changed(t);if(r.length===0&&n.length>0){Pn.clearContextCursor(t);return}if((e.length>0||o.length>0)&&r.length>0){const i=r[0],a=Ye.read(t,i);if(a.transformBox===null)return;const l=T.read(t,a.transformBox),c=Pn.read(t);(a.cursorKind!==c.contextCursorKind||l.rotateZ!==c.contextRotation)&&Pn.setContextCursor(t,a.cursorKind,l.rotateZ)}});function fc(t){return ls(t,e0).edgeScrolling}var IB=zr({guards:{isPointerNearEdge:({event:t})=>{const{edgeSizePx:e}=fc(t.ctx),n=_t.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}=fc(e.ctx);return performance.now()-t.edgeEnterStartTime>=n}},actions:{setEdgeEnterStartTime:Ze({edgeEnterStartTime:()=>performance.now()}),moveCamera:({event:t})=>{const{edgeSizePx:e,edgeScrollSpeedPxPerFrame:n}=fc(t.ctx),r=_t.read(t.ctx),o=we.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=we.write(t.ctx);h.left+=c,h.top+=u},resetContext:Ze({edgeEnterStartTime:0})}}).createMachine({id:"scrollEdges",initial:Dn.Idle,context:{edgeEnterStartTime:0},states:{[Dn.Idle]:{entry:"resetContext",on:{pointerMove:{guard:"isPointerNearEdge",target:Dn.Waiting}}},[Dn.Waiting]:{entry:"setEdgeEnterStartTime",on:{pointerMove:{guard:rs("isPointerNearEdge"),target:Dn.Idle},frame:{guard:"isEdgeScrollDelayPassed",target:Dn.Scrolling}}},[Dn.Scrolling]:{on:{frame:[{guard:rs("isPointerNearEdge"),target:Dn.Idle},{actions:"moveCamera"}]}}}}),NB=Se({phase:"capture"},t=>{if(!fc(t).enabled)return;const e=Xn.read(t).state;if(e!==_e.Dragging&&e!==_e.SelectionBoxDragging)return;const n=sf.read(t).state,r=n===Dn.Waiting||n===Dn.Scrolling,o=ct.getButtons(t,"select"),s=jr(t,o,{includeFrameEvent:r});s.length!==0&&sf.run(t,IB,s)}),hc=ie(t=>t.with(T).tracking(xt)),BB=zr({guards:{isSelectionEditable:({event:t})=>PB(t.ctx),isOverTransformBox:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:R(t.ctx,t.intersects[0],en),isOverTransformHandle:({event:t})=>!("intersects"in t)||t.intersects.length===0?!1:R(t.ctx,t.intersects[0],Ye),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=T.read(t.ctx,e);return Xt(t.ctx,n.tag).resizeMode!=="groupOnly"},hasEditAfterPlacing:({event:t})=>t.type!=="selectionChanged"||t.selectedEntityIds.length!==1?!1:R(t.ctx,t.selectedEntityIds[0],Ca)},actions:{addTransformBox:Ze(({context:t,event:e},n)=>{t.transformBoxId!==null&&rf.spawn(e.ctx,{transformBoxId:t.transformBoxId});const r=Bt(e.ctx);return Yy.spawn(e.ctx,{transformBoxId:r,skipHandles:n==null?void 0:n.skipHandles}),{transformBoxId:r}}),updateTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&nf.spawn(e.ctx,{transformBoxId:t.transformBoxId})},hideTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&qy.spawn(e.ctx,{transformBoxId:t.transformBoxId})},showTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&Jy.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeTransformBox:({context:t,event:e})=>{t.transformBoxId!==null&&rf.spawn(e.ctx,{transformBoxId:t.transformBoxId})},clearTransformBoxId:Ze({transformBoxId:()=>null}),startTransformBoxEdit:({context:t,event:e})=>{t.transformBoxId!==null&&Gy.spawn(e.ctx,{transformBoxId:t.transformBoxId})},removeEditAfterPlacing:({event:t})=>{if(t.type==="selectionChanged")for(const e of t.selectedEntityIds)R(t.ctx,e,Ca)&&mn(t.ctx,e,Ca)}}}).createMachine({id:"transformBox",initial:Jn.None,context:{transformBoxId:null},states:{[Jn.None]:{entry:["removeTransformBox","clearTransformBoxId"],on:{selectionChanged:[{guard:Ji(["hasEditAfterPlacing","selectionIsTransformable","isSelectionEditable"]),actions:[{type:"addTransformBox",params:{skipHandles:!0}},"removeEditAfterPlacing"],target:Jn.Editing},{guard:"selectionIsTransformable",target:Jn.Idle}]}},[Jn.Idle]:{entry:["addTransformBox"],on:{selectionChanged:[{guard:rs("selectionIsTransformable"),target:Jn.None},{guard:"selectionIsTransformable",actions:"showTransformBox"},{actions:"updateTransformBox"}],pointerDown:{actions:"hideTransformBox"},pointerUp:{actions:"showTransformBox"},click:{guard:Ji(["isOverTransformBox","isSelectionEditable"]),target:Jn.Editing}}},[Jn.Editing]:{entry:["hideTransformBox","startTransformBoxEdit"],on:{pointerDown:{guard:Ji([rs("isOverTransformBox"),rs("isOverTransformHandle")]),target:Jn.None},selectionChanged:{target:Jn.None,actions:Ul(({event:t})=>t)}}}}});function PB(t){const e=hc.current(t);if(e.length!==1)return!1;const n=e[0],r=T.read(t,n);return ay(t,r.tag)}var OB=Se({phase:"capture"},t=>{const e=[],n=hc.added(t),r=hc.removed(t);if(n.length>0||r.length>0){const i=[...hc.current(t)],a={type:"selectionChanged",ctx:t,selectedEntityIds:i};e.push(a)}const o=ct.getButtons(t,"select"),s=jr(t,o);e.push(...s),e.length!==0&&af.run(t,BB,e)}),o0={};ki(o0,{transformBoxSystem:()=>LB});var pc=ie(t=>t.with(T,xt)),DB=ie(t=>t.with(T,$r)),RB="a",zB="b",s0="c",$B="d",LB=Se({phase:"update",priority:-100},t=>{fe(t,rf,(e,{transformBoxId:n})=>{VB(e,n)}),fe(t,Yy,(e,{transformBoxId:n,skipHandles:r})=>{FB(e,n,r)}),fe(t,nf,(e,{transformBoxId:n})=>{cf(e,n)}),fe(t,qy,(e,{transformBoxId:n})=>{UB(e,n)}),fe(t,Jy,(e,{transformBoxId:n})=>{WB(e,n)}),fe(t,Gy,(e,{transformBoxId:n})=>{HB(e,n)}),fe(t,mB,uf)});function VB(t,e){if(!R(t,e,en)){uf(t);return}const n=dr(t,e,Ye,"transformBox");for(const r of n)st(t,r);st(t,e),uf(t)}function FB(t,e,n){ee(t,e,T,{tag:"transform-box",position:[0,0],size:[0,0],rotateZ:0,rank:RB}),ee(t,e,en,{}),ee(t,e,yt,{position:[0,0],size:[0,0],rotateZ:0,fontSize:16}),n||cf(t,e)}function cf(t,e){if(!AE(t,e))return;const n=pc.current(t);if(n.length===0)return;let r=0;r=T.read(t,n[0]).rotateZ;for(let c=1;c<n.length;c++){const u=T.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=T.getCorners(t,c);s.push(...u)}if(s.length===0)return;const i=T.write(t,e);if(i.rotateZ=r,pt.boundPoints(i.position,i.size,r,s),!(Xn.read(t).state===_e.Dragging)){if(R(t,e,yt)){const c=yt.write(t,e);c.position=i.position,c.size=i.size,c.rotateZ=r}for(const c of n){const u=T.read(t,c),f=R(t,c,gt)?gt.read(t,c).fontSizePx:16;if(!R(t,c,yt))ee(t,c,yt,{position:u.position,size:u.size,rotateZ:u.rotateZ,flip:u.flip,fontSize:f});else{const h=yt.write(t,c);h.position=u.position,h.size=u.size,h.rotateZ=u.rotateZ,h.flip=u.flip,h.fontSize=f}}}jB(t,e)}function jB(t,e){const n=T.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=pc.current(t);let w="scale";if(y.length===1){const A=T.read(t,y[0]);w=Xt(t,A.tag).resizeMode}else y.length>1&&y.every(F=>{const Y=T.read(t,F);return Xt(t,Y.tag).resizeMode==="free"})&&(w="free");const v=y.every(A=>{const F=T.read(t,A);return Xt(t,F.tag).canRotate}),b=y.every(A=>{const F=T.read(t,A);return Xt(t,F.tag).canScale});let S;switch(w){case"scale":case"text":S=Gn.Scale;break;case"free":S=Gn.Stretch;break;default:S=Gn.Scale;break}const k=we.read(t),E=l*k.zoom,_=c*k.zoom,M=Math.min(E,_),I=15;for(let A=0;A<2;A++)for(let F=0;F<2;F++)A+F!==1&&M<I/2||A+F===1&&_<I||(b&&m.push({tag:"transform-handle",kind:S,vectorX:A*2-1,vectorY:F*2-1,left:i+l*A-f/2,top:a+c*F-f/2,width:f,height:f,rotateZ:s,rank:$B,cursorKind:A+F===1?"nesw":"nwse",scaleMultiplier:[1,1],anchor:[.5,.5]}),v&&m.push({tag:"transform-rotate",kind:Gn.Rotate,vectorX:A*2-1,vectorY:F*2-1,left:i+A*l-(1-A)*h,top:a+F*c-(1-F)*h,width:h,height:h,rotateZ:s,rank:zB,cursorKind:g[A+F*2],scaleMultiplier:[.5,.5],anchor:[1-A,1-F]}));if(b)for(let A=0;A<2;A++)m.push({tag:"transform-edge",kind:S,vectorX:0,vectorY:A*2-1,left:i,top:a+c*A-p/2,width:l,height:p,rotateZ:s,rank:s0,cursorKind:"ns",scaleMultiplier:[0,1],anchor:[.5,.5]});if(b||w==="text")for(let A=0;A<2;A++)m.push({tag:"transform-edge",kind:w==="text"?Gn.Stretch:S,vectorX:A*2-1,vectorY:0,left:i+l*A-p/2,top:a,width:p,height:c,rotateZ:s,rank:s0,cursorKind:"ew",scaleMultiplier:[1,0],anchor:[.5,.5]});const P=dr(t,e,Ye,"transformBox"),V=new Map;for(const A of P){const F=Ye.read(t,A),Y=`${F.kind}-${F.vectorX}-${F.vectorY}`;V.set(Y,A)}const Z=new Set;for(const A of m){const F=`${A.kind}-${A.vectorX}-${A.vectorY}`;let Y=V.get(F);const ce=[A.left+A.width/2,A.top+A.height/2],se=$.clone(ce);$.rotateAround(se,u,s);const j=se[0]-A.width/2,X=se[1]-A.height/2;Y||(Y=Bt(t),ee(t,Y,T),ee(t,Y,Ye),ee(t,Y,yt),ee(t,Y,So));const he=T.write(t,Y);he.tag=A.tag,he.position=[j,X],he.size=[A.width,A.height],he.rotateZ=A.rotateZ,he.rank=A.rank;const Te=Ye.write(t,Y);Te.transformBox=e,Te.kind=A.kind,Te.vectorX=A.vectorX,Te.vectorY=A.vectorY,Te.cursorKind=A.cursorKind;const Ce=yt.write(t,Y);Ce.position=[j,X],Ce.size=[A.width,A.height],Ce.rotateZ=A.rotateZ;const je=So.write(t,Y);je.startPosition=[j,X],je.startSize=[A.width,A.height],$.copy(je.scaleMultiplier,A.scaleMultiplier),$.copy(je.anchor,A.anchor),Z.add(Y)}for(const A of P)Z.has(A)||st(t,A)}function UB(t,e){if(!R(t,e,en))return;if(!R(t,e,lt))ee(t,e,lt,{value:0});else{const r=lt.write(t,e);r.value=0}const n=dr(t,e,Ye,"transformBox");for(const r of n)if(!R(t,r,lt))ee(t,r,lt,{value:0});else{const o=lt.write(t,r);o.value=0}}function WB(t,e){if(!R(t,e,en))return;const n=pc.current(t);if(n.length===0)return;if(n.length===1){const o=T.read(t,n[0]);if(Xt(t,o.tag).resizeMode==="groupOnly")return}R(t,e,lt)&&mn(t,e,lt);const r=dr(t,e,Ye,"transformBox");for(const o of r)R(t,o,lt)&&mn(t,o,lt);cf(t,e)}function HB(t,e){if(R(t,e,en)){const n=dr(t,e,Ye,"transformBox");for(const r of n)st(t,r)}for(const n of pc.current(t))R(t,n,$r)||ee(t,n,$r,{})}function uf(t){for(const e of DB.current(t))R(t,e,$r)&&mn(t,e,$r)}var i0={};ki(i0,{selectSystem:()=>qB});var ZB=4,a0=ie(t=>t.with(T,xt,me)),KB=ie(t=>t.with(T,$r)),YB=zr({guards:{isThresholdReached:({context:t,event:e})=>$.distance(t.pointingStartClient,e.screenPosition)>=ZB,isOverBlock:({event:t})=>t.intersects.length>0,isOverSyncedBlock:({event:t})=>{const e=t.ctx;for(const n of t.intersects)if(R(e,n,me))return!0;return!1},isNotHeldByRemote:({event:t})=>{const e=t.ctx,n=t.intersects[0];return n?!Zd(e,n):!0},hasEditedBlocks:({event:t})=>KB.current(t.ctx).length>0},actions:{setPointingStart:Ze({pointingStartClient:({event:t})=>t.screenPosition,pointingStartWorld:({event:t})=>t.worldPosition}),setDragStart:Ze({dragStart:({event:t})=>t.worldPosition}),addHeldToDragged:({context:t,event:e})=>{t.draggedEntity!==null&&Zy.spawn(e.ctx,{entityId:t.draggedEntity})},removeHeldFromDragged:({context:t,event:e})=>{t.draggedEntity!==null&&Ky.spawn(e.ctx,{entityId:t.draggedEntity})},setDragCursor:({event:t,context:e})=>{if(e.draggedEntity)if(R(t.ctx,e.draggedEntity,Ye)){const n=Ye.read(t.ctx,e.draggedEntity),r=n.transformBox!==null?T.read(t.ctx,n.transformBox):void 0;ac.spawn(t.ctx,{contextCursorKind:n.cursorKind,contextRotation:(r==null?void 0:r.rotateZ)??0})}else ac.spawn(t.ctx,{contextCursorKind:"drag",contextRotation:0})},unsetDragCursor:({event:t})=>{ac.spawn(t.ctx,{contextCursorKind:""})},setDraggedEntity:Ze({draggedEntity:({event:t})=>t.intersects[0]??null,draggedEntityStart:({event:t})=>{if(!t.intersects.length)return[0,0];const e=t.intersects[0],n=T.read(t.ctx,e);return[n.position[0],n.position[1]]}}),resetDragged:({context:t,event:e})=>{t.draggedEntity!==null&&(Ea.spawn(e.ctx,{entityId:t.draggedEntity,position:t.draggedEntityStart}),t.isCloning&&ef.spawn(e.ctx,{entityIds:[t.draggedEntity],seed:t.cloneGeneratorSeed}))},resetContext:Ze({dragStart:()=>[0,0],pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],draggedEntityStart:()=>[0,0],draggedEntity:()=>null,cloneGeneratorSeed:()=>crypto.randomUUID(),isCloning:()=>!1}),createSelectionBox:({event:t})=>{Uy.spawn(t.ctx,void 0)},removeSelectionBox:({event:t})=>{Hy.spawn(t.ctx,void 0)},updateDragged:Ze({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=R(n,t.draggedEntity,me)||R(n,t.draggedEntity,en);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=Wt.snapX(n,r),o=Wt.snapY(n,o)),Ea.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=R(n,t.draggedEntity,en)?Array.from(a0.current(n)):[t.draggedEntity];zy.spawn(n,{entityIds:u,offset:[a,l],seed:t.cloneGeneratorSeed})}else if(!e.altDown&&t.isCloning){const l=R(n,t.draggedEntity,en)?Array.from(a0.current(n)):[t.draggedEntity];ef.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]);Wy.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(R(e,r,me)){n=r;break}n!==void 0&&(t.shiftDown?Fy.spawn(e,{entityId:n}):tf.spawn(e,{entityId:n,deselectOthers:!0}))},selectDragged:({context:t,event:e})=>{t.draggedEntity!==null&&R(e.ctx,t.draggedEntity,me)&&tf.spawn(e.ctx,{entityId:t.draggedEntity,deselectOthers:!0})},deselectAllIfShiftNotDown:({event:t})=>{t.shiftDown||bi.spawn(t.ctx,void 0)},deselectAllIfDraggedNotSelected:({context:t,event:e})=>{t.draggedEntity!==null&&(R(e.ctx,t.draggedEntity,xt)||R(e.ctx,t.draggedEntity,en)||R(e.ctx,t.draggedEntity,Ye)||bi.spawn(e.ctx,void 0))}}}).createMachine({id:"selection",initial:_e.Idle,context:{dragStart:[0,0],pointingStartClient:[0,0],pointingStartWorld:[0,0],draggedEntityStart:[0,0],draggedEntity:null,cloneGeneratorSeed:crypto.randomUUID(),isCloning:!1},states:{[_e.Idle]:{entry:["resetContext"],on:{pointerDown:[{guard:Ji(["isOverBlock","isNotHeldByRemote"]),target:_e.Pointing},{actions:"deselectAllIfShiftNotDown",target:_e.SelectionBoxPointing}]}},[_e.Pointing]:{entry:["setPointingStart","setDraggedEntity"],on:{pointerMove:{guard:Ji(["isThresholdReached",rs("hasEditedBlocks")]),target:_e.Dragging},pointerUp:[{guard:"isOverSyncedBlock",actions:"selectIntersect",target:_e.Idle},{actions:"deselectAllIfShiftNotDown",target:_e.Idle}],cancel:{target:_e.Idle}}},[_e.Dragging]:{entry:["setDragStart","addHeldToDragged","setDragCursor","deselectAllIfDraggedNotSelected"],exit:["unsetDragCursor"],on:{pointerMove:{actions:"updateDragged"},pointerUp:{actions:"selectDragged",target:_e.Idle},cancel:{actions:["resetDragged","removeHeldFromDragged"],target:_e.Idle}}},[_e.SelectionBoxPointing]:{entry:["setPointingStart"],on:{pointerMove:{guard:"isThresholdReached",target:_e.SelectionBoxDragging},pointerUp:{target:_e.Idle},cancel:{target:_e.Idle}}},[_e.SelectionBoxDragging]:{entry:["setDragStart","createSelectionBox"],exit:"removeSelectionBox",on:{pointerMove:{actions:"resizeSelectionBox"},pointerUp:{target:_e.Idle},cancel:{target:_e.Idle}}}}}),qB=Se({phase:"capture",priority:100},t=>{let e=ct.getButtons(t,"select");Xn.read(t).state===_e.Dragging&&e.length===0&&(e=["left"]);const r=jr(t,e);r.length!==0&&Xn.run(t,YB,r)}),l0={};ki(l0,{blockSystem:()=>JB,dragHandlerSystem:()=>nP,selectSystem:()=>cP});var Ei=ie(t=>t.with(T,xt)),c0=ie(t=>t.with(T,me)),JB=Se({phase:"update"},t=>{fe(t,Ea,(e,{entityId:n,position:r})=>{if(!R(e,n,T))return;const o=T.write(e,n);o.position=r}),fe(t,tf,(e,{entityId:n,deselectOthers:r})=>{r&&df(e),Si(e,n)}),fe(t,pB,(e,{entityId:n})=>{_a(e,n)}),fe(t,Fy,(e,{entityId:n})=>{R(e,n,xt)?_a(e,n):Si(e,n)}),fe(t,bi,df),fe(t,Zy,(e,{entityId:n})=>{if(!R(e,n,me)||R(e,n,Rt))return;const{sessionId:r}=Je(e);ee(e,n,Rt,{sessionId:r})}),fe(t,Ky,(e,{entityId:n})=>{R(e,n,xt)||R(e,n,Rt)&&mn(e,n,Rt)}),fe(t,jy,e=>{for(const n of c0.current(e))Si(e,n)}),fe(t,hB,(e,{entityId:n})=>{st(e,n)}),fe(t,Qd,e=>{for(const n of Ei.current(e))st(e,n)}),fe(t,Dy,GB),fe(t,Ry,XB),fe(t,ac,(e,n)=>{n.cursorKind!==void 0&&Pn.setCursor(e,n.cursorKind,n.rotation??0),n.contextCursorKind!==void 0&&Pn.setContextCursor(e,n.contextCursorKind,n.contextRotation??0),n.contextCursorKind===""&&Pn.clearContextCursor(e)}),fe(t,Ly,e=>{u0(e)}),fe(t,$y,e=>{u0(e);for(const n of Ei.current(e))st(e,n)}),fe(t,Vy,(e,n)=>{QB(e,n==null?void 0:n.position)}),fe(t,zy,(e,{entityIds:n,offset:r,seed:o})=>{eP(e,n,r,o)}),fe(t,ef,(e,{entityIds:n,seed:r})=>{tP(e,n,r)})});function df(t){for(const e of Ei.current(t))_a(t,e)}function GB(t){const e=[...Ei.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=T.read(t,n),s=T.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=T.write(t,n);r.rank=Zn.genNext(t)}}}function XB(t){const e=[...Ei.current(t)];if(e.length!==0){e.sort((n,r)=>{const o=T.read(t,n),s=T.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=T.write(t,n);r.rank=Zn.genPrev(t)}}}function u0(t){const e=[...Ei.current(t)];if(e.length===0)return;const{componentsById:n}=Je(t),r=new Map([...n].filter(([,c])=>c.sync==="document")),o=[],s=ne.zero();let i=!1;const a=me._getComponentId(t);for(const c of e){const u=new Map;R(t,c,me)&&u.set(a,me.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=vB(t,h.schema,p);u.set(f,m)}}if(o.push(u),R(t,c,Ve)){const{value:f}=Ve.read(t,c);i?ne.union(s,f):(ne.copy(s,f),i=!0)}}xa.setEntities(t,o);const l=xa.write(t);l.count=o.length,l.center=ne.center(s)}function QB(t,e){const n=xa.getEntities(t);if(n.length===0)return;const{componentsById:r}=Je(t),o=new Map([...r].filter(([,h])=>h.sync==="document")),s=xa.read(t),i=me._getComponentId(t),a=T._getComponentId(t);let l;if(e)l=$.clone(e),$.sub(l,s.center);else{const h=we.getWorldCenter(t);l=$.clone(h),$.sub(l,s.center),Wt.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});df(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),ee(t,p,me,{id:crypto.randomUUID()});for(const[g,y]of h){if(g===i)continue;const w=o.get(g);if(!w)continue;const v={...y};if(g===a){const S=$.clone(v.position);$.add(S,l),v.position=S,v.rank=Zn.genNext(t)}const b=bB(w.schema);if(b.length>0){for(const S of b)delete v[S];f.push({entityId:p,componentDef:w,componentData:y})}ee(t,p,w,v)}Si(t,p)}for(const{entityId:h,componentDef:p,componentData:m}of f)SB(t,h,p,m,u)}function eP(t,e,n,r){const{componentsById:o}=Je(t),s=new Map([...o].filter(([,c])=>c.sync==="document")),i=me._getComponentId(t),a=T._getComponentId(t),l=new Map;for(const c of e){if(!R(t,c,me))continue;const u=me.read(t,c),f=of(u.id,r),h=Bt(t);l.set(c,h),ee(t,h,me,{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=$.clone(g.position);$.add(y,n),g.position=y,g.rank=Zn.genPrev(t)}ee(t,h,m,g)}}d0(t,l)}function tP(t,e,n){const r=new Set;for(const i of e){if(!R(t,i,me))continue;const a=me.read(t,i);r.add(of(a.id,n))}const o=[];for(const i of c0.current(t)){const a=me.read(t,i);r.has(a.id)&&o.push(i)}const s=new Map;for(const i of o){const a=me.read(t,i).id;for(const l of e){if(!R(t,l,me))continue;const c=me.read(t,l).id;if(of(c,n)===a){s.set(i,l);break}}}d0(t,s);for(const i of o)st(t,i)}function d0(t,e){for(const[n,r]of e){for(const o of dr(t,n,Ke,"startBlock"))Ke.write(t,o).startBlock=r;for(const o of dr(t,n,Ke,"endBlock"))Ke.write(t,o).endBlock=r}}var ff=ie(t=>t.with(T,xt)),f0=ie(t=>t.with(T,en,yt)),nP=Se({phase:"update"},t=>{fe(t,Ea,(e,{entityId:n,position:r})=>{if(R(e,n,en)){rP(e,n,r);return}if(R(e,n,Ye)){oP(e,n,r);return}})});function rP(t,e,n){const r=yt.read(t,e),o=n[0]-r.position[0],s=n[1]-r.position[1];for(const i of ff.current(t)){if(!R(t,i,yt))continue;const a=yt.read(t,i),l=T.write(t,i);l.position=[a.position[0]+o,a.position[1]+s],Wt.snapPosition(t,l.position)}}function oP(t,e,n){const r=Ye.read(t,e);r.kind===Gn.Rotate?sP(t,e,n):r.kind===Gn.Scale?h0(t,e,n,!0):r.kind===Gn.Stretch&&h0(t,e,n,!1)}function sP(t,e,n){const r=f0.current(t);if(r.length===0){console.warn("No transform box found for rotation");return}const o=r[0],s=T.write(t,o),i=T.getCenter(t,o),a=T.read(t,e),l=[n[0]+a.size[0]/2,n[1]+a.size[1]/2],c=$.angleTo(i,l),u=yt.read(t,o),f=Ye.read(t,e),h=$.angle([s.size[0]*f.vectorX,s.size[1]*f.vectorY])+u.rotateZ;let p=c-h;const m=Wt.read(t),g=Sn.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=Dt.normalizeAngle(u.rotateZ+p);for(const w of ff.current(t)){if(!R(t,w,yt))continue;const v=yt.read(t,w),b=T.write(t,w);b.rotateZ=Dt.normalizeAngle(v.rotateZ+p);const S=[v.position[0]+v.size[0]/2,v.position[1]+v.size[1]/2],k=$.distance(i,S),E=$.angleTo(i,S)+p,_=$.fromPolar(k,E,i);b.position=[_[0]-b.size[0]/2,_[1]-b.size[1]/2],m.strict&&Wt.snapPosition(t,b.position)}}function h0(t,e,n,r){const o=f0.current(t);if(o.length===0){console.warn("No transform box found for scaling");return}const s=o[0],i=yt.read(t,s),a=Ye.read(t,e),l=T.read(t,e),c=[n[0]+l.size[0]/2,n[1]+l.size[1]/2];Wt.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];$.rotate(h,u);const p=[f[0]+h[0],f[1]+h[1]],m=[c[0]-p[0],c[1]-p[1]],g=$.clone(m);$.rotate(g,-u);let y=a.vectorX,w=a.vectorY,v=!1,b=!1;Math.sign(g[0])!==y&&y!==0&&(y=-y,v=!0),Math.sign(g[1])!==w&&w!==0&&(w=-w,b=!0);let S=Math.max(Math.abs(g[0]),1),k=Math.max(Math.abs(g[1]),1);if(r){const Z=i.size[0]/i.size[1];S/k>Z?k=S/Z:S=k*Z}else a.vectorX===0?S=i.size[0]:a.vectorY===0&&(k=i.size[1]);const E=i.size[0]>0?S/i.size[0]:1,_=i.size[1]>0?k/i.size[1]:1,M=Wt.read(t),I=$.create(y*S,w*k);$.rotate(I,u),$.scale(I,.5);const P=$.clone(p);$.add(P,I);const V=[E,_];for(const Z of ff.current(t)){if(!R(t,Z,yt))continue;const A=yt.read(t,Z),F=T.write(t,Z),Y=$.clone(A.position);$.add(Y,[A.size[0]/2,A.size[1]/2]);const ce=$.clone(Y);$.sub(ce,f),$.rotate(ce,-u),$.multiply(ce,V),v&&(ce[0]=-ce[0]),b&&(ce[1]=-ce[1]),$.rotate(ce,u);const se=$.clone(P);$.add(se,ce);const j=$.clone(A.size);$.multiply(j,V);const X=Xt(t,F.tag),he=(X==null?void 0:X.resizeMode)==="text";if(M.strict)if(he&&r){j[1]=Math.max(M.rowHeight,Wt.snapY(t,j[1]));const Te=A.size[0]/A.size[1];j[0]=j[1]*Te}else Wt.snapSize(t,j);if($.copy(F.position,se),$.sub(F.position,[j[0]/2,j[1]/2]),M.strict&&Wt.snapPosition(t,F.position),!r&&a.vectorY===0?F.size[0]=j[0]:!r&&a.vectorX===0?F.size[1]=j[1]:$.copy(F.size,j),R(t,Z,gt)){const Te=a.kind===Gn.Stretch,Ce=gt.write(t,Z);if(Te)Ce.constrainWidth=!0;else{const je=A.size[1]>0?j[1]/A.size[1]:1;Ce.fontSizePx=A.fontSize*je}}F.flip=[v!==A.flip[0],b!==A.flip[1]]}}var iP=ie(t=>t.with(T,xt)),p0=ie(t=>t.with(T,lc)),aP=ie(t=>t.with(T,me,Ve)),lP="z",cP=Se({phase:"update"},t=>{fe(t,Uy,e=>{const n=Bt(e);ee(e,n,T,{tag:"selection-box",position:[0,0],size:[0,0],rotateZ:0,rank:lP}),ee(e,n,lc,{})}),fe(t,Wy,(e,{bounds:n,deselectOthers:r})=>{const o=p0.current(e);if(o.length===0){console.warn("Can't update selection box: not found");return}const s=o[0],i=T.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=M2(e,n,aP.current(e));if(r)for(const h of iP.current(e))!f.includes(h)&&_a(e,h);for(const h of f)Si(e,h)}),fe(t,Hy,e=>{const n=p0.current(e);if(n.length===0){console.warn("Can't remove selection box: not found");return}const r=n[0];st(e,r)})}),mc=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function uP(t={}){return{name:e0,resources:wB.parse(t),components:Object.values(Xy).filter(e=>e instanceof qt),singletons:Object.values(n0).filter(e=>e instanceof vt),blockDefs:[{tag:"selection-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[lc]},{tag:"transform-box",stratum:"overlay",canRotate:!1,canScale:!1,components:[en]},{tag:"transform-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ye]},{tag:"transform-edge",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ye]},{tag:"transform-rotate",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ye]}],systems:[...mc(i0),...mc(r0),...mc(l0),...mc(o0)],keybinds:[{command:$y.name,key:dn.X,mod:!0},{command:Ly.name,key:dn.C,mod:!0},{command:Vy.name,key:dn.V,mod:!0},{command:Qd.name,key:dn.Delete},{command:jy.name,key:dn.A,mod:!0},{command:Dy.name,key:dn.BracketRight},{command:Ry.name,key:dn.BracketLeft}],cursors:yB}}var dP=Object.defineProperty,m0=(t,e)=>{for(var n in e)dP(t,n,{get:e[n],enumerable:!0})},g0={};m0(g0,{ArcArrow:()=>xe,ArrowHandle:()=>er,ArrowTerminal:()=>Ta,ElbowArrow:()=>Pe});var fP="arrows",y0="zzzzz",hP=24,w0=50,hf=4,pP=4,pf=24,Mo=24,v0=40,Qn={Idle:"idle",Pointing:"pointing",Dragging:"dragging"},Ci={None:"none",Idle:"idle"},$e={Start:"start",Middle:"middle",End:"end"},De={None:"none",V:"v",Delta:"delta",Circle:"circle",Diamond:"diamond"},gs={Arc:"arc",Elbow:"elbow"},gc=0,yc=1,wc=2,vc=3,kc=4,bc=5,mf=6,mP={value:C.tuple(C.float64(),7).default([0,0,.5,.5,1,1,hf]),startArrowHead:C.enum(De).default(De.None),endArrowHead:C.enum(De).default(De.V),trimStart:C.float64().default(0),trimEnd:C.float64().default(1)},gP=class extends qt{constructor(){super({name:"arcArrow",sync:"document"},mP)}getA(t,e){const{value:n}=this.read(t,e);return[n[gc],n[yc]]}getB(t,e){const{value:n}=this.read(t,e);return[n[wc],n[vc]]}getC(t,e){const{value:n}=this.read(t,e);return[n[kc],n[bc]]}getThickness(t,e){const{value:n}=this.read(t,e);return n[mf]}setA(t,e,n){const{value:r}=this.write(t,e);r[gc]=n[0],r[yc]=n[1]}setB(t,e,n){const{value:r}=this.write(t,e);r[wc]=n[0],r[vc]=n[1]}setC(t,e,n){const{value:r}=this.write(t,e);r[kc]=n[0],r[bc]=n[1]}setThickness(t,e,n){const{value:r}=this.write(t,e);r[mf]=n}getWorldArc(t,e){const{value:n}=this.read(t,e),r=T.uvToWorld(t,e,[n[gc],n[yc]]),o=T.uvToWorld(t,e,[n[wc],n[vc]]),s=T.uvToWorld(t,e,[n[kc],n[bc]]);return[r[0],r[1],o[0],o[1],s[0],s[1],n[mf]]}getWorldPoints(t,e){const{value:n}=this.read(t,e);return{a:T.uvToWorld(t,e,[n[gc],n[yc]]),b:T.uvToWorld(t,e,[n[wc],n[vc]]),c:T.uvToWorld(t,e,[n[kc],n[bc]])}}isCurved(t,e){const{value:n}=this.read(t,e);return!Re.isCollinear(n)}directionAt(t,e,n){const r=this.getWorldArc(t,e);return Re.directionAt(r,n)}pointAt(t,e,n){const r=this.getWorldArc(t,e);return Re.parametricToPoint(r,n)}length(t,e){const n=this.getWorldArc(t,e);return Re.length(n)}containsPoint(t,e,n){const r=this.getWorldArc(t,e);return Re.containsPoint(r,n)}},xe=new gP,er=Qe({name:"arrowHandle"},{kind:C.enum($e).default($e.Start),arrowEntity:C.ref()}),Ta=Qe({name:"arrowTerminal"},{blockEntity:C.ref(),terminalIndex:C.uint8().default(0)}),yP={points:C.buffer(C.float64()).size(pf*2),pointCount:C.uint8().default(0),thickness:C.float32().default(hf),startArrowHead:C.enum(De).default(De.None),endArrowHead:C.enum(De).default(De.V),trimStart:C.float64().default(0),trimEnd:C.float64().default(1)},wP=class extends qt{constructor(){super({name:"elbowArrow",sync:"document"},yP)}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>pf)throw new Error(`ElbowArrow points exceed capacity of ${pf}`);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 T.uvToWorld(t,e,n)}getEndWorld(t,e){const{pointCount:n}=this.read(t,e),r=this.getPoint(t,e,n-1);return T.uvToWorld(t,e,r)}getWorldPoints(t,e){return this.getPoints(t,e).map(r=>T.uvToWorld(t,e,r))}getThickness(t,e){const{thickness:n}=this.read(t,e);return n}},Pe=new wP,k0={};m0(k0,{ArrowDrawState:()=>gf,ArrowTransformState:()=>b0});var gf=Eo("arrowDrawState",{state:C.string().max(16).default(Qn.Idle),activeArrow:C.ref(),kind:C.enum(gs).default(gs.Elbow),pointingStartClient:C.tuple(C.int32(),2).default([0,0]),pointingStartWorld:C.tuple(C.float64(),2).default([0,0])}),b0=Eo("arrowTransformState",{state:C.string().max(16).default(Ci.None),activeArrow:C.ref()}),S0=pe("arrows-add-arrow"),E0=pe("arrows-remove-arrow"),C0=pe("arrows-add-or-update-transform-handles"),_0=pe("arrows-remove-transform-handles"),x0=pe("arrows-hide-transform-handles"),T0=pe("arrows-show-transform-handles"),vP=zr({guards:{isThresholdReached:({context:t,event:e})=>$.distance(t.pointingStartClient,e.screenPosition)>=pP},actions:{setPointingStart:Ze({pointingStartClient:({event:t})=>[t.screenPosition[0],t.screenPosition[1]],pointingStartWorld:({event:t})=>[t.worldPosition[0],t.worldPosition[1]]}),resetContext:Ze({pointingStartClient:()=>[0,0],pointingStartWorld:()=>[0,0],activeArrow:()=>null}),addArrow:Ze({activeArrow:({context:t,event:e})=>{const n=t.kind,r=t.pointingStartWorld,o=Bt(e.ctx);return S0.spawn(e.ctx,{entityId:o,position:r,kind:n}),o}}),removeArrow:Ze({activeArrow:({context:t,event:e})=>(t.activeArrow&&E0.spawn(e.ctx,{entityId:t.activeArrow}),null)}),exitArrowControl:({event:t})=>{const e=ct.write(t.ctx);e.leftMouseTool="select";const n=Pn.write(t.ctx);n.cursorKind="select"},deselectAll:({event:t})=>{bi.spawn(t.ctx)}}}).createMachine({id:"arrowDraw",initial:Qn.Idle,context:{activeArrow:null,kind:gs.Elbow,pointingStartClient:[0,0],pointingStartWorld:[0,0]},states:{[Qn.Idle]:{entry:"resetContext",on:{pointerDown:[{actions:"deselectAll",target:Qn.Pointing}]}},[Qn.Pointing]:{entry:"setPointingStart",on:{pointerMove:{guard:"isThresholdReached",target:Qn.Dragging},pointerUp:{target:Qn.Idle},cancel:{target:Qn.Idle}}},[Qn.Dragging]:{entry:"addArrow",exit:"exitArrowControl",on:{pointerUp:{target:Qn.Idle},cancel:{actions:"removeArrow",target:Qn.Idle}}}}}),kP=Se({phase:"capture",priority:100},t=>{const e=ct.getButtons(t,"arc-arrow","elbow-arrow");if(e.length===0)return;const n=jr(t,e);if(n.length===0)return;const r=ct.read(t).leftMouseTool,o=gf.write(t);o.kind=r==="elbow-arrow"?gs.Elbow:gs.Arc,gf.run(t,vP,n)}),yf=ie(t=>t.with(T).tracking(xt)),bP=zr({guards:{selectingSingleArrow:({event:t})=>{if(!("selectedEntities"in t)||t.selectedEntities.length!==1)return!1;const e=t.selectedEntities[0];return R(t.ctx,e,xe)||R(t.ctx,e,Pe)}},actions:{setActiveArrow:Ze({activeArrow:({event:t})=>!("selectedEntities"in t)||t.selectedEntities.length===0?null:t.selectedEntities[0]}),addOrUpdateTransformHandles:({context:t,event:e})=>{t.activeArrow&&C0.spawn(e.ctx,{arrowEntityId:t.activeArrow})},removeTransformHandles:({event:t})=>{_0.spawn(t.ctx,{})},hideTransformHandles:({event:t})=>{x0.spawn(t.ctx,{})},showTransformHandles:({event:t})=>{T0.spawn(t.ctx,{})}}}).createMachine({id:"arrowTransform",initial:Ci.None,context:{activeArrow:null},states:{[Ci.None]:{entry:"removeTransformHandles",on:{selectionChanged:[{guard:"selectingSingleArrow",actions:"setActiveArrow",target:Ci.Idle}]}},[Ci.Idle]:{entry:"addOrUpdateTransformHandles",on:{selectionChanged:[{guard:rs("selectingSingleArrow"),target:Ci.None},{actions:["setActiveArrow","addOrUpdateTransformHandles"]}],pointerDown:{actions:"hideTransformHandles"},pointerUp:{actions:"showTransformHandles"}}}}}),SP=Se({phase:"capture",priority:99},t=>{const e=EP(t);e.length!==0&&b0.run(t,bP,e)});function EP(t){const e=[],n=yf.added(t),r=yf.removed(t);if(n.length>0||r.length>0){const i=[...yf.current(t)];e.push({type:"selectionChanged",ctx:t,selectedEntities:i})}const o=ct.getButtons(t,"select"),s=jr(t,o);return e.push(...s),e}var CP=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 _P(t,e,n,r,o,s,i){return new xP(t,e,n,s,i).calculate(r,o)}var xP=class{constructor(t,e,n,r,o){this.ctx=t,this.padding=r,this.rotation=o;const s=$.midPoint(e,n);this.toLocal=ze.fromTranslation(-s[0],-s[1]),ze.rotate(this.toLocal,-o),this.toWorld=ze.fromRotation(o),ze.translate(this.toWorld,s[0],s[1]),this.localStart=this.transformToLocal(e),this.localEnd=this.transformToLocal(n)}transformToLocal(t){const e=$.clone(t);return ze.transformPoint(this.toLocal,e),e}transformToWorld(t){const e=$.clone(t);return ze.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=Ma(kt.origin(n),kt.origin(r)):o=this.routeBlockToBlock(t,e,n,r)}else t&&!e?this.isPointInsideBlockMargin(this.localEnd,t)?o=Ma(kt.origin(n),this.localEnd):o=this.routeBlockToPoint(t,n,this.localEnd):!t&&e?this.isPointInsideBlockMargin(this.localStart,e)?o=Ma(this.localStart,kt.origin(r)):o=this.routeBlockToPoint(e,r,this.localStart).reverse():o=Ma(kt.origin(n),this.localEnd);for(let s=0;s<o.length;s++)o[s]=this.transformToWorld(o[s]);return o}getBlockAabb(t){const e=T.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 pt.getAabb(s,e.size,o,i),i}isPointInsideBlockMargin(t,e){const n=this.getBlockAabb(e);return ne.pad(n,this.padding),ne.containsPoint(n,t)}routeBlockToBlock(t,e,n,r){const o=this.getBlockAabb(t),s=this.getBlockAabb(e);ne.pad(o,this.padding),ne.pad(s,this.padding),IP(o,s);const i=NP(o,s),a=Sc(n,i),l=Sc(r,i),c=kt.origin(n),u=kt.origin(r);if(a===null||l===null)return console.warn("[routeBlockToBlock] Failed to add start or end node to graph"),[c,u];const f=N0(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),TP(h),M0(h),MP(h),h}routeBlockToPoint(t,e,n){const r=kt.origin(e),o=kt.direction(e),s=Ec(r,n);if(o[0]===s[0]&&o[1]===s[1])return Ma(r,n);const i=this.getBlockAabb(t);ne.pad(i,this.padding);const a=kt.fromPoints(n,[-s[0],-s[1]]),l=kt.intersectAabb(a,i);l.length===0&&ne.expand(i,n);const c=ne.corners(i),u=A0(c),f=Sc(a,u),h=Sc(e,u);if(h===null||f===null)return[r,n];const p=N0(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),M0(m),m}calculateRay(t,e,n){let r;return n?r=this.exitClosestSide(t,n).direction:r=Ec(t,e),kt.fromPoints(t,r)}exitClosestSide(t,e){const n=T.read(this.ctx,e),r=T.getCenter(this.ctx,e),o=this.transformToWorld(t),s=$.clone(o),i=$.clone(r);$.sub(i,o),$.scale(i,.01),$.add(s,i);const a=[[0,-1],[1,0],[0,1],[-1,0]],l=a.map(m=>{const g=$.clone(m);return $.rotate(g,this.rotation),g}),c=[];for(let m=0;m<l.length;m++){const g=l[m],y=kt.fromPoints(s,g),w=kt.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=Ec(t,this.localEnd),g=c.find(y=>y.direction[0]===m[0]&&y.direction[1]===m[1]);if(g)return g}return u}};function Ma(t,e){const n=[];n.push(t);const r=e[0]-t[0],o=e[1]-t[1];if(Dt.approxEqual(o,0)||Dt.approxEqual(r,0))return n.push(e),n;const s=Ec(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 TP(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=Dt.approxEqual(r[0],o[0]),i=Dt.approxEqual(r[1],o[1]);(!s||!i)&&e.push(o)}t.length=0,t.push(...e)}function M0(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=Dt.approxEqual(r[0],o[0])&&Dt.approxEqual(o[0],s[0]),a=Dt.approxEqual(r[1],o[1])&&Dt.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 MP(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=AP(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 AP(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])>0?"left":"right"}function IP(t,e){if(!ne.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 A0(t){const e=t.map((n,r)=>({id:r,connections:[],distances:{},coords:n}));return I0(e,0),I0(e,1),e}function I0(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 NP(t,e){if(!ne.intersects(t,e))return[];const n=[],r=ne.corners(t),o=ne.corners(e);for(const c of r)ne.containsPoint(e,c,!1)||n.push(c);for(const c of o)ne.containsPoint(t,c,!1)||n.push(c);const s=ne.clone(t);ne.intersection(s,e);const i=ne.corners(s);for(const c of i)ne.containsPoint(t,c,!1)||ne.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 A0(a)}function Sc(t,e){const n=kt.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=kt.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 N0(t,e,n){const r={},o={},s=new CP;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 Ec(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 B0(t,e){if(t.length===0)return null;let n=t[0],r=$.distanceSq(t[0],e);for(let o=1;o<t.length;o++){const s=$.distanceSq(t[o],e);s<r&&(r=s,n=t[o])}return n}function BP(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 PP(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 P0=20,OP=ie(t=>t.tracking(xe,Ke)),DP=ie(t=>t.tracking(Pe,Ke)),RP=Se({phase:"update",priority:-10},t=>{for(const e of OP.addedOrChanged(t))zP(t,e);for(const e of DP.addedOrChanged(t))$P(t,e)});function zP(t,e){R(t,e,Me)||ee(t,e,Me,{});const n=xe.read(t,e),r=Re.clone(n.value);r[6]=Math.max(r[6],P0),Me.clear(t,e),Me.addArc(t,e,r),LP(t,e)}function $P(t,e){R(t,e,Me)||ee(t,e,Me,{});const n=Pe.read(t,e),r=Math.max(n.thickness,P0),o=Pe.getPoints(t,e),s=Me.write(t,e),i=Math.min(o.length-1,ui);s.capsuleCount=i,s.arcCount=0;for(let a=0;a<i;a++){const l=o[a],c=o[a+1],u=ht.create(l[0],l[1],c[0],c[1],r/2);Me.setCapsuleAt(t,e,a,u)}VP(t,e)}function LP(t,e){const n=Ke.read(t,e),r=xe.getWorldArc(t,e),{a:o,c:s}=xe.getWorldPoints(t,e);let i=O0(t,n.startBlock,r,o),a=O0(t,n.endBlock,r,s);1-a-i<.1&&(i=0,a=0);const l=xe.read(t,e);if(!Dt.approxEqual(l.trimStart,i)||!Dt.approxEqual(l.trimEnd,a)){const u=xe.write(t,e);u.trimStart=i,u.trimEnd=a}const c=Me.read(t,e);for(let u=0;u<c.arcCount;u++){const f=Me.getArcAt(t,e,u);Re.trim(f,i,1-a),Me.setArcAt(t,e,u,f)}}function O0(t,e,n,r){if(!e)return 0;const o=T.getCorners(t,e),s=Re.intersectRect(n,o);if(s.length===0)return 0;const i=B0(s,r);return i?Re.pointToParametric(n,i)??0:0}function VP(t,e){const n=Ke.read(t,e),r=Pe.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=D0(t,n.startBlock,s,a),u=D0(t,n.endBlock,i,l),f=Pe.read(t,e);if(!Dt.approxEqual(f.trimStart,c)||!Dt.approxEqual(f.trimEnd,u)){const g=Pe.write(t,e);g.trimStart=c,g.trimEnd=u}const h=Me.getCapsuleAt(t,e,0);ht.trim(h,c,1),Me.setCapsuleAt(t,e,0,h);const p=o-1,m=Me.getCapsuleAt(t,e,p);ht.trim(m,0,1-u),Me.setCapsuleAt(t,e,p,m)}function D0(t,e,n,r){if(!e)return 0;const o=T.getCorners(t,e),s=[];for(let f=0;f<4;f++){const h=o[f],p=o[(f+1)%4],m=FP(n,r,h,p);m&&s.push(m)}if(s.length===0)return 0;const i=B0(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 FP(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 Cc=ie(t=>t.with(er,T)),jP=ie(t=>t.with(me,Ve).tracking(T)),R0=ie(t=>t.with(Ta,T)),UP=Se({phase:"update"},t=>{fe(t,S0,(e,{entityId:n,position:r,kind:o})=>{HP(e,n,r,o)}),fe(t,E0,(e,{entityId:n})=>{ZP(e,n)}),fe(t,C0,(e,{arrowEntityId:n})=>{wf(e,n)}),fe(t,_0,e=>{GP(e)}),fe(t,x0,e=>{vf(e)}),fe(t,T0,e=>{XP(e)}),fe(t,Ea,(e,{entityId:n,position:r})=>{KP(e,n,r)}),WP(t)});function WP(t){const e=jP.addedOrChangedOrRemoved(t);if(e.length===0)return;const n=new Set;for(const r of e){const o=dr(t,r,Ke,"startBlock",!1);for(const i of o)n.has(i)||(n.add(i),z0(t,i));const s=dr(t,r,Ke,"endBlock",!1);for(const i of s)n.has(i)||(n.add(i),z0(t,i))}}function z0(t,e){const n=Ke.read(t,e);if(R(t,e,xe)){const{a:r,c:o}=xe.getWorldPoints(t,e);let s=r,i=o;n.startBlock!==null&&(s=T.uvToWorld(t,n.startBlock,n.startBlockUv),kf(t,e,$e.Start,s)),n.endBlock!==null&&(i=T.uvToWorld(t,n.endBlock,n.endBlockUv),kf(t,e,$e.End,i))}else if(R(t,e,Pe)){if(n.startBlock!==null){const r=T.uvToWorld(t,n.startBlock,n.startBlockUv);bf(t,e,$e.Start,r)}if(n.endBlock!==null){const r=T.uvToWorld(t,n.endBlock,n.endBlockUv);bf(t,e,$e.End,r)}}}function HP(t,e,n,r){const o=hf,s=r===gs.Elbow?"elbow-arrow":"arc-arrow",a=us.getAll(t).find(h=>R(t,h,me)&&Sf(t,h))??null;let l=n,c=[0,0];if(a!==null){const h=Ef(t,a,n);h!==null?(l=h.position,c=h.uv):(l=T.uvToWorld(t,a,[.5,.5]),c=[.5,.5])}ee(t,e,T,{tag:s,rank:Zn.genNext(t),position:l,size:[o,o]}),ee(t,e,me,{id:crypto.randomUUID()}),r===gs.Arc?ee(t,e,xe,{value:[0,0,.5,.5,1,1,o],startArrowHead:De.None,endArrowHead:De.V}):ee(t,e,Pe,{points:[0,0,.5,0,.5,1,1,1],pointCount:4,thickness:o,startArrowHead:De.None,endArrowHead:De.V}),ee(t,e,Ke,{startBlock:a,startBlockUv:c}),Si(t,e);const f=wf(t,e).find(h=>er.read(t,h).kind===$e.End);if(f){const h=T.read(t,f),p=Xn.write(t);p.state=_e.Dragging,p.draggedEntity=f,p.dragStart=l,p.draggedEntityStart=[h.position[0],h.position[1]],vf(t)}}function ZP(t,e){st(t,e)}function KP(t,e,n){R(t,e,xe)?YP(t,e):R(t,e,Pe)?qP(t,e):R(t,e,er)&&JP(t,e,n)}function YP(t,e){const n=Ke.read(t,e);if(n.startBlock!==null){const{a:r}=xe.getWorldPoints(t,e);Aa(t,e,$e.Start,r)}if(n.endBlock!==null){const{c:r}=xe.getWorldPoints(t,e);Aa(t,e,$e.End,r)}}function qP(t,e){const n=Ke.read(t,e);if(n.startBlock!==null){const r=Pe.getStartWorld(t,e);Aa(t,e,$e.Start,r)}if(n.endBlock!==null){const r=Pe.getEndWorld(t,e);Aa(t,e,$e.End,r)}}function JP(t,e,n){const r=er.read(t,e),o=r.arrowEntity;if(!o)return;const s=T.read(t,e);let i=[n[0]+s.size[0]/2,n[1]+s.size[1]/2];if(r.kind!==$e.Middle){const a=rO(t,o,r.kind,i);a!==null&&(i=a)}R(t,o,xe)?kf(t,o,r.kind,i):R(t,o,Pe)&&bf(t,o,r.kind,i),r.kind!==$e.Middle&&Aa(t,o,r.kind,i)}function wf(t,e){const n=hP,r=[$e.Start,$e.End];R(t,e,xe)&&r.push($e.Middle);const o=Array.from(Cc.current(t)),s=new Map;for(const l of o){const c=er.read(t,l);s.set(c.kind,l)}const i=new Set;for(const l of r){const c=QP(t,e,l),u=c[0]-n/2,f=c[1]-n/2;let h=s.get(l);h||(h=Bt(t),ee(t,h,er),ee(t,h,T),ee(t,h,So),ee(t,h,Ye,{kind:"arrow"}));const p=er.write(t,h);p.kind=l,p.arrowEntity=e;const m=T.write(t,h);m.tag="arrow-handle",m.rank=y0,m.position=[u,f],m.size=[n,n];const g=So.write(t,h);g.startPosition=[u,f],g.startSize=[n,n],i.add(h)}for(const l of o)i.has(l)||st(t,l);const a=Xn.read(t);return a.state===_e.Dragging&&a.draggedEntity!==null&&R(t,a.draggedEntity,er)&&vf(t),Array.from(i)}function GP(t){for(const e of Cc.current(t))st(t,e);_c(t)}function vf(t){for(const e of Cc.current(t))if(!R(t,e,lt))ee(t,e,lt,{value:0});else{const n=lt.write(t,e);n.value=0}}function XP(t){const e=Cc.current(t);for(const n of e)R(t,n,lt)&&mn(t,n,lt);if(e.length>0){const n=er.read(t,e[0]);n.arrowEntity&&wf(t,n.arrowEntity)}_c(t)}function QP(t,e,n){if(R(t,e,xe)){const{a:r,b:o,c:s}=xe.getWorldPoints(t,e);switch(n){case $e.Start:return r;case $e.Middle:return o;case $e.End:return s}}if(R(t,e,Pe))switch(n){case $e.Start:return Pe.getStartWorld(t,e);case $e.End:return Pe.getEndWorld(t,e)}return console.warn("Arrow entity has no recognized arrow component"),[0,0]}function kf(t,e,n,r){const{a:o,b:s,c:i}=xe.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:v}=BP(u,r,f);l=PP(s,w,.5*v,f)}const h=T.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],xe.setA(t,e,T.worldToUv(t,e,a)),xe.setB(t,e,T.worldToUv(t,e,l)),xe.setC(t,e,T.worldToUv(t,e,c))}function bf(t,e,n,r){const o=Ke.read(t,e);let s,i;n===$e.Start?(s=r,o.endBlock!==null?i=T.uvToWorld(t,o.endBlock,o.endBlockUv):i=Pe.getEndWorld(t,e)):(o.startBlock!==null?s=T.uvToWorld(t,o.startBlock,o.startBlockUv):s=Pe.getStartWorld(t,e),i=r);const l=T.read(t,e).rotateZ||0,c=_P(t,s,i,o.startBlock,o.endBlock,w0,l),u=T.write(t,e),f=[0,0],h=[1,1];pt.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=>T.worldToUv(t,e,m));Pe.setPoints(t,e,p)}function Aa(t,e,n,r){let s=us.getAll(t).find(l=>l!==e&&R(t,l,me)&&!R(t,l,Ke)&&Sf(t,l))??null;const i=Ke.write(t,e);if(s!==null){const l=n===$e.Start?i.endBlock:i.startBlock;s===l&&(s=null)}s!==null?nO(t,s):_c(t);let a=[0,0];if(s!==null){const l=Ef(t,s,r,v0);l!==null?a=l.uv:a=T.worldToUv(t,s,r)}n===$e.Start?(i.startBlock=s,i.startBlockUv=a):(i.endBlock=s,i.endBlockUv=a),eO(t,e)}function eO(t,e){const n=Ke.read(t,e);let r=null;for(const s of[n.startBlock,n.endBlock]){if(s===null)continue;const i=T.read(t,s).rank;(r===null||i>r)&&(r=i)}const o=T.read(t,e).rank;if(r!==null&&o<r){const s=T.write(t,e);s.rank=Rl(r,null)}}function Sf(t,e){const n=T.read(t,e).tag;return Xt(t,n).connectors.enabled}function tO(t){const e=R0.current(t);return e.length===0?null:Ta.read(t,e[0]).blockEntity}function nO(t,e){if(tO(t)===e)return;_c(t);const n=T.read(t,e).tag,r=Xt(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=T.uvToWorld(t,e,i),l=Bt(t);ee(t,l,Ta,{blockEntity:e,terminalIndex:s}),ee(t,l,T,{tag:"arrow-terminal",rank:y0,position:[a[0]-Mo/2,a[1]-Mo/2],size:[Mo,Mo]}),ee(t,l,So,{startPosition:[a[0]-Mo/2,a[1]-Mo/2],startSize:[Mo,Mo]})}}function _c(t){for(const e of R0.current(t))st(t,e)}function Ef(t,e,n,r){const o=T.read(t,e).tag,s=Xt(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=T.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 rO(t,e,n,r){const s=us.getAll(t).find(c=>c!==e&&R(t,c,me)&&!R(t,c,Ke)&&Sf(t,c))??null;if(s===null)return null;const i=Ke.read(t,e),a=n===$e.Start?i.endBlock:i.startBlock;if(s===a)return null;const l=Ef(t,s,r,v0);return l===null?null:l.position}function oO(t={}){return{name:fP,components:Object.values(g0).filter(e=>e instanceof qt),singletons:Object.values(k0).filter(e=>e instanceof vt),blockDefs:[{tag:"arc-arrow",resizeMode:"groupOnly",components:[xe,Ke,In],connectors:{enabled:!1}},{tag:"elbow-arrow",resizeMode:"groupOnly",components:[Pe,Ke,In],connectors:{enabled:!1}},{tag:"arrow-handle",stratum:"overlay",canRotate:!1,canScale:!1,components:[er],connectors:{enabled:!1}},{tag:"arrow-terminal",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ta],connectors:{enabled:!1}}],systems:[kP,SP,UP,RP],resources:{elbowArrowPadding:t.elbowArrowPadding??w0}}}const Cf=[{kind:De.None,label:"None",gap:0,svg:""},{kind:De.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:De.Delta,label:"Triangle",gap:20,svg:'<polygon points="-1,0 -12,-7 -12,7" fill="currentColor" />'},{kind:De.Circle,label:"Circle",gap:0,svg:'<circle cx="-6" cy="0" r="6" fill="currentColor" />'},{kind:De.Diamond,label:"Diamond",gap:0,svg:'<polygon points="0,0 -7,-6 -14,0 -7,6" fill="currentColor" />'}];function _i(t){return Cf.find(e=>e.kind===t)}const $0=Symbol.for("__woven_canvas_dropdown_active__"),L0=Symbol.for("__woven_canvas_dropdown_level__"),V0=Symbol.for("__woven_canvas_floating_menu__"),_f=Symbol.for("__woven_canvas_toolbar__"),F0=Symbol.for("__woven_canvas_tooltip__"),Rn=Symbol.for("__woven_canvas__");function Tt(t,e){const n=d.inject(Rn);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();R(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 sO={key:0},iO=["x1","y1","x2","y2","stroke","stroke-width"],aO=["x1","y1","x2","y2","stroke","stroke-width"],lO=["points","fill"],cO=["cx","cy","r","fill"],uO=["points","fill"],dO=15,fO=2,Kr=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/fO)**.33,c=dO*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",sO,[t.kind===d.unref(De).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,iO),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,aO)],64)):t.kind===d.unref(De).Delta&&o.value?(d.openBlock(),d.createElementBlock("polygon",{key:1,points:o.value,fill:t.color},null,8,lO)):t.kind===d.unref(De).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,cO)):t.kind===d.unref(De).Diamond&&i.value?(d.openBlock(),d.createElementBlock("polygon",{key:3,points:i.value,fill:t.color},null,8,uO)):d.createCommentVNode("",!0)])):d.createCommentVNode("",!0)}}),hO={class:"arrow-svg",preserveAspectRatio:"none"},pO=["d","stroke","stroke-width"],mO=["x1","y1","x2","y2","stroke","stroke-width"],gO=["d"],yO=["x1","y1","x2","y2"],wO=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=Tt(e.entityId,In),i=Tt(e.entityId,xe);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"),k=s.value.blue.toString(16).padStart(2,"0");return`#${b}${S}${k}`}),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=Re.create(b[0],b[1],b[2],b[3],b[4],b[5],b[6]);return!Re.isCollinear(S)}),p=d.computed(()=>{if(!i.value)return null;const b=i.value.value,S=r.value,k=o.value;return Re.create(b[0]*S,b[1]*k,b[2]*S,b[3]*k,b[4]*S,b[5]*k,b[6])}),m=d.computed(()=>!p.value||!h.value?null:Re.compute(p.value)),g=d.computed(()=>{var F,Y,ce,se;if(!i.value||!p.value)return null;const b=p.value,S=i.value.startArrowHead,k=i.value.endArrowHead,E=Re.length(b);let _=i.value.trimStart;if((F=e.connector)!=null&&F.startBlock&&S!=="none"){const j=((Y=_i(S))==null?void 0:Y.gap)??0,X=E>0?j/E:0;_+=X}let M=i.value.trimEnd;if((ce=e.connector)!=null&&ce.endBlock&&k!=="none"){const j=((se=_i(k))==null?void 0:se.gap)??0,X=E>0?j/E:0;M+=X}const I=1-M,P=Re.parametricToPoint(b,_),V=Re.parametricToPoint(b,I),Z=v(Re.directionAt(b,_)),A=Re.directionAt(b,I);return{start:P,end:V,startDir:Z,endDir:A,tStart:_,tEnd:I,startHead:S,endHead:k}}),y=d.computed(()=>{if(!g.value||!m.value||!h.value)return"";const{start:b,end:S,tStart:k,tEnd:E}=g.value,{radius:_,clockwise:M,arcAngle:I}=m.value,V=I*(E-k)>Math.PI?1:0,Z=M?0:1;return`M ${b[0]} ${b[1]} A ${_} ${_} 0 ${V} ${Z} ${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 v(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",hO,[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,pO)):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,mO)):d.createCommentVNode("",!0),g.value?(d.openBlock(),d.createElementBlock(d.Fragment,{key:2},[g.value.startHead!=="none"?(d.openBlock(),d.createBlock(Kr,{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(Kr,{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,gO)):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,yO)):d.createCommentVNode("",!0),g.value.startHead!=="none"?(d.openBlock(),d.createBlock(Kr,{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(Kr,{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))}}),ys=(t,e)=>{const n=t.__vccOpts||t;for(const[r,o]of e)n[r]=o;return n},j0=ys(wO,[["__scopeId","data-v-bcf5b4f3"]]),vO={},kO={class:"wov-arrow-handle"};function bO(t,e){return d.openBlock(),d.createElementBlock("div",kO,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-handle-inner"},null,-1)])])}const U0=ys(vO,[["render",bO]]),SO={},EO={class:"wov-arrow-terminal"};function CO(t,e){return d.openBlock(),d.createElementBlock("div",EO,[...e[0]||(e[0]=[d.createElementVNode("div",{class:"wov-arrow-terminal-ring"},[d.createElementVNode("div",{class:"wov-arrow-terminal-fill"})],-1)])])}const W0=ys(SO,[["render",CO]]),_O={class:"arrow-svg",preserveAspectRatio:"none"},xO=["x1","y1","x2","y2"],TO=["x1","y1","x2","y2","stroke","stroke-width"],MO=["x1","y1","x2","y2"],H0=ys(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=Tt(e.entityId,In),i=Tt(e.entityId,Pe),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,v=[];for(let b=0;b<g.pointCount;b++){const S=g.points[b*2]*y,k=g.points[b*2+1]*w;v.push([S,k])}return v}),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,P,V,Z;if(!i.value||h.value.length<2)return null;const g=i.value,y=[...h.value.map(A=>[...A])],w=g.startArrowHead,v=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 k=g.trimStart;if((I=e.connector)!=null&&I.startBlock&&w!=="none"){const A=Math.hypot(b[0],b[1]),F=((P=_i(w))==null?void 0:P.gap)??0,Y=A>0?F/A:0;k+=Y}let E=g.trimEnd;if((V=e.connector)!=null&&V.endBlock&&v!=="none"){const A=Math.hypot(S[0],S[1]),F=((Z=_i(v))==null?void 0:Z.gap)??0,Y=A>0?F/A:0;E+=Y}y[0]=[y[0][0]+(y[1][0]-y[0][0])*k,y[0][1]+(y[1][1]-y[0][1])*k];const _=y.length-1;y[_]=[y[_-1][0]+(y[_][0]-y[_-1][0])*(1-E),y[_-1][1]+(y[_][1]-y[_-1][1])*(1-E)];const M=[];for(let A=0;A<y.length-1;A++)M.push({start:y[A],end:y[A+1]});return $.scale(b,-1),{points:y,lines:M,startPos:y[0],endPos:y[y.length-1],startDir:b,endDir:S,startHead:w,endHead:v}});return(g,y)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"containerRef",ref:n,class:"wov-elbow-arrow"},[(d.openBlock(),d.createElementBlock("svg",_O,[a.value&&p.value.length>0?(d.openBlock(!0),d.createElementBlock(d.Fragment,{key:0},d.renderList(p.value,(w,v)=>(d.openBlock(),d.createElementBlock("line",{key:"bg-"+v,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,xO))),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,v)=>(d.openBlock(),d.createElementBlock("line",{key:v,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,TO))),128)),m.value.startHead!=="none"?(d.openBlock(),d.createBlock(Kr,{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(Kr,{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,v)=>(d.openBlock(),d.createElementBlock("line",{key:"hl-"+v,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,MO))),128)),m.value.startHead!=="none"?(d.openBlock(),d.createBlock(Kr,{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(Kr,{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 AO=Object.defineProperty,xf=(t,e)=>{for(var n in e)AO(t,n,{get:e[n],enumerable:!0})},Z0=pe("start-eraser-stroke"),K0=pe("add-eraser-stroke-point"),Y0=pe("complete-eraser-stroke"),q0=pe("cancel-eraser-stroke"),J0={};xf(J0,{Erased:()=>ws,EraserStroke:()=>Ia});var ws=Qe({name:"erased"},{eraserStrokeId:C.ref()}),xi=8,IO="eraser",vr=20,Ia=Qe({name:"eraserStroke"},{points:C.buffer(C.float32()).size(vr*2),pointCount:C.uint32().default(0),firstPointIndex:C.uint32().default(0),radius:C.float32().default(8)}),G0={};xf(G0,{EraserStateSingleton:()=>Tf});var vs={Idle:"idle",Erasing:"erasing"},Tf=Eo("eraserState",{state:C.string().max(16).default(vs.Idle),activeStroke:C.ref(),lastWorldPosition:C.tuple(C.float64(),2).default([0,0])}),X0={};xf(X0,{captureEraserSystem:()=>BO,updateEraserSystem:()=>DO});var NO=zr({guards:{},actions:{startStroke:({event:t})=>{Z0.spawn(t.ctx,{worldPosition:t.worldPosition})},addPoint:Ze({lastWorldPosition:({event:t,context:e})=>e.activeStroke?(K0.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition}),[t.worldPosition[0],t.worldPosition[1]]):e.lastWorldPosition}),completeStroke:({event:t,context:e})=>{e.activeStroke&&Y0.spawn(t.ctx,{strokeId:e.activeStroke})},cancelStroke:({event:t,context:e})=>{e.activeStroke&&q0.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:Ze({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"eraser",initial:vs.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[vs.Idle]:{entry:["resetContext"],on:{pointerDown:{target:vs.Erasing,actions:["startStroke"]}}},[vs.Erasing]:{on:{pointerMove:{actions:["addPoint"]},frame:{actions:["addPoint"]},pointerUp:{target:vs.Idle,actions:["completeStroke"]},cancel:{target:vs.Idle,actions:["cancelStroke"]}}}}}),BO=Se({phase:"capture",priority:100},t=>{const e=ct.getButtons(t,"eraser"),n=jr(t,e,{includeFrameEvent:!0});n.length!==0&&Tf.run(t,NO,n)}),PO=ie(t=>t.with(T,me,Ve)),OO=ie(t=>t.with(ws)),DO=Se({phase:"update"},t=>{fe(t,Z0,(e,{worldPosition:n})=>{RO(e,n)}),fe(t,K0,(e,{strokeId:n,worldPosition:r})=>{zO(e,n,r)}),fe(t,Y0,(e,{strokeId:n})=>{VO(e,n)}),fe(t,q0,(e,{strokeId:n})=>{FO(e,n)})});function RO(t,e){const n=Bt(t);ee(t,n,T,{tag:"eraser",rank:Zn.genNext(t),position:[e[0]-xi,e[1]-xi],size:[xi*2,xi*2]}),ee(t,n,Ia,{points:e,pointCount:1,firstPointIndex:0,radius:xi});const r=Tf.write(t);r.activeStroke=n,r.lastWorldPosition=e}function zO(t,e,n){const r=Ia.write(t,e),o=r.pointCount,s=(o-1)%vr*2,i=r.points[s],a=r.points[s+1],l=o%vr*2;if(r.points[l]=n[0],r.points[l+1]=n[1],r.pointCount++,r.pointCount>vr&&(r.firstPointIndex=(r.pointCount-vr)%vr),!Ve.containsPoint(t,e,n)){Ve.expandByPoint(t,e,n);const{value:g}=Ve.read(t,e),y=T.write(t,e);$.set(y.position,ne.left(g),ne.top(g)),$.set(y.size,ne.width(g),ne.height(g))}const c=n[0]-i,u=n[1]-a;if(c*c+u*u<1)return;const h=ht.create(i,a,n[0],n[1],xi),p=$O(t,PO.current(t)),m=I2(t,h,p);for(const g of m)LO(t,g,e)}function*$O(t,e){for(const n of e)R(t,n,ws)||(yield n)}function LO(t,e,n){ee(t,e,ws,{eraserStrokeId:n}),ee(t,e,lt,{value:80})}function VO(t,e){const n=dr(t,e,ws,"eraserStrokeId");for(const r of n)st(t,r);st(t,e)}function FO(t,e){const n=[];for(const r of OO.current(t))ws.read(t,r).eraserStrokeId===e&&n.push(r);for(const r of n)mn(t,r,ws),mn(t,r,lt);st(t,e)}var jO=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e),UO=Hn({tailRadius:Gt().positive().optional(),tailLength:Gt().int().min(1).max(vr).optional()});function WO(t={}){const e=UO.parse(t);return{name:IO,components:Object.values(J0).filter(n=>n instanceof qt),singletons:Object.values(G0).filter(n=>n instanceof vt),blockDefs:[{tag:"eraser-stroke",stratum:"overlay",canRotate:!1,canScale:!1,components:[Ia]}],systems:jO(X0),resources:{tailRadius:e.tailRadius??8,tailLength:e.tailLength??vr}}}const{PI:HO}=Math,Na=HO+1e-4,Q0=.5,ew=[1,1];function tw(t,e,n,r=o=>o){return t*r(.5-e*(.5-n))}const{min:Mf}=Math;function nw(t,e,n){let r=Mf(1,e/n);return Mf(1,t+(Mf(1,1-r)-t)*(r*.275))}function ZO(t){return[-t[0],-t[1]]}function kr(t,e){return[t[0]+e[0],t[1]+e[1]]}function rw(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function Ao(t,e){return[t[0]-e[0],t[1]-e[1]]}function Af(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function Io(t,e){return[t[0]*e,t[1]*e]}function If(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function KO(t,e){return[t[0]/e,t[1]/e]}function ow(t){return[t[1],-t[0]]}function Nf(t,e){let n=e[0];return t[0]=e[1],t[1]=-n,t}function sw(t,e){return t[0]*e[0]+t[1]*e[1]}function YO(t,e){return t[0]===e[0]&&t[1]===e[1]}function qO(t){return Math.hypot(t[0],t[1])}function iw(t,e){let n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function aw(t){return KO(t,qO(t))}function JO(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function Bf(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 lw(t,e,n,r){let o=Math.sin(r),s=Math.cos(r),i=e[0]-n[0],a=e[1]-n[1],l=i*s-a*o,c=i*o+a*s;return t[0]=l+n[0],t[1]=c+n[1],t}function cw(t,e,n){return kr(t,Io(Ao(e,t),n))}function GO(t,e,n,r){let o=n[0]-e[0],s=n[1]-e[1];return t[0]=e[0]+o*r,t[1]=e[1]+s*r,t}function uw(t,e,n){return kr(t,Io(e,n))}const zt=[0,0],No=[0,0],Bo=[0,0];function XO(t,e){let n=uw(t,aw(ow(Ao(t,kr(t,[1,1])))),-e),r=[],o=1/13;for(let s=o;s<=1;s+=o)r.push(Bf(n,t,Na*2*s));return r}function QO(t,e,n){let r=[],o=1/n;for(let s=o;s<=1;s+=o)r.push(Bf(e,t,Na*s));return r}function eD(t,e,n){let r=Ao(e,n),o=Io(r,.5),s=Io(r,.51);return[Ao(t,o),Ao(t,s),kr(t,s),kr(t,o)]}function tD(t,e,n,r){let o=[],s=uw(t,e,n),i=1/r;for(let a=i;a<1;a+=i)o.push(Bf(s,t,Na*3*a));return o}function nD(t,e,n){return[kr(t,Io(e,n)),kr(t,Io(e,n*.99)),Ao(t,Io(e,n*.99)),Ao(t,Io(e,n))]}function dw(t,e,n){return t===!1||t===void 0?0:t===!0?Math.max(e,n):t}function rD(t,e,n){return t.slice(0,10).reduce((r,o)=>{let s=o.pressure;return e&&(s=nw(r,o.distance,n)),(r+s)/2},t[0].pressure)}function oD(t,e={}){let{size:n=16,smoothing:r=.5,thinning:o=.5,simulatePressure:s=!0,easing:i=se=>se,start:a={},end:l={},last:c=!1}=e,{cap:u=!0,easing:f=se=>se*(2-se)}=a,{cap:h=!0,easing:p=se=>--se*se*se+1}=l;if(t.length===0||n<=0)return[];let m=t[t.length-1].runningLength,g=dw(a.taper,n,m),y=dw(l.taper,n,m),w=(n*r)**2,v=[],b=[],S=rD(t,s,n),k=tw(n,o,t[t.length-1].pressure,i),E,_=t[0].vector,M=t[0].point,I=M,P=M,V=I,Z=!1;for(let se=0;se<t.length;se++){let{pressure:j}=t[se],{point:X,vector:he,distance:Te,runningLength:Ce}=t[se],je=se===t.length-1;if(!je&&m-Ce<3)continue;o?(s&&(j=nw(S,Te,n)),k=tw(n,o,j,i)):k=n/2,E===void 0&&(E=k);let ar=Ce<g?f(Ce/g):1,so=m-Ce<y?p((m-Ce)/y):1;k=Math.max(.01,k*Math.min(ar,so));let Ks=(je?t[se]:t[se+1]).vector,Go=je?1:sw(he,Ks),zu=sw(he,_)<0&&!Z,Wi=Go!==null&&Go<0;if(zu||Wi){Nf(zt,_),If(zt,zt,k);for(let Xo=0;Xo<=1;Xo+=.07692307692307693)Af(No,X,zt),lw(No,No,X,Na*Xo),P=[No[0],No[1]],v.push(P),rw(Bo,X,zt),lw(Bo,Bo,X,Na*-Xo),V=[Bo[0],Bo[1]],b.push(V);M=P,I=V,Wi&&(Z=!0);continue}if(Z=!1,je){Nf(zt,he),If(zt,zt,k),v.push(Ao(X,zt)),b.push(kr(X,zt));continue}GO(zt,Ks,he,Go),Nf(zt,zt),If(zt,zt,k),Af(No,X,zt),P=[No[0],No[1]],(se<=1||iw(M,P)>w)&&(v.push(P),M=P),rw(Bo,X,zt),V=[Bo[0],Bo[1]],(se<=1||iw(I,V)>w)&&(b.push(V),I=V),S=j,_=he}let A=[t[0].point[0],t[0].point[1]],F=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:kr(t[0].point,[1,1]),Y=[],ce=[];if(t.length===1){if(!(g||y)||c)return XO(A,E||k)}else{g||y&&t.length===1||(u?Y.push(...QO(A,b[0],13)):Y.push(...eD(A,v[0],b[0])));let se=ow(ZO(t[t.length-1].vector));y||g&&t.length===1?ce.push(F):h?ce.push(...tD(F,se,k,29)):ce.push(...nD(F,se,k))}return v.concat(ce,b.reverse(),Y)}const fw=[0,0];function hw(t){return t!=null&&t>=0}function sD(t,e={}){var h;let{streamline:n=.5,size:r=16,last:o=!1}=e;if(t.length===0)return[];let s=.15+(1-n)*.85,i=Array.isArray(t[0])?t:t.map(({x:p,y:m,pressure:g=Q0})=>[p,m,g]);if(i.length===2){let p=i[1];i=i.slice(0,-1);for(let m=1;m<5;m++)i.push(cw(i[0],p,m/4))}i.length===1&&(i=[...i,[...kr(i[0],ew),...i[0].slice(2)]]);let a=[{point:[i[0][0],i[0][1]],pressure:hw(i[0][2])?i[0][2]:.25,vector:[...ew],distance:0,runningLength:0}],l=!1,c=0,u=a[0],f=i.length-1;for(let p=1;p<i.length;p++){let m=o&&p===f?[i[p][0],i[p][1]]:cw(u.point,i[p],s);if(YO(u.point,m))continue;let g=JO(m,u.point);if(c+=g,p<f&&!l){if(c<r)continue;l=!0}Af(fw,u.point,m),u={point:m,pressure:hw(i[p][2])?i[p][2]:Q0,vector:aw(fw),distance:g,runningLength:c},a.push(u)}return a[0].vector=((h=a[1])==null?void 0:h.vector)||[0,0],a}function Pf(t,e={}){return oD(sD(t,e),e)}const iD={class:"wov-eraser-stroke"},aD={preserveAspectRatio:"none"},lD=["d"],cD="#88888833",pw=d.defineComponent({__name:"Eraser",props:{entityId:{}},setup(t){const e=t,n=Tt(e.entityId,Ia),r=Tt(e.entityId,T),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,vr);for(let S=0;S<m;S++){const k=(l+S)%vr*2;p.push([c[k]-f,c[k+1]-h])}const g=Pf(p,{size:u,start:{taper:66,cap:!0}});if(g.length<3)return"";let y=g[0],w=g[1];const v=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],v[0]).toFixed(2)},${s(w[1],v[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",iD,[(d.openBlock(),d.createElementBlock("svg",aD,[d.createElementVNode("path",{d:o.value,fill:cD},null,8,lD)]))]))}}),uD={class:"wov-image-block"},dD={key:0,class:"wov-image-placeholder"},fD={key:1,class:"wov-image-placeholder wov-image-error"},hD=["src","alt"],pD={key:3,class:"wov-image-upload-overlay"},mD={class:"wov-image-upload-status"},mw=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(Rn);if(!n)throw new Error("ImageBlock must be used within a WovenCanvas component");const r=n,o=Tt(e.entityId,as),s=Tt(e.entityId,Qi),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===mr.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 mr.Pending:return"Loading...";case mr.Uploading:return"Loading...";case mr.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",uD,[a.value&&!i.value?(d.openBlock(),d.createElementBlock("div",dD,[...m[0]||(m[0]=[d.createElementVNode("span",null,"Loading...",-1)])])):l.value?(d.openBlock(),d.createElementBlock("div",fD,[...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,hD)):d.createCommentVNode("",!0),f.value?(d.openBlock(),d.createElementBlock("div",pD,[d.createElementVNode("span",mD,d.toDisplayString(f.value),1)])):d.createCommentVNode("",!0)])}}});function gD(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var gw={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})()})(gw);var yD=gw.exports;const yw=gD(yD);var wD=Object.defineProperty,Of=(t,e)=>{for(var n in e)wD(t,n,{get:e[n],enumerable:!0})},ww=pe("start-pen-stroke"),vw=pe("add-pen-stroke-point"),kw=pe("complete-pen-stroke"),bw=pe("remove-pen-stroke"),Sw={};Of(Sw,{POINTS_CAPACITY:()=>xc,PenStroke:()=>tr});var xc=256,vD={points:C.buffer(C.float32()).size(xc*2),pressures:C.buffer(C.float32()).size(xc),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)},kD=class extends qt{constructor(){super({name:"penStroke",sync:"document"},vD)}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}},tr=new kD,bD=8,SD="pen",Ew={};Of(Ew,{PenStateSingleton:()=>Df});var ks={Idle:"idle",Drawing:"drawing"},Df=Eo("penState",{state:C.string().max(16).default(ks.Idle),activeStroke:C.ref(),lastWorldPosition:C.tuple(C.float64(),2).default([0,0])}),Cw={};Of(Cw,{capturePenSystem:()=>CD,updatePenSystem:()=>xD});var ED=zr({guards:{},actions:{startStroke:({event:t})=>{const e=t.pointerType===Lr.Pen?t.pressure:null;ww.spawn(t.ctx,{worldPosition:t.worldPosition,pressure:e,thickness:bD})},addPoint:Ze({lastWorldPosition:({event:t,context:e})=>{if(!e.activeStroke)return e.lastWorldPosition;const n=t.pointerType===Lr.Pen?t.pressure:null;return vw.spawn(t.ctx,{strokeId:e.activeStroke,worldPosition:t.worldPosition,pressure:n}),t.worldPosition}}),completeStroke:({event:t,context:e})=>{e.activeStroke&&kw.spawn(t.ctx,{strokeId:e.activeStroke})},removeStroke:({event:t,context:e})=>{e.activeStroke&&bw.spawn(t.ctx,{strokeId:e.activeStroke})},resetContext:Ze({activeStroke:()=>null,lastWorldPosition:()=>[0,0]})}}).createMachine({id:"pen",initial:ks.Idle,context:{activeStroke:null,lastWorldPosition:[0,0]},states:{[ks.Idle]:{entry:["resetContext"],on:{pointerDown:{target:ks.Drawing,actions:["startStroke"]}}},[ks.Drawing]:{on:{pointerMove:{actions:["addPoint"]},pointerUp:{target:ks.Idle,actions:["completeStroke"]},cancel:{target:ks.Idle,actions:["removeStroke"]}}}}}),CD=Se({phase:"capture",priority:100},t=>{const e=ct.getButtons(t,"pen"),n=jr(t,e);n.length!==0&&Df.run(t,ED,n)}),_D=ie(t=>t.tracking(tr)),xD=Se({phase:"update"},t=>{fe(t,ww,(e,{worldPosition:n,pressure:r,thickness:o})=>{TD(e,n,r,o)}),fe(t,vw,(e,{strokeId:n,worldPosition:r,pressure:o})=>{MD(e,n,r,o)}),fe(t,kw,(e,{strokeId:n})=>{AD(e,n)}),fe(t,bw,(e,{strokeId:n})=>{ID(e,n)});for(const e of _D.addedOrChanged(t))tr.read(t,e).isComplete&&_w(t,e)});function TD(t,e,n,r){const o=r/2,s=Bt(t);ee(t,s,me,{id:crypto.randomUUID()}),ee(t,s,T,{tag:"pen-stroke",rank:Zn.genNext(t),position:[e[0]-o,e[1]-o],size:[o*2,o*2]}),ee(t,s,In,{});const{sessionId:i}=Je(t);ee(t,s,Rt,{sessionId:i});const a=n!==null;ee(t,s,tr,{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=Df.write(t);c.activeStroke=s,c.lastWorldPosition=e}function MD(t,e,n,r){const o=tr.write(t,e),s=o.pointCount;if(!(s>=xc)&&(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++,!Ve.containsPoint(t,e,n))){Ve.expandByPoint(t,e,n);const{value:i}=Ve.read(t,e),a=T.write(t,e);$.set(a.position,ne.left(i),ne.top(i)),$.set(a.size,ne.width(i),ne.height(i)),o.originalLeft=a.position[0],o.originalTop=a.position[1],o.originalWidth=a.size[0],o.originalHeight=a.size[1]}}function AD(t,e){const n=tr.write(t,e);n.isComplete=!0,mn(t,e,Rt),_w(t,e)}function ID(t,e){st(t,e)}function _w(t,e){const n=tr.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=yw(r,o,!1);for(;s.length-1>ui;)o*=2,s=yw(r,o,!1);if(s.length===1){const u=s[0];s.push({x:u.x,y:u.y})}R(t,e,Me)?Me.clear(t,e):ee(t,e,Me,{});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];Me.addCapsuleUv(t,e,p,m,n.thickness)}}var ND=t=>Object.values(t).filter(e=>typeof e=="object"&&e!==null&&"_system"in e&&"phase"in e);function BD(){return{name:SD,components:Object.values(Sw).filter(t=>t instanceof qt),singletons:Object.values(Ew).filter(t=>t instanceof vt),blockDefs:[{tag:"pen-stroke",resizeMode:"free",components:[tr,In],connectors:{enabled:!1}}],systems:ND(Cw),resources:{}}}const PD=["data-complete"],OD={preserveAspectRatio:"none"},DD=["d","fill"],RD={key:0,class:"highlight",preserveAspectRatio:"none"},zD=["d"],xw=ys(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=Tt(e.entityId,tr),r=Tt(e.entityId,T),o=Tt(e.entityId,In),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 v=p/2;return`M ${v},0 a ${v},${v} 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 v=2;v<f.length-1;v++)m=f[v],g=f[v+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 v=f.points[w*2],b=f.points[w*2+1],S=(v-f.originalLeft)*p,k=(b-f.originalTop)*m;f.hasPressure?g.push([S,k,f.pressures[w]]):g.push([S,k])}const y=Pf(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,v=Pf(g,{last:!0,size:w,simulatePressure:!f.hasPressure});i.value=l(v,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",OD,[d.createElementVNode("path",{d:s.value,fill:c.value},null,8,DD)])),u.value?(d.openBlock(),d.createElementBlock("svg",RD,[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,zD)])):d.createCommentVNode("",!0)],8,PD)}}}),[["__scopeId","data-v-9b41c649"]]);function ut(){const t=d.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 Ba={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 $t(t){this.content=t}$t.prototype={constructor:$t,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 $t(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 $t(n)},addToStart:function(t,e){return new $t([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new $t(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 $t(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=$t.from(t),t.size?new $t(t.content.concat(this.subtract(t).content)):this},append:function(t){return t=$t.from(t),t.size?new $t(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=$t.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}},$t.from=function(t){if(t instanceof $t)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new $t(e)};function Tw(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=Tw(o.content,s.content,n+1);if(i!=null)return i}n+=o.nodeSize}}function Mw(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=Mw(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 Tw(this,e,n)}findDiffEnd(e,n=this.size,r=e.size){return Mw(this,e,n,r)}findIndex(e){if(e==0)return Tc(0,e);if(e==this.size)return Tc(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?Tc(n+1,s):Tc(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 Rf={index:0,offset:0};function Tc(t,e){return Rf.index=t,Rf.offset=e,Rf}function Mc(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(!Mc(t[r],e[r]))return!1}else{for(let r in t)if(!(r in e)||!Mc(t[r],e[r]))return!1;for(let r in e)if(!(r in t))return!1}return!0}let Fe=class Sp{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&&Mc(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 Sp.none;if(e instanceof Sp)return[e];let n=e.slice();return n.sort((r,o)=>r.type.rank-o.type.rank),n}};Fe.none=[];class Ac extends Error{}class K{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=Iw(this.content,e+this.openStart,n);return r&&new K(r,this.openStart,this.openEnd)}removeBetween(e,n){return new K(Aw(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 K.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 K(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 K(e,r,o)}}K.empty=new K(D.empty,0,0);function Aw(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(Aw(s.content,e-o-1,n-o-1)))}function Iw(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=Iw(i.content,e-s-1,n,i);return a&&t.replaceChild(o,i.copy(a))}function $D(t,e,n){if(n.openStart>t.depth)throw new Ac("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Ac("Inconsistent open depths");return Nw(t,e,n,0)}function Nw(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=Nw(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 Ss(i,a.cut(0,t.parentOffset).append(n.content).append(a.cut(e.parentOffset)))}else{let{start:i,end:a}=LD(n,t);return Ss(s,Pw(t,i,a,e,r))}else return Ss(s,Ic(t,e,r))}function Bw(t,e){if(!e.type.compatibleContent(t.type))throw new Ac("Cannot join "+e.type.name+" onto "+t.type.name)}function zf(t,e,n){let r=t.node(n);return Bw(r,e.node(n)),r}function bs(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 Pa(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&&(bs(t.nodeAfter,r),s++));for(let a=s;a<i;a++)bs(o.child(a),r);e&&e.depth==n&&e.textOffset&&bs(e.nodeBefore,r)}function Ss(t,e){return t.type.checkContent(e),t.copy(e)}function Pw(t,e,n,r,o){let s=t.depth>o&&zf(t,e,o+1),i=r.depth>o&&zf(n,r,o+1),a=[];return Pa(null,t,o,a),s&&i&&e.index(o)==n.index(o)?(Bw(s,i),bs(Ss(s,Pw(t,e,n,r,o+1)),a)):(s&&bs(Ss(s,Ic(t,e,o+1)),a),Pa(e,n,o,a),i&&bs(Ss(i,Ic(n,r,o+1)),a)),Pa(r,null,o,a),new D(a)}function Ic(t,e,n){let r=[];if(Pa(null,t,n,r),t.depth>n){let o=zf(t,e,n+1);bs(Ss(o,Ic(t,e,n+1)),r)}return Pa(e,null,n,r),new D(r)}function LD(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 Oa{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 Fe.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 Nc(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 Oa(n,r,s)}static resolveCached(e,n){let r=Ow.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 Ow.set(e,r=new VD);let o=r.elts[r.i]=Oa.resolve(e,n);return r.i=(r.i+1)%FD,o}}class VD{constructor(){this.elts=[],this.i=0}}const FD=12,Ow=new WeakMap;class Nc{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 jD=Object.create(null);let Yr=class Ep{constructor(e,n,r,o=Fe.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&&Mc(this.attrs,n||e.defaultAttrs||jD)&&Fe.sameSet(this.marks,r||Fe.none)}copy(e=null){return e==this.content?this:new Ep(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new Ep(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 K.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 K(c,o.depth-i,s.depth-i)}replace(e,n,r){return $D(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 Oa.resolveCached(this,e)}resolveNoCache(e){return Oa.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()+")"),Dw(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=Fe.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(!Fe.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}};Yr.prototype.text=void 0;class Bc extends Yr{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):Dw(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 Bc(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Bc(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 Dw(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Es{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new UD(e,n);if(r.next==null)return Es.empty;let o=Rw(r);r.next&&r.err("Unexpected trailing text");let s=JD(qD(o));return GD(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
|
+
`)}}Es.empty=new Es(!0);class UD{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 Rw(t){let e=[];do e.push(WD(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function WD(t){let e=[];do e.push(HD(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function HD(t){let e=YD(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=ZD(t,e);else break;return e}function zw(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function ZD(t,e){let n=zw(t),r=n;return t.eat(",")&&(t.next!="}"?r=zw(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function KD(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 YD(t){if(t.eat("(")){let e=Rw(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=KD(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 qD(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 $w(t,e){return e-t}function Lw(t,e){let n=[];return r(e),n.sort($w);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 JD(t){let e=Object.create(null);return n(Lw(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]);Lw(t,l).forEach(u=>{c||o.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new Es(r.indexOf(t.length-1)>-1);for(let i=0;i<o.length;i++){let a=o[i][1].sort($w);s.next.push({type:o[i][0],next:e[a.join(",")]||n(a)})}return s}}function GD(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 Vw(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 Fw(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 jw(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 Uw(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new QD(t,r,e[r]);return n}let Ww=class vS{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=Uw(e,r.attrs),this.defaultAttrs=Vw(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==Es.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:Fw(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Yr(this,this.computeAttrs(e),D.from(n),Fe.setFrom(r))}createChecked(e=null,n,r){return n=D.from(n),this.checkContent(n),new Yr(this,this.computeAttrs(e),n,Fe.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 Yr(this,e,n.append(s),Fe.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){jw(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:Fe.none:e}static compile(e,n){let r=Object.create(null);e.forEach((s,i)=>r[s]=new vS(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 XD(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 QD{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?XD(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Pc{constructor(e,n,r,o){this.name=e,this.rank=n,this.schema=r,this.spec=o,this.attrs=Uw(e,o.attrs),this.excluded=null;let s=Vw(this.attrs);this.instance=s?new Fe(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Fe(this,Fw(this.attrs,e))}static compile(e,n){let r=Object.create(null),o=0;return e.forEach((s,i)=>r[s]=new Pc(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){jw(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class Hw{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=$t.from(e.nodes),n.marks=$t.from(e.marks||{}),this.nodes=Ww.compile(this.spec.nodes,this),this.marks=Pc.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]=Es.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?Zw(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==""?[]:Zw(this,i.split(" "))}this.nodeFromJSON=o=>Yr.fromJSON(this,o),this.markFromJSON=o=>Fe.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 Ww){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 Bc(r,r.defaultAttrs,e,Fe.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 Zw(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 eR(t){return t.tag!=null}function tR(t){return t.style!=null}class qr{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(o=>{if(eR(o))this.tags.push(o);else if(tR(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 Jw(this,n,!1);return r.addAll(e,Fe.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new Jw(this,n,!0);return r.addAll(e,Fe.none,n.from,n.to),K.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(oR(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=Gw(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=Gw(i)),i.node||i.ignore||i.mark||(i.node=o)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new qr(e,qr.schemaRules(e)))}}const Kw={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},nR={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Yw={ol:!0,ul:!0},Da=1,$f=2,Ra=4;function qw(t,e,n){return e!=null?(e?Da:0)|(e==="full"?$f:0):t&&t.whitespace=="pre"?Da|$f:n&~Ra}class Oc{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=Fe.none,this.match=s||(i&Ra?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&Da)){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&&!Kw.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Jw{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=qw(null,n.preserveWhitespace,0)|(r?Ra:0);o?s=new Oc(o.type,o.attrs,Fe.none,!0,n.topMatch||o.type.contentMatch,i):r?s=new Oc(null,null,Fe.none,!0,null,i):s=new Oc(e.schema.topNodeType,null,Fe.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&$f?"full":this.localPreserveWS||(o.options&Da)>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;Yw.hasOwnProperty(i)&&this.parser.normalizeLists&&rR(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:nR.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(Kw.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=Fe.none;for(let a of o.concat(e.marks))(s.type?s.type.allowsMarkType(a.type):Xw(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=qw(e,s,i.options);i.options&Ra&&i.content.length==0&&(a|=Ra);let l=Fe.none;return r=r.filter(c=>(i.type?i.type.allowsMarkType(c.type):Xw(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new Oc(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|=Da)}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 rR(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Yw.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function oR(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function Gw(t){let e={};for(let n in t)e[n]=t[n];return e}function Xw(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 Cs{constructor(e,n){this.nodes=e,this.marks=n}serializeFragment(e,n={},r){r||(r=Lf(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}=Dc(Lf(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&&Dc(Lf(r),o(e,n),null,e.attrs)}static renderSpec(e,n,r=null,o){return Dc(e,n,r,o)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Cs(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=Qw(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return Qw(e.marks)}}function Qw(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function Lf(t){return t.document||window.document}const ev=new WeakMap;function sR(t){let e=ev.get(t);return e===void 0&&ev.set(t,e=iR(t)),e}function iR(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 Dc(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=sR(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}=Dc(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 tv=65535,nv=Math.pow(2,16);function aR(t,e){return t+e*nv}function rv(t){return t&tv}function lR(t){return(t-(t&tv))/nv}const ov=1,sv=2,Rc=4,iv=8;class Vf{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&iv)>0}get deletedBefore(){return(this.delInfo&(ov|Rc))>0}get deletedAfter(){return(this.delInfo&(sv|Rc))>0}get deletedAcross(){return(this.delInfo&Rc)>0}}class Cn{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Cn.empty)return Cn.empty}recover(e){let n=0,r=rv(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+lR(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:aR(a/3,e-l),g=e==l?sv:e==f?ov:Rc;return(n<0?e!=l:e!=f)&&(g|=iv),new Vf(p,g,m)}o+=u-c}return r?e+o:new Vf(e+o,0,null)}touches(e,n){let r=0,o=rv(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 Cn(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?Cn.empty:new Cn(e<0?[0,-e,0]:[0,0,e])}}Cn.empty=new Cn([]);class za{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 za(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 za;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 Vf(e,o,null)}}const Ff=Object.create(null);class Zt{getMap(){return Cn.empty}merge(e){return null}static fromJSON(e,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Ff[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 Ff)throw new RangeError("Duplicate use of step JSON ID "+e);return Ff[e]=n,n.prototype.jsonID=e,n}}class dt{constructor(e,n){this.doc=e,this.failed=n}static ok(e){return new dt(e,null)}static fail(e){return new dt(null,e)}static fromReplace(e,n,r,o){try{return dt.ok(e.replace(n,r,o))}catch(s){if(s instanceof Ac)return dt.fail(s.message);throw s}}}function jf(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let s=t.child(o);s.content.size&&(s=s.copy(jf(s.content,e,s))),s.isInline&&(s=e(s,n,o)),r.push(s)}return D.fromArray(r)}class Po extends Zt{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 K(jf(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 dt.fromReplace(e,this.from,this.to,s)}invert(){return new nr(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 Po(n.pos,r.pos,this.mark)}merge(e){return e instanceof Po&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Po(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 Po(n.from,n.to,e.markFromJSON(n.mark))}}Zt.jsonID("addMark",Po);class nr extends Zt{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 K(jf(n.content,o=>o.mark(this.mark.removeFromSet(o.marks)),e),n.openStart,n.openEnd);return dt.fromReplace(e,this.from,this.to,r)}invert(){return new Po(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 nr(n.pos,r.pos,this.mark)}merge(e){return e instanceof nr&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new nr(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 nr(n.from,n.to,e.markFromJSON(n.mark))}}Zt.jsonID("removeMark",nr);class Oo extends Zt{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return dt.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return dt.fromReplace(e,this.pos,this.pos+1,new K(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 _s(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))}}Zt.jsonID("addNodeMark",Oo);class _s extends Zt{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return dt.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return dt.fromReplace(e,this.pos,this.pos+1,new K(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 _s(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 _s(n.pos,e.markFromJSON(n.mark))}}Zt.jsonID("removeNodeMark",_s);class Mt extends Zt{constructor(e,n,r,o=!1){super(),this.from=e,this.to=n,this.slice=r,this.structure=o}apply(e){return this.structure&&Uf(e,this.from,this.to)?dt.fail("Structure replace would overwrite content"):dt.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Cn([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?K.empty:new K(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?K.empty:new K(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,K.fromJSON(e,n.slice),!!n.structure)}}Zt.jsonID("replace",Mt);class At extends Zt{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&&(Uf(e,this.from,this.gapFrom)||Uf(e,this.gapTo,this.to)))return dt.fail("Structure gap-replace would overwrite content");let n=e.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return dt.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?dt.fromReplace(e,this.from,this.to,r):dt.fail("Content does not fit in gap")}getMap(){return new Cn([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 At(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 At(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 At(n.from,n.to,n.gapFrom,n.gapTo,K.fromJSON(e,n.slice),n.insert,!!n.structure)}}Zt.jsonID("replaceAround",At);function Uf(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 cR(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 nr(h,p,f[g])));a&&a.to==h?a.to=p:s.push(a=new Po(h,p,r))}}),o.forEach(l=>t.step(l)),s.forEach(l=>t.step(l))}function uR(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 Pc){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 nr(i.from,i.to,i.style)))}function Wf(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 Mt(a,u,K.empty));else{r=f;for(let h=0;h<c.marks.length;h++)n.allowsMarkType(c.marks[h].type)||t.step(new nr(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 K(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 K(l,0,0))}for(let l=i.length-1;l>=0;l--)t.step(i[l])}function dR(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Ti(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||!dR(i,a,l))break;a&&(o=1),l<i.childCount&&(s=1)}return null}function fR(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 At(l,c,i,a,new K(u.append(h),f,p),u.size-f,!0))}function av(t,e,n=null,r=t){let o=hR(t,e),s=o&&pR(r,e);return s?o.map(lv).concat({type:e,attrs:n}).concat(s.map(lv)):null}function lv(t){return{type:t,attrs:null}}function hR(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 pR(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 mR(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 At(o,s,o,s,new K(r,0,0),n.length,!0))}function gR(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)&&yR(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&&uv(t,i,a,s),Wf(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 At(f,h,f+1,h-1,new K(D.from(r.create(l,null,i.marks)),0,0),1,!0)),c===!0&&cv(t,i,a,s),!1}})}function cv(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 uv(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 yR(t,e,n){let r=t.resolve(e),o=r.index();return r.parent.canReplaceWith(o,o+1,n)}function wR(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 At(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new K(D.from(i),0,0),1,!0))}function Jr(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 vR(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 K(s.append(i),n,n),!0))}function xs(t,e){let n=t.resolve(e),r=n.index();return dv(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function kR(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 dv(t,e){return!!(t&&e&&!t.isLeaf&&kR(t,e))}function zc(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&&dv(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 bR(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);uv(t,u.node(),u.before(),a)}i.inlineContent&&Wf(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),K.empty,!0)),r===!0){let u=t.doc.resolve(c);cv(t,u.node(),u.before(),t.steps.length)}return t}function SR(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 fv(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 $c(t,e,n=e,r=K.empty){if(e==n&&!r.size)return null;let o=t.resolve(e),s=t.resolve(n);return hv(o,s,r)?new Mt(e,n,r):new ER(o,s,r).fit()}function hv(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class ER{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 K(s,i,a);return e>-1?new At(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=Hf(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=Hf(e,n);return!o.childCount||o.firstChild.isLeaf?!1:(this.unplaced=new K(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=Hf(e,n);if(o.childCount<=1&&n>0){let s=e.size-n<=n+o.size;this.unplaced=new K($a(e,n-1,1),n-1,s?n-1:r)}else this.unplaced=new K($a(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(pv(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=La(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?K.empty:new K($a(i.content,e-1,1),e-1,p<0?i.openEnd:e-1):new K($a(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||!Zf(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=Zf(e,n,o,r,s);if(i){for(let a=n-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=Zf(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=La(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=La(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=La(this.placed,this.frontier.length,n))}}function $a(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy($a(t.firstChild.content,e-1,n)))}function La(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(La(t.lastChild.content,e-1,n)))}function Hf(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function pv(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,pv(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 Zf(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&&!CR(n,s.content,i)?a:null}function CR(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}function _R(t){return t.spec.defining||t.spec.definingForContent}function xR(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let o=t.doc.resolve(e),s=t.doc.resolve(n);if(hv(o,s,r))return t.step(new Mt(e,n,r));let i=gv(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=_R(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 v=o.node(y-1),b=o.index(y-1);if(v.canReplaceWith(b,b,m.type,m.marks))return t.replace(o.before(y),w?s.after(y):n,new K(mv(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 mv(t,e,n,r,o){if(e<n){let s=t.firstChild;t=t.replaceChild(0,s.copy(mv(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 TR(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let o=SR(t.doc,e,r.type);o!=null&&(e=n=o)}t.replaceRange(e,n,new K(D.from(r),0,0))}function MR(t,e,n){let r=t.doc.resolve(e),o=t.doc.resolve(n),s=gv(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 gv(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 Mi extends Zt{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 dt.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 dt.fromReplace(e,this.pos,this.pos+1,new K(D.from(o),0,n.isLeaf?0:1))}getMap(){return Cn.empty}invert(e){return new Mi(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 Mi(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 Mi(n.pos,n.attr,n.value)}}Zt.jsonID("attr",Mi);class Va extends Zt{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 dt.ok(r)}getMap(){return Cn.empty}invert(e){return new Va(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 Va(n.attr,n.value)}}Zt.jsonID("docAttr",Va);let Ai=class extends Error{};Ai=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n},Ai.prototype=Object.create(Error.prototype),Ai.prototype.constructor=Ai,Ai.prototype.name="TransformError";class yv{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new za}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Ai(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=K.empty){let o=$c(this.doc,e,n,r);return o&&this.step(o),this}replaceWith(e,n,r){return this.replace(e,n,new K(D.from(r),0,0))}delete(e,n){return this.replace(e,n,K.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return xR(this,e,n,r),this}replaceRangeWith(e,n,r){return TR(this,e,n,r),this}deleteRange(e,n){return MR(this,e,n),this}lift(e,n){return fR(this,e,n),this}join(e,n=1){return bR(this,e,n),this}wrap(e,n){return mR(this,e,n),this}setBlockType(e,n=e,r,o=null){return gR(this,e,n,r,o),this}setNodeMarkup(e,n,r=null,o){return wR(this,e,n,r,o),this}setNodeAttribute(e,n,r){return this.step(new Mi(e,n,r)),this}setDocAttribute(e,n){return this.step(new Va(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 Fe)n.isInSet(r.marks)&&this.step(new _s(e,n));else{let o=r.marks,s,i=[];for(;s=n.isInSet(o);)i.push(new _s(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 vR(this,e,n,r),this}addMark(e,n,r){return cR(this,e,n,r),this}removeMark(e,n,r){return uR(this,e,n,r),this}clearIncompatible(e,n,r){return Wf(this,e,n,r),this}}const Kf=Object.create(null);class be{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new AR(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=K.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?K.empty:n),a==0&&kv(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),kv(e,r,n.isInline?-1:1))}}static findFrom(e,n,r=!1){let o=e.parent.inlineContent?new ye(e):Ii(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?Ii(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Ii(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 _n(e.node(0))}static atStart(e){return Ii(e,e,0,0,1)||new _n(e)}static atEnd(e){return Ii(e,e,e.content.size,e.childCount,-1)||new _n(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Kf[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 Kf)throw new RangeError("Duplicate use of selection JSON ID "+e);return Kf[e]=n,n.prototype.jsonID=e,n}getBookmark(){return ye.between(this.$anchor,this.$head).getBookmark()}}be.prototype.visible=!0;class AR{constructor(e,n){this.$from=e,this.$to=n}}let wv=!1;function vv(t){!wv&&!t.parent.inlineContent&&(wv=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class ye extends be{constructor(e,n=e){vv(e),vv(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 be.near(r);let o=e.resolve(n.map(this.anchor));return new ye(o.parent.inlineContent?o:r,r)}replace(e,n=K.empty){if(super.replace(e,n),n==K.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof ye&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Lc(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 ye(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=be.findFrom(n,r,!0)||be.findFrom(n,-r,!0);if(s)n=s.$head;else return be.near(n,r)}return e.parent.inlineContent||(o==0?e=n:(e=(be.findFrom(e,-r,!0)||be.findFrom(e,r,!0)).$anchor,e.pos<n.pos!=o<0&&(e=n))),new ye(e,n)}}be.jsonID("text",ye);class Lc{constructor(e,n){this.anchor=e,this.head=n}map(e){return new Lc(e.map(this.anchor),e.map(this.head))}resolve(e){return ye.between(e.resolve(this.anchor),e.resolve(this.head))}}class ae extends be{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?be.near(s):new ae(s)}content(){return new K(D.from(this.node),0,0)}eq(e){return e instanceof ae&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Yf(this.anchor)}static fromJSON(e,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new ae(e.resolve(n.anchor))}static create(e,n){return new ae(e.resolve(n))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}ae.prototype.visible=!1,be.jsonID("node",ae);class Yf{constructor(e){this.anchor=e}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Lc(r,r):new Yf(r)}resolve(e){let n=e.resolve(this.anchor),r=n.nodeAfter;return r&&ae.isSelectable(r)?new ae(n):be.near(n)}}class _n extends be{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,n=K.empty){if(n==K.empty){e.delete(0,e.doc.content.size);let r=be.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,n)}toJSON(){return{type:"all"}}static fromJSON(e){return new _n(e)}map(e){return new _n(e)}eq(e){return e instanceof _n}getBookmark(){return IR}}be.jsonID("all",_n);const IR={map(){return this},resolve(t){return new _n(t)}};function Ii(t,e,n,r,o,s=!1){if(e.inlineContent)return ye.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&&ae.isSelectable(a))return ae.create(t,n-(o<0?a.nodeSize:0))}else{let l=Ii(t,a,n+o,o<0?a.childCount:0,o,s);if(l)return l}n+=a.nodeSize*o}return null}function kv(t,e,n){let r=t.steps.length-1;if(r<e)return;let o=t.steps[r];if(!(o instanceof Mt||o instanceof At))return;let s=t.mapping.maps[r],i;s.forEach((a,l,c,u)=>{i==null&&(i=u)}),t.setSelection(be.near(t.doc.resolve(i),n))}const bv=1,Vc=2,Sv=4;class NR extends yv{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|bv)&~Vc,this.storedMarks=null,this}get selectionSet(){return(this.updated&bv)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Vc,this}ensureMarks(e){return Fe.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&Vc)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~Vc,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)||Fe.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(be.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|=Sv,this}get scrolledIntoView(){return(this.updated&Sv)>0}}function Ev(t,e){return!e||!t?t:t.bind(e)}class Fa{constructor(e,n,r){this.name=e,this.init=Ev(n.init,r),this.apply=Ev(n.apply,r)}}const BR=[new Fa("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Fa("selection",{init(t,e){return t.selection||be.atStart(e.doc)},apply(t){return t.selection}}),new Fa("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Fa("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class qf{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=BR.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 Fa(r.key,r.spec.state,r))})}}class Ni{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 Ni(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 NR(this)}static create(e){let n=new qf(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new Ni(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 qf(this.schema,e.plugins),r=n.fields,o=new Ni(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 qf(e.schema,e.plugins),s=new Ni(o);return o.fields.forEach(i=>{if(i.name=="doc")s.doc=Yr.fromJSON(e.schema,n.doc);else if(i.name=="selection")s.selection=be.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 Cv(t,e,n){for(let r in t){let o=t[r];o instanceof Function?o=o.bind(e):r=="handleDOMEvents"&&(o=Cv(o,e,{})),n[r]=o}return n}class wt{constructor(e){this.spec=e,this.props={},e.props&&Cv(e.props,this,this.props),this.key=e.key?e.key.key:_v("plugin")}getState(e){return e[this.key]}}const Jf=Object.create(null);function _v(t){return t in Jf?t+"$"+ ++Jf[t]:(Jf[t]=0,t+"$")}class tn{constructor(e="key"){this.key=_v(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Gf=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function xv(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const Tv=(t,e,n)=>{let r=xv(t,n);if(!r)return!1;let o=Xf(r);if(!o){let i=r.blockRange(),a=i&&Ti(i);return a==null?!1:(e&&e(t.tr.lift(i,a).scrollIntoView()),!0)}let s=o.nodeBefore;if(Rv(t,o,e,-1))return!0;if(r.parent.content.size==0&&(Bi(s,"end")||ae.isSelectable(s)))for(let i=r.depth;;i--){let a=$c(t.doc,r.before(i),r.after(i),K.empty);if(a&&a.slice.size<a.to-a.from){if(e){let l=t.tr.step(a);l.setSelection(Bi(s,"end")?be.findFrom(l.doc.resolve(l.mapping.map(o.pos,-1)),-1):ae.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},PR=(t,e,n)=>{let r=xv(t,n);if(!r)return!1;let o=Xf(r);return o?Mv(t,o,e):!1},OR=(t,e,n)=>{let r=Iv(t,n);if(!r)return!1;let o=Qf(r);return o?Mv(t,o,e):!1};function Mv(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=$c(t.doc,s,l,K.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(ye.create(u.doc,s)),n(u.scrollIntoView())}return!0}function Bi(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 Av=(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=Xf(r)}let i=s&&s.nodeBefore;return!i||!ae.isSelectable(i)?!1:(e&&e(t.tr.setSelection(ae.create(t.doc,s.pos-i.nodeSize)).scrollIntoView()),!0)};function Xf(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 Iv(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}const Nv=(t,e,n)=>{let r=Iv(t,n);if(!r)return!1;let o=Qf(r);if(!o)return!1;let s=o.nodeAfter;if(Rv(t,o,e,1))return!0;if(r.parent.content.size==0&&(Bi(s,"start")||ae.isSelectable(s))){let i=$c(t.doc,r.before(),r.after(),K.empty);if(i&&i.slice.size<i.to-i.from){if(e){let a=t.tr.step(i);a.setSelection(Bi(s,"start")?be.findFrom(a.doc.resolve(a.mapping.map(o.pos)),1):ae.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},Bv=(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=Qf(r)}let i=s&&s.nodeAfter;return!i||!ae.isSelectable(i)?!1:(e&&e(t.tr.setSelection(ae.create(t.doc,s.pos)).scrollIntoView()),!0)};function Qf(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 DR=(t,e)=>{let n=t.selection,r=n instanceof ae,o;if(r){if(n.node.isTextblock||!xs(t.doc,n.from))return!1;o=n.from}else if(o=zc(t.doc,n.from,-1),o==null)return!1;if(e){let s=t.tr.join(o);r&&s.setSelection(ae.create(s.doc,o-t.doc.resolve(o).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},RR=(t,e)=>{let n=t.selection,r;if(n instanceof ae){if(n.node.isTextblock||!xs(t.doc,n.to))return!1;r=n.to}else if(r=zc(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},zR=(t,e)=>{let{$from:n,$to:r}=t.selection,o=n.blockRange(r),s=o&&Ti(o);return s==null?!1:(e&&e(t.tr.lift(o,s).scrollIntoView()),!0)},Pv=(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 eh(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 $R=(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=eh(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(be.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},Ov=(t,e)=>{let n=t.selection,{$from:r,$to:o}=n;if(n instanceof _n||r.parent.inlineContent||o.parent.inlineContent)return!1;let s=eh(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(ye.create(a.doc,i+1)),e(a.scrollIntoView())}return!0},Dv=(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(Jr(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),o=r&&Ti(r);return o==null?!1:(e&&e(t.tr.lift(r,o).scrollIntoView()),!0)};function LR(t){return(e,n)=>{let{$from:r,$to:o}=e.selection;if(e.selection instanceof ae&&e.selection.node.isBlock)return!r.parentOffset||!Jr(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=eh(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 ye||e.selection instanceof _n)&&u.deleteSelection();let f=u.mapping.map(r.pos),h=Jr(u.doc,f,s.length,s);if(h||(s[0]=a?{type:a}:null,h=Jr(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 VR=LR(),FR=(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(ae.create(t.doc,o))),!0)};function jR(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||xs(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function Rv(t,e,n,r){let o=e.nodeBefore,s=e.nodeAfter,i,a,l=o.type.spec.isolating||s.type.spec.isolating;if(!l&&jR(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 At(e.pos-1,p,e.pos,p,new K(m,1,0),i.length,!0)),y=g.doc.resolve(p+2*i.length);y.nodeAfter&&y.nodeAfter.type==o.type&&xs(g.doc,y.pos)&&g.join(y.pos),n(g.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&l?null:be.findFrom(e,1),f=u&&u.$from.blockRange(u.$to),h=f&&Ti(f);if(h!=null&&h>=e.depth)return n&&n(t.tr.lift(f,h).scrollIntoView()),!0;if(c&&Bi(s,"start",!0)&&Bi(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 v=t.tr.step(new At(e.pos-m.length,e.pos+s.nodeSize,e.pos+y,e.pos+s.nodeSize-y,new K(w,m.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function zv(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(ye.create(e.doc,t<0?o.start(s):o.end(s)))),!0):!1}}const UR=zv(-1),WR=zv(1);function HR(t,e=null){return function(n,r){let{$from:o,$to:s}=n.selection,i=o.blockRange(s),a=i&&av(i,t,e);return a?(r&&r(n.tr.wrap(i,a).scrollIntoView()),!0):!1}}function $v(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 th(...t){return function(e,n,r){for(let o=0;o<t.length;o++)if(t[o](e,n,r))return!0;return!1}}th(Gf,Tv,Av),th(Gf,Nv,Bv),th(Pv,Ov,Dv,VR),typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function ZR(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 KR(a,i,t,e)?(r&&r(a.scrollIntoView()),!0):!1}}function KR(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 Nc(l,l,e.depth),e.endIndex<e.parent.childCount&&(e=new Nc(e.$from,i.resolve(e.$to.end(e.depth)),e.depth)),o=!0}let a=av(s,n,r,e);return a?(t&&YR(t,e,a,o,n),!0):!1}function YR(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 At(e.start-(r?2:0),e.end,e.start,e.end,new K(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&&Jr(t.doc,l,a)&&(t.split(l,a),l+=2*a),l+=c.child(u).nodeSize;return t}function qR(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?JR(e,n,t,s):GR(e,n,s):!0:!1}}function JR(t,e,n,r){let o=t.tr,s=r.end,i=r.$to.end(r.depth);s<i&&(o.step(new At(s-1,i,s,i,new K(D.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new Nc(o.doc.resolve(r.$from.pos),o.doc.resolve(i),r.depth));const a=Ti(r);if(a==null)return!1;o.lift(r,a);let l=o.doc.resolve(o.mapping.map(s,-1)-1);return xs(o.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&o.join(l.pos),e(o.scrollIntoView()),!0}function GR(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 At(f-(a?1:0),h+(l?1:0),f+1,h-1,new K((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 XR(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 K(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 At(h-(c?3:1),p,h,p,f,1,!0)).scrollIntoView())}return!0}}const Lt=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},Pi=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let nh=null;const Gr=function(t,e,n){let r=nh||(nh=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},QR=function(){nh=null},Ts=function(t,e,n,r){return n&&(Lv(t,e,n,r,-1)||Lv(t,e,n,r,1))},e3=/^(img|br|input|textarea|hr)$/i;function Lv(t,e,n,r,o){for(var s;;){if(t==n&&e==r)return!0;if(e==(o<0?0:zn(t))){let i=t.parentNode;if(!i||i.nodeType!=1||ja(t)||e3.test(t.nodeName)||t.contentEditable=="false")return!1;e=Lt(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?zn(t):0}else return!1}}function zn(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function t3(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=zn(t)}else if(t.parentNode&&!ja(t))e=Lt(t),t=t.parentNode;else return null}}function n3(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&&!ja(t))e=Lt(t)+1,t=t.parentNode;else return null}}function r3(t,e,n){for(let r=e==0,o=e==zn(t);r||o;){if(t==n)return!0;let s=Lt(t);if(t=t.parentNode,!t)return!1;r=r&&s==0,o=o&&s==zn(t)}}function ja(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 Fc=function(t){return t.focusNode&&Ts(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Ms(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}function o3(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function s3(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(zn(r.offsetNode),r.offset)}}catch{}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(zn(r.startContainer),r.startOffset)}}}const br=typeof navigator<"u"?navigator:null,Vv=typeof document<"u"?document:null,Do=br&&br.userAgent||"",rh=/Edge\/(\d+)/.exec(Do),Fv=/MSIE \d/.exec(Do),oh=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Do),fn=!!(Fv||oh||rh),Ro=Fv?document.documentMode:oh?+oh[1]:rh?+rh[1]:0,$n=!fn&&/gecko\/(\d+)/i.test(Do);$n&&+(/Firefox\/(\d+)/.exec(Do)||[0,0])[1];const sh=!fn&&/Chrome\/(\d+)/.exec(Do),Vt=!!sh,jv=sh?+sh[1]:0,Kt=!fn&&!!br&&/Apple Computer/.test(br.vendor),Oi=Kt&&(/Mobile\/\w+/.test(Do)||!!br&&br.maxTouchPoints>2),Ln=Oi||(br?/Mac/.test(br.platform):!1),Uv=br?/Win/.test(br.platform):!1,Xr=/Android \d/.test(Do),Ua=!!Vv&&"webkitFontSmoothing"in Vv.documentElement.style,i3=Ua?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function a3(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 Qr(t,e){return typeof t=="number"?t:t[e]}function l3(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 Wv(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=Pi(i);continue}let a=i,l=a==s.body,c=l?a3(s):l3(a),u=0,f=0;if(e.top<c.top+Qr(r,"top")?f=-(c.top-e.top+Qr(o,"top")):e.bottom>c.bottom-Qr(r,"bottom")&&(f=e.bottom-e.top>c.bottom-c.top?e.top+Qr(o,"top")-c.top:e.bottom-c.bottom+Qr(o,"bottom")),e.left<c.left+Qr(r,"left")?u=-(c.left-e.left+Qr(o,"left")):e.right>c.right-Qr(r,"right")&&(u=e.right-c.right+Qr(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:Pi(i)}}function c3(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:Hv(t.dom)}}function Hv(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Pi(r));return e}function u3({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Zv(n,r==0?0:r-e)}function Zv(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 Di=null;function d3(t){if(t.setActive)return t.setActive();if(Di)return t.focus(Di);let e=Hv(t);t.focus(Di==null?{get preventScroll(){return Di={preventScroll:!0},!0}}:void 0),Di||(Di=!1,Zv(e,0))}function Kv(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=Gr(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?f3(n,o):!n||r&&n.nodeType==1?{node:t,offset:s}:Kv(n,o)}function f3(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=zo(r,1);if(i.top!=i.bottom&&ih(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 ih(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function h3(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}function p3(t,e,n){let{node:r,offset:o}=Kv(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 m3(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 Yv(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(ih(e,c))return Yv(i,e,c)}}if((s=(s+1)%r)==o)break}return t}function g3(t,e){let n=t.dom.ownerDocument,r,o=0,s=s3(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(!ih(e,c)||(i=Yv(t.dom,e,c),!i))return null}if(Kt)for(let c=i;r&&c;c=Pi(c))c.draggable&&(r=void 0);if(i=h3(i,e),r){if($n&&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;Ua&&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=m3(t,r,o,e))}a==null&&(a=p3(t,i,e));let l=t.docView.nearestDesc(i,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function qv(t){return t.top<t.bottom||t.left<t.right}function zo(t,e){let n=t.getClientRects();if(n.length){let r=n[e<0?0:n.length-1];if(qv(r))return r}return Array.prototype.find.call(n,qv)||t.getBoundingClientRect()}const y3=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function Jv(t,e,n){let{node:r,offset:o,atom:s}=t.docView.domFromPos(e,n<0?-1:1),i=Ua||$n;if(r.nodeType==3)if(i&&(y3.test(r.nodeValue)||(n<0?!o:o==r.nodeValue.length))){let l=zo(Gr(r,o,o),n);if($n&&o&&/\s/.test(r.nodeValue[o-1])&&o<r.nodeValue.length){let c=zo(Gr(r,o-1,o-1),-1);if(c.top==l.top){let u=zo(Gr(r,o,o+1),-1);if(u.top!=l.top)return Wa(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++,Wa(zo(Gr(r,l,c),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&o&&(n<0||o==zn(r))){let l=r.childNodes[o-1];if(l.nodeType==1)return ah(l.getBoundingClientRect(),!1)}if(s==null&&o<zn(r)){let l=r.childNodes[o];if(l.nodeType==1)return ah(l.getBoundingClientRect(),!0)}return ah(r.getBoundingClientRect(),n>=0)}if(s==null&&o&&(n<0||o==zn(r))){let l=r.childNodes[o-1],c=l.nodeType==3?Gr(l,zn(l)-(i?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return Wa(zo(c,1),!1)}if(s==null&&o<zn(r)){let l=r.childNodes[o];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?Gr(l,0,i?0:1):l.nodeType==1?l:null:null;if(c)return Wa(zo(c,-1),!0)}return Wa(zo(r.nodeType==3?Gr(r):r,-n),n>=0)}function Wa(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 ah(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 Gv(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 w3(t,e,n){let r=e.selection,o=n=="up"?r.$from:r.$to;return Gv(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=Jv(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=Gr(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 v3=/[\u0590-\u08ac]/;function k3(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?!v3.test(r.parent.textContent)||!a.modify?n=="left"||n=="backward"?s:i:Gv(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 Xv=null,Qv=null,ek=!1;function b3(t,e,n){return Xv==e&&Qv==n?ek:(Xv=e,Qv=n,ek=n=="up"||n=="down"?w3(t,e,n):k3(t,e,n))}const Vn=0,tk=1,As=2,Sr=3;class Ha{constructor(e,n,r,o){this.parent=e,this.children=n,this.dom=r,this.contentDOM=o,this.dirty=Vn,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>Lt(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 ok){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 nk&&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?Lt(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?Lt(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=Lt(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=Lt(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(($n||Kt)&&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:Lt(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($n&&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&&Kt)&&Ts(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Ts(l.node,l.offset,u.focusNode,u.focusOffset))return;let h=!1;if((c.extend||e==n)&&!(f&&$n)){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?As:tk,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?As:Sr}r=i}this.dirty=As}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?As:tk;n.dirty<r&&(n.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class nk extends Ha{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==Vn&&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 S3 extends Ha{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 Is extends Ha{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=Cs.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Is(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!=Vn){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=Vn}}slice(e,n,r){let o=Is.create(this.parent,this.mark,!0,r),s=this.children,i=this.size;n<i&&(s=ch(s,n,i,r)),e>0&&(s=ch(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 $o extends Ha{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}=Cs.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=ak(u,r,n),c?l=new E3(e,n,r,o,u,f||null,h,c,s,i+1):n.isText?new jc(e,n,r,o,u,h,s):new $o(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==Vn&&e.eq(this.node)&&Uc(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 _3(this,i&&i.node,e);M3(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?Fe.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==As)&&(i&&this.protectLocalComposition(e,i),sk(this.contentDOM,this.children,e),Oi&&A3(this.dom))}localCompositionInfo(e,n){let{from:r,to:o}=e.state.selection;if(!(e.state.selection instanceof ye)||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=I3(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 S3(this,s,n,o);e.input.compositionNodes.push(i),this.children=ch(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=Vn}updateOuterDeco(e){if(Uc(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=ik(this.dom,this.nodeDOM,lh(this.outerDeco,this.node,n),lh(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 rk(t,e,n,r,o){ak(r,e,t);let s=new $o(void 0,t,e,n,r,r,r,o,0);return s.contentDOM&&s.updateChildren(o,0),s}class jc extends $o{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!=Vn&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Vn||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=Vn,!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 jc(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 ok extends Ha{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Vn&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class E3 extends $o{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 sk(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=lk(r),o=!0;r=r.nextSibling}else o=!0,t.insertBefore(a,r);if(i instanceof Is){let l=r?r.previousSibling:t.lastChild;sk(i.contentDOM,i.children,n),r=l?l.nextSibling:t.firstChild}}for(;r;)r=lk(r),o=!0;o&&n.trackWrites==t&&(n.trackWrites=null)}const Za=function(t){t&&(this.nodeName=t)};Za.prototype=Object.create(null);const Ns=[new Za];function lh(t,e,n){if(t.length==0)return Ns;let r=n?Ns[0]:new Za,o=[r];for(let s=0;s<t.length;s++){let i=t[s].type.attrs;if(i){i.nodeName&&o.push(r=new Za(i.nodeName));for(let a in i){let l=i[a];l!=null&&(n&&o.length==1&&o.push(r=new Za(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 ik(t,e,n,r){if(n==Ns&&r==Ns)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=Ns[0]),o=l}C3(o,a||Ns[0],i)}return o}function C3(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 ak(t,e,n){return ik(t,t,Ns,lh(e,n,t.nodeType!=1))}function Uc(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 lk(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class _3{constructor(e,n,r){this.lock=n,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=x3(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=Vn,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=Is.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=As),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 $o){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&&Uc(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=As,f.updateChildren(o,i+1),f.dirty=Vn),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)||!Uc(r,e.outerDeco)||!o.eq(e.innerDeco))return null;let a=$o.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=$o.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 nk(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 Is;)n=e,e=n.children[n.children.length-1];(!e||!(e instanceof jc)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Kt||Vt)&&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 ok(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 x3(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 Is)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 T3(t,e){return t.type.side-e.type.side}function M3(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(T3);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 A3(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 I3(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 ch(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 uh(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(Fc(n)){for(l=i;o&&!o.node;)o=o.parent;let f=o.node;if(o&&f.isAtom&&ae.isSelectable(f)&&o.parent&&!(f.isInline&&r3(n.focusNode,n.focusOffset,o.dom))){let h=o.posBefore;c=new ae(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=fh(t,u,a,f)}return c}function ck(t){return t.editable?t.hasFocus():gk(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function eo(t,e=!1){let n=t.state.selection;if(hk(t,n),!!ck(t)){if(!e&&t.input.mouseDown&&t.input.mouseDown.allowDefault&&Vt){let r=t.domSelectionRange(),o=t.domObserver.currentSelection;if(r.anchorNode&&o.anchorNode&&Ts(r.anchorNode,r.anchorOffset,o.anchorNode,o.anchorOffset)){t.input.mouseDown.delayedSelectionSync=!0,t.domObserver.setCurSelection();return}}if(t.domObserver.disconnectSelection(),t.cursorWrapper)B3(t);else{let{anchor:r,head:o}=n,s,i;uk&&!(n instanceof ye)&&(n.$from.parent.inlineContent||(s=dk(t,n.from)),!n.empty&&!n.$from.parent.inlineContent&&(i=dk(t,n.to))),t.docView.setSelection(r,o,t,e),uk&&(s&&fk(s),i&&fk(i)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&N3(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}}const uk=Kt||Vt&&jv<63;function dk(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(Kt&&o&&o.contentEditable=="false")return dh(o);if((!o||o.contentEditable=="false")&&(!s||s.contentEditable=="false")){if(o)return dh(o);if(s)return dh(s)}}function dh(t){return t.contentEditable="true",Kt&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function fk(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function N3(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(()=>{(!ck(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function B3(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,Lt(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&fn&&Ro<=11&&(n.disabled=!0,n.disabled=!1)}function hk(t,e){if(e instanceof ae){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(pk(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else pk(t)}function pk(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function fh(t,e,n,r){return t.someProp("createSelectionBetween",o=>o(t,e,n))||ye.between(e,n,r)}function mk(t){return t.editable&&!t.hasFocus()?!1:gk(t)}function gk(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 P3(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Ts(e.node,e.offset,n.anchorNode,n.anchorOffset)}function hh(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&&be.findFrom(s,e)}function Lo(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function yk(t,e,n){let r=t.state.selection;if(r instanceof ye)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 Lo(t,new ye(r.$anchor,i))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let o=hh(t.state,e);return o&&o instanceof ae?Lo(t,o):!1}else if(!(Ln&&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?ae.isSelectable(s)?Lo(t,new ae(e<0?t.state.doc.resolve(o.pos-s.nodeSize):o)):Ua?Lo(t,new ye(t.state.doc.resolve(e<0?a:a+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof ae&&r.node.isInline)return Lo(t,new ye(e>0?r.$to:r.$from));{let o=hh(t.state,e);return o?Lo(t,o):!1}}}function Wc(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function Ka(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function Ri(t,e){return e<0?O3(t):D3(t)}function O3(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,s,i=!1;for($n&&n.nodeType==1&&r<Wc(n)&&Ka(n.childNodes[r],-1)&&(i=!0);;)if(r>0){if(n.nodeType!=1)break;{let a=n.childNodes[r-1];if(Ka(a,-1))o=n,s=--r;else if(a.nodeType==3)n=a,r=n.nodeValue.length;else break}}else{if(wk(n))break;{let a=n.previousSibling;for(;a&&Ka(a,-1);)o=n.parentNode,s=Lt(a),a=a.previousSibling;if(a)n=a,r=Wc(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}i?ph(t,n,r):o&&ph(t,o,s)}function D3(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o=Wc(n),s,i;for(;;)if(r<o){if(n.nodeType!=1)break;let a=n.childNodes[r];if(Ka(a,1))s=n,i=++r;else break}else{if(wk(n))break;{let a=n.nextSibling;for(;a&&Ka(a,1);)s=a.parentNode,i=Lt(a)+1,a=a.nextSibling;if(a)n=a,r=0,o=Wc(n);else{if(n=n.parentNode,n==t.dom)break;r=o=0}}}s&&ph(t,s,i)}function wk(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function R3(t,e){for(;t&&e==t.childNodes.length&&!ja(t);)e=Lt(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 z3(t,e){for(;t&&!e&&!ja(t);)e=Lt(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 ph(t,e,n){if(e.nodeType!=3){let s,i;(i=R3(e,n))?(e=i,n=0):(s=z3(e,n))&&(e=s,n=s.nodeValue.length)}let r=t.domSelection();if(!r)return;if(Fc(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&&eo(t)},50)}function vk(t,e){let n=t.state.doc.resolve(e);if(!(Vt||Uv)&&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 kk(t,e,n){let r=t.state.selection;if(r instanceof ye&&!r.empty||n.indexOf("s")>-1||Ln&&n.indexOf("m")>-1)return!1;let{$from:o,$to:s}=r;if(!o.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let i=hh(t.state,e);if(i&&i instanceof ae)return Lo(t,i)}if(!o.parent.inlineContent){let i=e<0?o:s,a=r instanceof _n?be.near(i,e):be.findFrom(i,e);return a?Lo(t,a):!1}return!1}function bk(t,e){if(!(t.state.selection instanceof ye))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 Sk(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function $3(t){if(!Kt||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;Sk(t,r,"true"),setTimeout(()=>Sk(t,r,"false"),20)}return!1}function L3(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function V3(t,e){let n=e.keyCode,r=L3(e);if(n==8||Ln&&n==72&&r=="c")return bk(t,-1)||Ri(t,-1);if(n==46&&!e.shiftKey||Ln&&n==68&&r=="c")return bk(t,1)||Ri(t,1);if(n==13||n==27)return!0;if(n==37||Ln&&n==66&&r=="c"){let o=n==37?vk(t,t.state.selection.from)=="ltr"?-1:1:-1;return yk(t,o,r)||Ri(t,o)}else if(n==39||Ln&&n==70&&r=="c"){let o=n==39?vk(t,t.state.selection.from)=="ltr"?1:-1:1;return yk(t,o,r)||Ri(t,o)}else{if(n==38||Ln&&n==80&&r=="c")return kk(t,-1,r)||Ri(t,-1);if(n==40||Ln&&n==78&&r=="c")return $3(t)||kk(t,1,r)||Ri(t,1);if(r==(Ln?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function mh(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")||Cs.fromSchema(t.state.schema),a=Ik(),l=a.createElement("div");l.appendChild(i.serializeFragment(r,{document:a}));let c=l.firstChild,u,f=0;for(;c&&c.nodeType==1&&(u=Mk[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 Ek(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 K(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=Cs.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=W3(n),Ua&&H3(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")||qr.fromSchema(t.state.schema)).parseSlice(i,{preserveWhitespace:!!(l||u),context:o,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!F3.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)a=Z3(Tk(a,+u[1],+u[2]),u[4]);else if(a=K.maxOpen(j3(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=Tk(a,f,h)}return t.someProp("transformPasted",f=>{a=f(a,t,l)}),a}const F3=/^(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 j3(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&&_k(l,s,a,i[i.length-1],0))i[i.length-1]=c;else{i.length&&(i[i.length-1]=xk(i[i.length-1],s.length));let u=Ck(a,l);i.push(u),o=o.matchType(u.type),s=l}}),i)return D.from(i)}return t}function Ck(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,D.from(t));return t}function _k(t,e,n,r,o){if(o<t.length&&o<e.length&&t[o]==e[o]){let s=_k(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(Ck(n,t,o+1))))}}function xk(t,e){if(e==0)return t;let n=t.content.replaceChild(t.childCount-1,xk(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(D.empty,!0);return t.copy(n.append(r))}function gh(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=gh(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 Tk(t,e,n){return e<t.openStart&&(t=new K(gh(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new K(gh(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}const Mk={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 Ak=null;function Ik(){return Ak||(Ak=document.implementation.createHTMLDocument("title"))}let yh=null;function U3(t){let e=window.trustedTypes;return e?(yh||(yh=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:n=>n})),yh.createHTML(t)):t}function W3(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=Ik().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(t),o;if((o=r&&Mk[r[1].toLowerCase()])&&(t=o.map(s=>"<"+s+">").join("")+t+o.map(s=>"</"+s+">").reverse().join("")),n.innerHTML=U3(t),o)for(let s=0;s<o.length;s++)n=n.querySelector(o[s])||n;return n}function H3(t){let e=t.querySelectorAll(Vt?"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 Z3(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 K(o,s,i)}const nn={},rn={},K3={touchstart:!0,touchmove:!0};class Y3{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 q3(t){for(let e in nn){let n=nn[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=r=>{G3(t,r)&&!vh(t,r)&&(t.editable||!(r.type in rn))&&n(t,r)},K3[e]?{passive:!0}:void 0)}Kt&&t.dom.addEventListener("input",()=>null),wh(t)}function Vo(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function J3(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 wh(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=r=>vh(t,r))})}function vh(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return r?r(t,e)||e.defaultPrevented:!1})}function G3(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 X3(t,e){!vh(t,e)&&nn[e.type]&&(t.editable||!(e.type in rn))&&nn[e.type](t,e)}rn.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!Bk(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Xr&&Vt&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),Oi&&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,Ms(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",r=>r(t,n))||V3(t,n)?n.preventDefault():Vo(t,"key")},rn.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)},rn.keypress=(t,e)=>{let n=e;if(Bk(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||Ln&&n.metaKey)return;if(t.someProp("handleKeyPress",o=>o(t,n))){n.preventDefault();return}let r=t.state.selection;if(!(r instanceof ye)||!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 Hc(t){return{left:t.clientX,top:t.clientY}}function Q3(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}function kh(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 zi(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 ez(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return r&&r.isAtom&&ae.isSelectable(r)?(zi(t,new ae(n)),!0):!1}function tz(t,e){if(e==-1)return!1;let n=t.state.selection,r,o;n instanceof ae&&(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(ae.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?(zi(t,ae.create(t.state.doc,o)),!0):!1}function nz(t,e,n,r,o){return kh(t,"handleClickOn",e,n,r)||t.someProp("handleClick",s=>s(t,e,r))||(o?tz(t,n):ez(t,n))}function rz(t,e,n,r){return kh(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",o=>o(t,e,r))}function oz(t,e,n,r){return kh(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",o=>o(t,e,r))||sz(t,n,r)}function sz(t,e,n){if(n.button!=0)return!1;let r=t.state.doc;if(e==-1)return r.inlineContent?(zi(t,ye.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)zi(t,ye.create(r,a+1,a+1+i.content.size));else if(ae.isSelectable(i))zi(t,ae.create(r,a));else continue;return!0}}function bh(t){return Zc(t)}const Nk=Ln?"metaKey":"ctrlKey";nn.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=bh(t),o=Date.now(),s="singleClick";o-t.input.lastClick.time<500&&Q3(n,t.input.lastClick)&&!n[Nk]&&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(Hc(n));i&&(s=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new iz(t,i,n,!!r)):(s=="doubleClick"?rz:oz)(t,i.pos,i.inside,n)?n.preventDefault():Vo(t,"pointer"))};class iz{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[Nk],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 ae&&c.from<=i&&c.to>i)&&(this.mightDrag={node:s,pos:i,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&$n&&!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)),Vo(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(()=>eo(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(Hc(e))),this.updateAllowDefault(e),this.allowDefault||!n?Vo(this.view,"pointer"):nz(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Kt&&this.mightDrag&&!this.mightDrag.node.isAtom||Vt&&!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)?(zi(this.view,be.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):Vo(this.view,"pointer")}move(e){this.updateAllowDefault(e),Vo(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)}}nn.touchstart=t=>{t.input.lastTouch=Date.now(),bh(t),Vo(t,"pointer")},nn.touchmove=t=>{t.input.lastTouch=Date.now(),Vo(t,"pointer")},nn.contextmenu=t=>bh(t);function Bk(t,e){return t.composing?!0:Kt&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const az=Xr?5e3:-1;rn.compositionstart=rn.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof ye&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Vt&&Uv&&lz(t)))t.markCursor=t.state.storedMarks||n.marks(),Zc(t,!0),t.markCursor=null;else if(Zc(t,!e.selection.empty),$n&&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}Pk(t,az)};function lz(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"}rn.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++,Pk(t,20))};function Pk(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Zc(t),e))}function Ok(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=uz());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function cz(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=t3(e.focusNode,e.focusOffset),r=n3(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 uz(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function Zc(t,e=!1){if(!(Xr&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),Ok(t),e||t.docView&&t.docView.dirty){let n=uh(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 dz(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 Ya=fn&&Ro<15||Oi&&i3<604;nn.copy=rn.cut=(t,e)=>{let n=e,r=t.state.selection,o=n.type=="cut";if(r.empty)return;let s=Ya?null:n.clipboardData,i=r.content(),{dom:a,text:l}=mh(t,i);s?(n.preventDefault(),s.clearData(),s.setData("text/html",a.innerHTML),s.setData("text/plain",l)):dz(t,a),o&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function fz(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function hz(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?qa(t,r.value,null,o,e):qa(t,r.textContent,r.innerHTML,o,e)},50)}function qa(t,e,n,r,o){let s=Ek(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",l=>l(t,o,s||K.empty)))return!0;if(!s)return!1;let i=fz(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 Dk(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," "):""}rn.paste=(t,e)=>{let n=e;if(t.composing&&!Xr)return;let r=Ya?null:n.clipboardData,o=t.input.shiftKey&&t.input.lastKeyCode!=45;r&&qa(t,Dk(r),r.getData("text/html"),o,n)?n.preventDefault():hz(t,n)};class Rk{constructor(e,n,r){this.slice=e,this.move=n,this.node=r}}const pz=Ln?"altKey":"ctrlKey";function zk(t,e){let n=t.someProp("dragCopies",r=>!r(e));return n??!e[pz]}nn.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(Hc(n)),i;if(!(s&&s.pos>=o.from&&s.pos<=(o instanceof ae?o.to-1:o.to))){if(r&&r.mightDrag)i=ae.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=ae.create(t.state.doc,f.posBefore))}}let a=(i||t.state.selection).content(),{dom:l,text:c,slice:u}=mh(t,a);(!n.dataTransfer.files.length||!Vt||jv>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Ya?"Text":"text/html",l.innerHTML),n.dataTransfer.effectAllowed="copyMove",Ya||n.dataTransfer.setData("text/plain",c),t.dragging=new Rk(u,zk(t,n),i)},nn.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)},rn.dragover=rn.dragenter=(t,e)=>e.preventDefault(),rn.drop=(t,e)=>{try{mz(t,e,t.dragging)}finally{t.dragging=null}};function mz(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Hc(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=Ek(t,Dk(e.dataTransfer),Ya?null:e.dataTransfer.getData("text/html"),!1,o);let i=!!(n&&zk(t,e));if(t.someProp("handleDrop",p=>p(t,e,s||K.empty,i))){e.preventDefault();return}if(!s)return;e.preventDefault();let a=s?fv(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&&ae.isSelectable(s.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(s.content.firstChild))l.setSelection(new ae(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(fh(t,h,l.doc.resolve(p)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}nn.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())&&eo(t)},20))},nn.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)},nn.beforeinput=(t,e)=>{if(Vt&&Xr&&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,Ms(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 rn)nn[t]=rn[t];function Ja(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 Kc{constructor(e,n){this.toDOM=e,this.spec=n||Bs,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 on(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof Kc&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Ja(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class Fo{constructor(e,n){this.attrs=e,this.spec=n||Bs}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 on(s,i,this)}valid(e,n){return n.from<n.to}eq(e){return this==e||e instanceof Fo&&Ja(this.attrs,e.attrs)&&Ja(this.spec,e.spec)}static is(e){return e.type instanceof Fo}destroy(){}}class Sh{constructor(e,n){this.attrs=e,this.spec=n||Bs}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 on(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 Sh&&Ja(this.attrs,e.attrs)&&Ja(this.spec,e.spec)}destroy(){}}class on{constructor(e,n,r){this.from=e,this.to=n,this.type=r}copy(e,n){return new on(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 on(e,e,new Kc(n,r))}static inline(e,n,r,o){return new on(e,n,new Fo(r,o))}static node(e,n,r,o){return new on(e,n,new Sh(r,o))}get spec(){return this.type.spec}get inline(){return this.type instanceof Fo}get widget(){return this.type instanceof Kc}}const $i=[],Bs={};class nt{constructor(e,n){this.local=e.length?e:$i,this.children=n.length?n:$i}static create(e,n){return n.length?Yc(n,e,0,Bs):Yt}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==Yt||e.maps.length==0?this:this.mapInner(e,n,0,0,r||Bs)}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?gz(this.children,i||[],e,n,r,o,s):i?new nt(i.sort(Ps),$i):Yt}add(e,n){return n.length?this==Yt?nt.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=Lk(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,Yc(u,a,c+1,Bs)),s+=3}});let i=$k(s?Vk(n):n,-r);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||i.splice(a--,1);return new nt(i.length?this.local.concat(i).sort(Ps):this.local,o||this.children)}remove(e){return e.length==0||this==Yt?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!=Yt?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 nt(o,r):Yt}forChild(e,n){if(this==Yt)return this;if(n.isLeaf)return nt.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 nt(o.sort(Ps),$i);return r?new jo([a,r]):a}return r||Yt}eq(e){if(this==e)return!0;if(!(e instanceof nt)||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 Eh(this.localsInner(e))}localsInner(e){if(this==Yt)return $i;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)}}nt.empty=new nt([],[]),nt.removeOverlap=Eh;const Yt=nt.empty;class jo{constructor(e){this.members=e}map(e,n){const r=this.members.map(o=>o.map(e,n,Bs));return jo.from(r)}forChild(e,n){if(n.isLeaf)return nt.empty;let r=[];for(let o=0;o<this.members.length;o++){let s=this.members[o].forChild(e,n);s!=Yt&&(s instanceof jo?r=r.concat(s.members):r.push(s))}return jo.from(r)}eq(e){if(!(e instanceof jo)||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?Eh(r?n:n.sort(Ps)):$i}static from(e){switch(e.length){case 0:return Yt;case 1:return e[0];default:return new jo(e.every(n=>n instanceof nt)?e:e.reduce((n,r)=>n.concat(r instanceof nt?r:r.members),[]))}}forEachSet(e){for(let n=0;n<this.members.length;n++)this.members[n].forEachSet(e)}}function gz(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 v=a[w+1];if(v<0||h>v+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!=Yt?(a[c]=f,a[c+1]=p,a[c+2]=w):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=yz(a,t,e,n,o,s,i),u=Yc(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 nt(e.sort(Ps),a)}function $k(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 on(o.from+e,o.to+e,o.type))}return n}function yz(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 Lk(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 Vk(t){let e=[];for(let n=0;n<t.length;n++)t[n]!=null&&e.push(t[n]);return e}function Yc(t,e,n,r){let o=[],s=!1;e.forEach((a,l)=>{let c=Lk(t,a,l+n);if(c){s=!0;let u=Yc(c,a,n+l+1,r);u!=Yt&&o.push(l,l+a.nodeSize,u)}});let i=$k(s?Vk(t):t,-n).sort(Ps);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 nt(i,o):Yt}function Ps(t,e){return t.from-e.from||t.to-e.to}function Eh(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),Fk(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),Fk(e,o,r.copy(s.from,r.to)));break}}}return e}function Fk(t,e,n){for(;e<t.length&&Ps(n,t[e])>0;)e++;t.splice(e,0,n)}function Ch(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Yt&&e.push(r)}),t.cursorWrapper&&e.push(nt.create(t.state.doc,[t.cursorWrapper.deco])),jo.from(e)}const wz={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},vz=fn&&Ro<=11;class kz{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 bz{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new kz,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]);fn&&Ro<=11&&r.some(o=>o.type=="childList"&&o.removedNodes.length||o.type=="characterData"&&o.oldValue.length>o.target.nodeValue.length)?this.flushSoon():Kt&&e.composing&&r.some(o=>o.type=="childList"&&o.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),vz&&(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,wz)),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(mk(this.view)){if(this.suppressingSelectionUpdates)return eo(this.view);if(fn&&Ro<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ts(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=Pi(s))n.add(s);for(let s=e.anchorNode;s;s=Pi(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)&&mk(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(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)}}else if($n&&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||Cz(e,f)!=p)&&h.remove()}}}let c=null;s<0&&o&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Fc(r)&&(c=uh(e))&&c.eq(be.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,eo(e),this.currentSelection.set(r),e.scrollToSelection()):(s>-1||o)&&(s>-1&&(e.docView.markDirty(s,i),Sz(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,_z(e,l)),this.handleDOMChange(s,i,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||eo(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(fn&&Ro<=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?Lt(o)+1:0,a=r.localPosFromDOM(e.target,i,-1),l=s&&s.parentNode==e.target?Lt(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 jk=new WeakMap,Uk=!1;function Sz(t){if(!jk.has(t)&&(jk.set(t,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)!==-1)){if(t.requiresGeckoHackNode=$n,Uk)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."),Uk=!0}}function Wk(t,e){let n=e.startContainer,r=e.startOffset,o=e.endContainer,s=e.endOffset,i=t.domAtPos(t.state.selection.anchor);return Ts(i.node,i.offset,o,s)&&([n,r,o,s]=[o,s,n,r]),{anchorNode:n,anchorOffset:r,focusNode:o,focusOffset:s}}function Ez(t,e){if(e.getComposedRanges){let o=e.getComposedRanges(t.root)[0];if(o)return Wk(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?Wk(t,n):null}function Cz(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 _z(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 xz(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}],Fc(l)||c.push({node:l.focusNode,offset:l.focusOffset})),Vt&&t.input.lastKeyCode===8)for(let y=s;y>o;y--){let w=r.childNodes[y-1],v=w.pmViewDesc;if(w.nodeName=="BR"&&!v){s=y;break}if(!v||v.size)break}let f=t.state.doc,h=t.someProp("domParser")||qr.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:Tz,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 Tz(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(Kt&&/^(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||Kt&&/^(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 Mz=/^(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 Az(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.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,M=uh(t,_);if(M&&!t.state.selection.eq(M)){if(Vt&&Xr&&t.input.lastKeyCode===13&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",P=>P(t,Ms(13,"Enter"))))return;let I=t.state.tr.setSelection(M);_=="pointer"?I.setMeta("pointer",!0):_=="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=xz(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=Bz(f.content,c.doc.content,c.from,h,p);if(m&&t.input.domChangeCount++,(Oi&&t.input.lastIOSEnter>Date.now()-225||Xr)&&o.some(_=>_.nodeType==1&&!Mz.test(_.nodeName))&&(!m||m.endA>=m.endB)&&t.someProp("handleKeyDown",_=>_(t,Ms(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!m)if(r&&l instanceof ye&&!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 _=Hk(t,t.state.doc,c.sel);if(_&&!_.eq(t.state.selection)){let M=t.state.tr.setSelection(_);s&&M.setMeta("composition",s),t.dispatch(M)}}return}t.state.selection.from<t.state.selection.to&&m.start==m.endB&&t.state.selection instanceof ye&&(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)),fn&&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),v=g.sameParent(y)&&g.parent.inlineContent&&w.end()>=m.endA;if((Oi&&t.input.lastIOSEnter>Date.now()-225&&(!v||o.some(_=>_.nodeName=="DIV"||_.nodeName=="P"))||!v&&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,Ms(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>m.start&&Nz(u,m.start,m.endA,g,y)&&t.someProp("handleKeyDown",_=>_(t,Ms(8,"Backspace")))){Xr&&Vt&&t.domObserver.suppressSelectionUpdates();return}Vt&&m.endB==m.start&&(t.input.lastChromeDelete=Date.now()),Xr&&!v&&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(_){return _(t,Ms(13,"Enter"))})},20));let b=m.start,S=m.endA,k=_=>{let M=_||t.state.tr.replace(b,S,c.doc.slice(m.start-c.from,m.endB-c.from));if(c.sel){let I=Hk(t,M.doc,c.sel);I&&!(Vt&&t.composing&&I.empty&&(m.start!=m.endB||t.input.lastChromeDelete<Date.now()-100)&&(I.head==b||I.head==M.mapping.map(S)-1)||fn&&I.empty&&I.head==b)&&M.setSelection(I)}return s&&M.setMeta("composition",s),M.scrollIntoView()},E;if(v)if(g.pos==y.pos){fn&&Ro<=11&&g.parentOffset==0&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>eo(t),20));let _=k(t.state.tr.delete(b,S)),M=u.resolve(m.start).marksAcross(u.resolve(m.endA));M&&_.ensureMarks(M),t.dispatch(_)}else if(m.endA==m.endB&&(E=Iz(g.parent.content.cut(g.parentOffset,y.parentOffset),w.parent.content.cut(w.parentOffset,m.endA-w.start())))){let _=k(t.state.tr);E.type=="add"?_.addMark(b,S,E.mark):_.removeMark(b,S,E.mark),t.dispatch(_)}else if(g.parent.child(g.index()).isText&&g.index()==y.index()-(y.textOffset?0:1)){let _=g.parent.textBetween(g.parentOffset,y.parentOffset),M=()=>k(t.state.tr.insertText(_,b,S));t.someProp("handleTextInput",I=>I(t,b,S,_,M))||t.dispatch(M())}else t.dispatch(k());else t.dispatch(k())}function Hk(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:fh(t,e.resolve(n.anchor),e.resolve(n.head))}function Iz(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 Nz(t,e,n,r,o){if(n-e<=o.pos-r.pos||_h(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(_h(s,!0,!0));return!i.parent.isTextblock||i.pos>n||_h(i,!0,!1)<n?!1:r.parent.content.cut(r.parentOffset).eq(i.parent.content)}function _h(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 Bz(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&&Zk(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&&Zk(t.textBetween(s-1,s+1))&&(s+=l?1:-1),i=s+(i-a),a=s}return{start:s,endA:i,endB:a}}function Zk(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 Kk{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 Y3,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Xk),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=Jk(this),qk(this),this.nodeViews=Gk(this),this.docView=rk(this.state.doc,Yk(this),Ch(this),this.dom,this),this.domObserver=new bz(this,(r,o,s,i)=>Az(this,r,o,s,i)),this.domObserver.start(),q3(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&&wh(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Xk),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&&(Ok(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=Gk(this);Oz(p,this.nodeViews)&&(this.nodeViews=p,s=!0)}(a||n.handleDOMEvents!=this._props.handleDOMEvents)&&wh(this),this.editable=Jk(this),qk(this);let l=Ch(this),c=Yk(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&&c3(this);if(i){this.domObserver.stop();let p=f&&(fn||Vt)&&!this.composing&&!o.selection.empty&&!e.selection.empty&&Pz(o.selection,e.selection);if(f){let m=Vt?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=cz(this)),(s||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=rk(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())&&P3(this))?eo(this,p):(hk(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&&u3(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 ae){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&Wv(this,n.getBoundingClientRect(),e)}else Wv(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 Rk(e.slice,e.move,o<0?void 0:ae.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(fn){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&&d3(this.dom),eo(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 g3(this,e)}coordsAtPos(e,n=1){return Jv(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 b3(this,n||this.state,e)}pasteHTML(e,n){return qa(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return qa(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return mh(this,e)}destroy(){this.docView&&(J3(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Ch(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,QR())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return X3(this,e)}domSelectionRange(){let e=this.domSelection();return e?Kt&&this.root.nodeType===11&&o3(this.dom.ownerDocument)==this.dom&&Ez(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Kk.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Yk(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"),[on.node(0,t.state.doc.content.size,e)]}function qk(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:on.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Jk(t){return!t.someProp("editable",e=>e(t.state)===!1)}function Pz(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 Gk(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 Oz(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 Xk(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:"'"},qc={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Dz=typeof navigator<"u"&&/Mac/.test(navigator.platform),Rz=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Ft=0;Ft<10;Ft++)Uo[48+Ft]=Uo[96+Ft]=String(Ft);for(var Ft=1;Ft<=24;Ft++)Uo[Ft+111]="F"+Ft;for(var Ft=65;Ft<=90;Ft++)Uo[Ft]=String.fromCharCode(Ft+32),qc[Ft]=String.fromCharCode(Ft);for(var xh in Uo)qc.hasOwnProperty(xh)||(qc[xh]=Uo[xh]);function zz(t){var e=Dz&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||Rz&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?qc: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 $z=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Lz=typeof navigator<"u"&&/Win/.test(navigator.platform);function Vz(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))$z?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 Fz(t){let e=Object.create(null);for(let n in t)e[Vz(n)]=t[n];return e}function Th(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 jz(t){return new wt({props:{handleKeyDown:Qk(t)}})}function Qk(t){let e=Fz(t);return function(n,r){let o=zz(r),s,i=e[Th(o,r)];if(i&&i(n.state,n.dispatch,n))return!0;if(o.length==1&&o!=" "){if(r.shiftKey){let a=e[Th(o,r,!1)];if(a&&a(n.state,n.dispatch,n))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(Lz&&r.ctrlKey&&r.altKey)&&(s=Uo[r.keyCode])&&s!=o){let a=e[Th(s,r)];if(a&&a(n.state,n.dispatch,n))return!0}}return!1}}var Uz=Object.defineProperty,Mh=(t,e)=>{for(var n in e)Uz(t,n,{get:e[n],enumerable:!0})};function Jc(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 Gc=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:Jc({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}},e1={};Mh(e1,{blur:()=>Wz,clearContent:()=>Hz,clearNodes:()=>Zz,command:()=>Kz,createParagraphNear:()=>Yz,cut:()=>qz,deleteCurrentNode:()=>Jz,deleteNode:()=>Gz,deleteRange:()=>Xz,deleteSelection:()=>Qz,enter:()=>e$,exitCode:()=>t$,extendMarkRange:()=>n$,first:()=>r$,focus:()=>s$,forEach:()=>i$,insertContent:()=>a$,insertContentAt:()=>u$,joinBackward:()=>h$,joinDown:()=>f$,joinForward:()=>p$,joinItemBackward:()=>m$,joinItemForward:()=>g$,joinTextblockBackward:()=>y$,joinTextblockForward:()=>w$,joinUp:()=>d$,keyboardShortcut:()=>k$,lift:()=>b$,liftEmptyBlock:()=>S$,liftListItem:()=>E$,newlineInCode:()=>C$,resetAttributes:()=>_$,scrollIntoView:()=>x$,selectAll:()=>T$,selectNodeBackward:()=>M$,selectNodeForward:()=>A$,selectParentNode:()=>I$,selectTextblockEnd:()=>N$,selectTextblockStart:()=>B$,setContent:()=>P$,setMark:()=>X$,setMeta:()=>Q$,setNode:()=>e4,setNodeSelection:()=>t4,setTextDirection:()=>n4,setTextSelection:()=>r4,sinkListItem:()=>o4,splitBlock:()=>s4,splitListItem:()=>i4,toggleList:()=>a4,toggleMark:()=>l4,toggleNode:()=>c4,toggleWrap:()=>u4,undoInputRule:()=>d4,unsetAllMarks:()=>f4,unsetMark:()=>h4,unsetTextDirection:()=>p4,updateAttributes:()=>m4,wrapIn:()=>g4,wrapInList:()=>y4});var Wz=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window==null?void 0:window.getSelection())==null||n.removeAllRanges())}),!0),Hz=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),Zz=()=>({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=Ti(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},Kz=t=>e=>t(e),Yz=()=>({state:t,dispatch:e})=>Ov(t,e),qz=(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 ye(r.doc.resolve(Math.max(i-1,0)))),!0},Jz=()=>({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 It(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 Gz=t=>({tr:e,state:n,dispatch:r})=>{const o=It(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},Xz=t=>({tr:e,dispatch:n})=>{const{from:r,to:o}=t;return n&&e.delete(r,o),!0},Qz=()=>({state:t,dispatch:e})=>Gf(t,e),e$=()=>({commands:t})=>t.keyboardShortcut("Enter"),t$=()=>({state:t,dispatch:e})=>$R(t,e);function Ah(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function Xc(t,e,n={strict:!0}){const r=Object.keys(e);return r.length?r.every(o=>n.strict?e[o]===t[o]:Ah(e[o])?e[o].test(t[o]):e[o]===t[o]):!0}function t1(t,e,n={}){return t.find(r=>r.type===e&&Xc(Object.fromEntries(Object.keys(n).map(o=>[o,r.attrs[o]])),n))}function n1(t,e,n={}){return!!t1(t,e,n)}function Ih(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),!t1([...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&&n1([...t.parent.child(i-1).marks],e,n);)i-=1,a-=t.parent.child(i).nodeSize;for(;l<t.parent.childCount&&n1([...t.parent.child(l).marks],e,n);)c+=t.parent.child(l).nodeSize,l+=1;return{from:a,to:c}}function to(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 n$=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const s=to(t,r.schema),{doc:i,selection:a}=n,{$from:l,from:c,to:u}=a;if(o){const f=Ih(l,s,e);if(f&&f.from<=c&&f.to>=u){const h=ye.create(i,f.from,f.to);n.setSelection(h)}}return!0},r$=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 r1(t){return t instanceof ye}function Os(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function o1(t,e=null){if(!e)return null;const n=be.atStart(t),r=be.atEnd(t);if(e==="start"||e===!0)return n;if(e==="end")return r;const o=n.from,s=r.to;return e==="all"?ye.create(t,Os(0,o,s),Os(t.content.size,o,s)):ye.create(t,Os(e,o,s),Os(e,o,s))}function s1(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function Qc(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function o$(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var s$=(t=null,e={})=>({editor:n,view:r,tr:o,dispatch:s})=>{e={scrollIntoView:!0,...e};const i=()=>{(Qc()||s1())&&r.dom.focus(),o$()&&!Qc()&&!s1()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),e!=null&&e.scrollIntoView&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(s&&t===null&&!r1(n.state.selection))return i(),!0;const a=o1(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},i$=(t,e)=>n=>t.every((r,o)=>e(r,{...n,index:o})),a$=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),i1=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&&i1(r)}return t};function Ga(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 i1(n)}function Xa(t,e,n){if(t instanceof Yr||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),Xa("",e,n)}if(o){if(n.errorOnInvalidContent){let i=!1,a="";const l=new Hw({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?qr.fromSchema(l).parseSlice(Ga(t),n.parseOptions):qr.fromSchema(l).parse(Ga(t),n.parseOptions),n.errorOnInvalidContent&&i)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const s=qr.fromSchema(e);return n.slice?s.parseSlice(Ga(t),n.parseOptions).content:s.parse(Ga(t),n.parseOptions)}return Xa("",e,n)}function l$(t,e,n){const r=t.steps.length-1;if(r<e)return;const o=t.steps[r];if(!(o instanceof Mt||o instanceof At))return;const s=t.mapping.maps[r];let i=0;s.forEach((a,l,c,u)=>{i===0&&(i=u)}),t.setSelection(be.near(t.doc.resolve(i),n))}var c$=t=>!("type"in t),u$=(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{Xa(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(y){l(y)}try{a=Xa(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((c$(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(),v=y.parentOffset===0,b=w.isText||w.isTextblock,S=w.content.size>0;v&&b&&S&&(u=Math.max(0,u-1)),r.replaceWith(u,f,g)}n.updateSelection&&l$(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},d$=()=>({state:t,dispatch:e})=>DR(t,e),f$=()=>({state:t,dispatch:e})=>RR(t,e),h$=()=>({state:t,dispatch:e})=>Tv(t,e),p$=()=>({state:t,dispatch:e})=>Nv(t,e),m$=()=>({state:t,dispatch:e,tr:n})=>{try{const r=zc(t.doc,t.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},g$=()=>({state:t,dispatch:e,tr:n})=>{try{const r=zc(t.doc,t.selection.$from.pos,1);return r==null?!1:(n.join(r,2),e&&e(n),!0)}catch{return!1}},y$=()=>({state:t,dispatch:e})=>PR(t,e),w$=()=>({state:t,dispatch:e})=>OR(t,e);function a1(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function v$(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))Qc()||a1()?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 k$=t=>({editor:e,view:n,tr:r,dispatch:o})=>{const s=v$(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 Qa(t,e,n={}){const{from:r,to:o,empty:s}=t.selection,i=e?It(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=>Xc(f.node.attrs,n,{strict:!1}));return s?!!c.length:c.reduce((f,h)=>f+h.to-h.from,0)>=l}var b$=(t,e={})=>({state:n,dispatch:r})=>{const o=It(t,n.schema);return Qa(n,o,e)?zR(n,r):!1},S$=()=>({state:t,dispatch:e})=>Dv(t,e),E$=t=>({state:e,dispatch:n})=>{const r=It(t,e.schema);return qR(r)(e,n)},C$=()=>({state:t,dispatch:e})=>Pv(t,e);function eu(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function l1(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 _$=(t,e)=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=eu(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=It(t,r.schema)),a==="mark"&&(i=to(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,l1(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(l1(h.attrs,e))))})})}),l},x$=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),T$=()=>({tr:t,dispatch:e})=>{if(e){const n=new _n(t.doc);t.setSelection(n)}return!0},M$=()=>({state:t,dispatch:e})=>Av(t,e),A$=()=>({state:t,dispatch:e})=>Bv(t,e),I$=()=>({state:t,dispatch:e})=>FR(t,e),N$=()=>({state:t,dispatch:e})=>WR(t,e),B$=()=>({state:t,dispatch:e})=>UR(t,e);function Nh(t,e,n={},r={}){return Xa(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var P$=(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=Nh(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 c1(t,e){const n=to(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 O$(t,e){const n=new yv(t);return e.forEach(r=>{r.steps.forEach(o=>{n.step(o)})}),n}function D$(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 R$(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 Bh(t){return e=>R$(e.$from,t)}function oe(t,e,n){return t.config[e]===void 0&&t.parent?oe(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?oe(t.parent,e,n):null}):t.config[e]}function Ph(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},r=oe(e,"addExtensions",n);return r?[e,...Ph(r())]:e}).flat(10)}function tu(t,e){const n=Cs.fromSchema(e).serializeFragment(t),o=document.implementation.createHTMLDocument().createElement("div");return o.appendChild(n),o.innerHTML}function u1(t){return typeof t=="function"}function Ue(t,e=void 0,...n){return u1(t)?e?t.bind(e)(...n):t(...n):t}function z$(t={}){return Object.keys(t).length===0&&t.constructor===Object}function Li(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 d1(t){const e=[],{nodeExtensions:n,markExtensions:r}=Li(t),o=[...n,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},i=n.filter(c=>c.name!=="text").map(c=>c.name),a=r.map(c=>c.name),l=[...i,...a];return t.forEach(c=>{const u={name:c.name,options:c.options,storage:c.storage,extensions:o},f=oe(c,"addGlobalAttributes",u);if(!f)return;f().forEach(p=>{let m;Array.isArray(p.types)?m=p.types:p.types==="*"?m=l:p.types==="nodes"?m=i:p.types==="marks"?m=a:m=[],m.forEach(g=>{Object.entries(p.attributes).forEach(([y,w])=>{e.push({type:g,name:y,attribute:{...s,...w}})})})})}),o.forEach(c=>{const u={name:c.name,options:c.options,storage:c.storage},f=oe(c,"addAttributes",u);if(!f)return;const h=f();Object.entries(h).forEach(([p,m])=>{const g={...s,...m};typeof(g==null?void 0:g.default)=="function"&&(g.default=g.default()),g!=null&&g.isRequired&&(g==null?void 0:g.default)===void 0&&delete g.default,e.push({type:c.name,name:p,attribute:g})})}),e}function Vi(...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 nu(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)=>Vi(n,r),{})}function $$(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function f1(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):$$(n.getAttribute(i.name));return a==null?s:{...s,[i.name]:a}},{});return{...r,...o}}}}function h1(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&z$(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 m1(t,e){var n;const r=d1(t),{nodeExtensions:o,markExtensions:s}=Li(t),i=(n=o.find(c=>oe(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,v)=>{const b=oe(v,"extendNodeSchema",f);return{...w,...b?b(c):{}}},{}),p=h1({...h,content:Ue(oe(c,"content",f)),marks:Ue(oe(c,"marks",f)),group:Ue(oe(c,"group",f)),inline:Ue(oe(c,"inline",f)),atom:Ue(oe(c,"atom",f)),selectable:Ue(oe(c,"selectable",f)),draggable:Ue(oe(c,"draggable",f)),code:Ue(oe(c,"code",f)),whitespace:Ue(oe(c,"whitespace",f)),linebreakReplacement:Ue(oe(c,"linebreakReplacement",f)),defining:Ue(oe(c,"defining",f)),isolating:Ue(oe(c,"isolating",f)),attrs:Object.fromEntries(u.map(p1))}),m=Ue(oe(c,"parseHTML",f));m&&(p.parseDOM=m.map(w=>f1(w,u)));const g=oe(c,"renderHTML",f);g&&(p.toDOM=w=>g({node:w,HTMLAttributes:nu(w,u)}));const y=oe(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 v=oe(w,"extendMarkSchema",f);return{...y,...v?v(c):{}}},{}),p=h1({...h,inclusive:Ue(oe(c,"inclusive",f)),excludes:Ue(oe(c,"excludes",f)),group:Ue(oe(c,"group",f)),spanning:Ue(oe(c,"spanning",f)),code:Ue(oe(c,"code",f)),attrs:Object.fromEntries(u.map(p1))}),m=Ue(oe(c,"parseHTML",f));m&&(p.parseDOM=m.map(y=>f1(y,u)));const g=oe(c,"renderHTML",f);return g&&(p.toDOM=y=>g({mark:y,HTMLAttributes:nu(y,u)})),[c.name,p]}));return new Hw({topNode:i,nodes:a,marks:l})}function L$(t){const e=t.filter((n,r)=>t.indexOf(n)!==r);return Array.from(new Set(e))}function el(t){return t.sort((n,r)=>{const o=oe(n,"priority")||100,s=oe(r,"priority")||100;return o>s?-1:o<s?1:0})}function Oh(t){const e=el(Ph(t)),n=L$(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 g1(t,e){const n=Oh(t);return m1(n,e)}function ru(t,e){const n=g1(e),r=Yr.fromJSON(n,t);return tu(r.content,n)}function Wo(t,e){const n=g1(e),r=Ga(t);return qr.fromSchema(n).parse(r).toJSON()}function y1(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 V$(t,e){const n={from:0,to:t.content.size};return y1(t,n,e)}function w1(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function F$(t,e){const n=It(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 j$(t,e){const n=eu(typeof e=="string"?e:e.name,t.schema);return n==="node"?F$(t,e):n==="mark"?c1(t,e):{}}function U$(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 W$(t){const e=U$(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 H$(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}})})}),W$(r)}function v1(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(o=>{const s=n.resolve(t),i=Ih(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 tl(t,e){return e.nodes[t]||e.marks[t]||null}function ou(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 Z$=(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 Dh(t,e,n={}){const{empty:r,ranges:o}=t.selection,s=e?to(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(f=>s?s.name===f.type.name:!0).find(f=>Xc(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(s&&g.inlineContent&&!g.type.allowsMarkType(s))return!1;if(!g.isText&&!g.marks.length)return;const w=Math.max(p,y),v=Math.min(m,y+g.nodeSize),b=v-w;i+=b,a.push(...g.marks.map(S=>({mark:S,from:w,to:v})))})}),i===0)return!1;const l=a.filter(f=>s?s.name===f.mark.type.name:!0).filter(f=>Xc(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 K$(t,e,n={}){if(!e)return Qa(t,null,n)||Dh(t,null,n);const r=eu(e,t.schema);return r==="node"?Qa(t,e,n):r==="mark"?Dh(t,e,n):!1}function k1(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function b1(t,e){const{nodeExtensions:n}=Li(e),r=n.find(i=>i.name===t);if(!r)return!1;const o={name:r.name,options:r.options,storage:r.storage},s=Ue(oe(r,"group",o));return typeof s!="string"?!1:s.split(" ").includes("list")}function su(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&&(su(s,{ignoreWhitespace:n,checkChildren:e})||(o=!1))}),o}return!1}function Y$(t){return t instanceof ae}var S1=class kS{constructor(e){this.position=e}static fromJSON(e){return new kS(e.position)}toJSON(){return{position:this.position}}};function q$(t,e){const n=e.mapping.mapResult(t.position);return{position:new S1(n.pos),mapResult:n}}function J$(t){return new S1(t)}function G$(t,e,n){var r;const{selection:o}=e;let s=null;if(r1(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 X$=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const{selection:s}=n,{empty:i,ranges:a}=s,l=to(t,r.schema);if(o)if(i){const c=c1(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 G$(r,n,l)},Q$=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),e4=(t,e={})=>({state:n,dispatch:r,chain:o})=>{const s=It(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})=>$v(s,{...i,...e})(n)?!0:a.clearNodes()).command(({state:a})=>$v(s,{...i,...e})(a,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},t4=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,o=Os(t,0,r.content.size),s=ae.create(r,o);e.setSelection(s)}return!0},n4=(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},r4=t=>({tr:e,dispatch:n})=>{if(n){const{doc:r}=e,{from:o,to:s}=typeof t=="number"?{from:t,to:t}:t,i=ye.atStart(r).from,a=ye.atEnd(r).to,l=Os(o,i,a),c=Os(s,i,a),u=ye.create(r,l,c);e.setSelection(u)}return!0},o4=t=>({state:e,dispatch:n})=>{const r=It(t,e.schema);return XR(r)(e,n)};function E1(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 s4=({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=ou(c,a.node().type.name,a.node().attrs);if(s instanceof ae&&s.node.isBlock)return!a.parentOffset||!Jr(i,a.pos)?!1:(r&&(t&&E1(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:D$(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=f&&h?[{type:h,attrs:u}]:void 0,m=Jr(e.doc,e.mapping.map(a.pos),1,p);if(!p&&!m&&Jr(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 ye&&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&&E1(n,o.extensionManager.splittableMarks),e.scrollIntoView()}return m},i4=(t,e={})=>({tr:n,state:r,dispatch:o,editor:s})=>{var i;const a=It(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 v=l.index(-1)?1:l.index(-2)?2:3;for(let M=l.depth-v;M>=l.depth-3;M-=1)w=D.from(l.node(M).copy(w));const b=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,S={...ou(h,l.node().type.name,l.node().attrs),...e},k=((i=a.contentMatch.defaultType)==null?void 0:i.createAndFill(S))||void 0;w=w.append(D.from(a.createAndFill(null,k)||void 0));const E=l.before(l.depth-(v-1));n.replace(E,l.after(-b),new K(w,4-v,0));let _=-1;n.doc.nodesBetween(E,n.doc.content.size,(M,I)=>{if(_>-1)return!1;M.isTextblock&&M.content.size===0&&(_=I+1)}),_>-1&&n.setSelection(ye.near(n.doc.resolve(_))),n.scrollIntoView()}return!0}const p=c.pos===l.end()?f.contentMatchAt(0).defaultType:null,m={...ou(h,f.type.name,f.attrs),...e},g={...ou(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(!Jr(n.doc,l.pos,2))return!1;if(o){const{selection:w,storedMarks:v}=r,{splittableMarks:b}=s.extensionManager,S=v||w.$to.parentOffset&&w.$from.marks();if(n.split(l.pos,2,y).scrollIntoView(),!S||!o)return!0;const k=S.filter(E=>b.includes(E.type.name));n.ensureMarks(k)}return!0},Rh=(t,e)=>{const n=Bh(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)&&xs(t.doc,n.pos)&&t.join(n.pos),!0},zh=(t,e)=>{const n=Bh(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)&&xs(t.doc,r)&&t.join(r),!0},a4=(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=It(t,i.schema),m=It(e,i.schema),{selection:g,storedMarks:y}=i,{$from:w,$to:v}=g,b=w.blockRange(v),S=y||g.$to.parentOffset&&g.$from.marks();if(!b)return!1;const k=Bh(E=>b1(E.type.name,f))(g);if(b.depth>=1&&k&&b.depth-k.depth<=1){if(k.node.type===p)return c.liftListItem(m);if(b1(k.node.type.name,f)&&p.validContent(k.node.content)&&a)return l().command(()=>(s.setNodeMarkup(k.pos,p),!0)).command(()=>Rh(s,p)).command(()=>zh(s,p)).run()}return!n||!S||!a?l().command(()=>u().wrapInList(p,r)?!0:c.clearNodes()).wrapInList(p,r).command(()=>Rh(s,p)).command(()=>zh(s,p)).run():l().command(()=>{const E=u().wrapInList(p,r),_=S.filter(M=>h.includes(M.type.name));return s.ensureMarks(_),E?!0:c.clearNodes()}).wrapInList(p,r).command(()=>Rh(s,p)).command(()=>zh(s,p)).run()},l4=(t,e={},n={})=>({state:r,commands:o})=>{const{extendEmptyMarkRange:s=!1}=n,i=to(t,r.schema);return Dh(r,i,e)?o.unsetMark(i,{extendEmptyMarkRange:s}):o.setMark(i,e)},c4=(t,e,n={})=>({state:r,commands:o})=>{const s=It(t,r.schema),i=It(e,r.schema),a=Qa(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})},u4=(t,e={})=>({state:n,commands:r})=>{const o=It(t,n.schema);return Qa(n,o,e)?r.lift(o):r.wrapIn(o,e)},d4=()=>({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},f4=()=>({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},h4=(t,e={})=>({tr:n,state:r,dispatch:o})=>{var s;const{extendEmptyMarkRange:i=!1}=e,{selection:a}=n,l=to(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=Ih(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},p4=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},m4=(t,e={})=>({tr:n,state:r,dispatch:o})=>{let s=null,i=null;const a=eu(typeof t=="string"?t:t.name,r.schema);if(!a)return!1;a==="node"&&(s=It(t,r.schema)),a==="mark"&&(i=to(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(v=>{if(i===v.type&&(l=!0,o)){const b=Math.max(w,u),S=Math.min(w+y.nodeSize,f);n.addMark(b,S,i.create({...v.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},g4=(t,e={})=>({state:n,dispatch:r})=>{const o=It(t,n.schema);return HR(o,e)(n,r)},y4=(t,e={})=>({state:n,dispatch:r})=>{const o=It(t,n.schema);return ZR(o,e)(n,r)},w4=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={}}},v4=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},k4=(t,e)=>{if(Ah(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 iu(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=Z$(c)+s;return i.forEach(h=>{if(u)return;const p=k4(f,h.find);if(!p)return;const m=l.state.tr,g=Jc({state:l.state,transaction:m}),y={from:r-(p[0].length-s.length),to:o},{commands:w,chain:v,can:b}=new Gc({editor:n,state:g});h.handler({state:g,range:y,match:p,commands:w,chain:v,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 b4(t){const{editor:e,rules:n}=t,r=new wt({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=tu(D.from(u),i.schema);const{from:f}=l,h=f+u.length;iu({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 iu({editor:e,from:s,to:i,text:a,rules:n,plugin:r})},handleDOMEvents:{compositionend:o=>(setTimeout(()=>{const{$cursor:s}=o.state.selection;s&&iu({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?iu({editor:e,from:i.pos,to:i.pos,text:`
|
|
81
|
+
`,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function S4(t){return Object.prototype.toString.call(t).slice(8,-1)}function au(t){return S4(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function C1(t,e){const n={...t};return au(t)&&au(e)&&Object.keys(e).forEach(r=>{au(e[r])&&au(t[r])?n[r]=C1(t[r],e[r]):n[r]=e[r]}),n}var $h=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{...Ue(oe(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Ue(oe(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>C1(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}},nl=class bS extends $h{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new bS(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 E4(t){return typeof t=="number"}var C4=class{constructor(t){this.find=t.find,this.handler=t.handler}},_4=(t,e,n)=>{if(Ah(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 x4(t){const{editor:e,state:n,from:r,to:o,rule:s,pasteEvent:i,dropEvent:a}=t,{commands:l,chain:c,can:u}=new Gc({editor:e,state:n}),f=[];return n.doc.nodesBetween(r,o,(p,m)=>{var g,y,w,v,b;if((y=(g=p.type)==null?void 0:g.spec)!=null&&y.code||!(p.isText||p.isTextblock||p.isInline))return;const S=(b=(v=(w=p.content)==null?void 0:w.size)!=null?v:p.nodeSize)!=null?b:0,k=Math.max(r,m),E=Math.min(o,m+S);if(k>=E)return;const _=p.isText?p.text||"":p.textBetween(k-m,E-m,void 0,"");_4(_,s.find,i).forEach(I=>{if(I.index===void 0)return;const P=k+I.index+1,V=P+I[0].length,Z={from:n.tr.mapping.map(P),to:n.tr.mapping.map(V)},A=s.handler({state:n,range:Z,match:I,commands:l,chain:c,can:u,pasteEvent:i,dropEvent:a});f.push(A)})}),f.every(p=>p!==null)}var lu=null,T4=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function M4(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=Jc({state:u,transaction:g});if(!(!x4({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 wt({view(f){const h=m=>{var g;r=(g=f.dom.parentElement)!=null&&g.contains(m.target)?f.dom.parentElement:null,r&&(lu=e)},p=()=>{lu&&(lu=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=lu;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"),v=!!w;if(!g&&!y&&!v)return;if(v){let{text:k}=w;typeof k=="string"?k=k:k=tu(D.from(k),p.schema);const{from:E}=w,_=E+k.length,M=T4(k);return l({rule:u,state:p,from:E,to:{b:_},pasteEvt:M})}const b=h.doc.content.findDiffStart(p.doc.content),S=h.doc.content.findDiffEnd(p.doc.content);if(!(!E4(b)||!S||b===S.b))return l({rule:u,state:p,from:b,to:S,pasteEvt:i})}}))}var cu=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=Oh(t),this.schema=m1(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:tl(e.name,this.schema)},r=oe(e,"addCommands",n);return r?{...t,...r()}:t},{})}get plugins(){const{editor:t}=this;return el([...this.extensions].reverse()).flatMap(r=>{const o={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:t,type:tl(r.name,this.schema)},s=[],i=oe(r,"addKeyboardShortcuts",o);let a={};if(r.type==="mark"&&oe(r,"exitable",o)&&(a.ArrowRight=()=>nl.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=jz(a);s.push(l);const c=oe(r,"addInputRules",o);if(k1(r,t.options.enableInputRules)&&c){const h=c();if(h&&h.length){const p=b4({editor:t,rules:h}),m=Array.isArray(p)?p:[p];s.push(...m)}}const u=oe(r,"addPasteRules",o);if(k1(r,t.options.enablePasteRules)&&u){const h=u();if(h&&h.length){const p=M4({editor:t,rules:h});s.push(...p)}}const f=oe(r,"addProseMirrorPlugins",o);if(f){const h=f();s.push(...h)}return s})}get attributes(){return d1(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=Li(this.extensions);return Object.fromEntries(e.filter(n=>!!oe(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:It(n.name,this.schema)},s=oe(n,"addNodeView",o);if(!s)return[];const i=s();if(!i)return[];const a=(l,c,u,f,h)=>{const p=nu(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 el([...this.extensions].reverse()).reduceRight((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:tl(o.name,this.schema)},i=oe(o,"dispatchTransaction",s);return i?a=>{i.call(s,{transaction:a,next:r})}:r},t)}transformPastedHTML(t){const{editor:e}=this;return el([...this.extensions]).reduce((r,o)=>{const s={name:o.name,options:o.options,storage:this.editor.extensionStorage[o.name],editor:e,type:tl(o.name,this.schema)},i=oe(o,"transformPastedHTML",s);return i?(a,l)=>{const c=r(a,l);return i.call(s,c)}:r},t||(r=>r))}get markViews(){const{editor:t}=this,{markExtensions:e}=Li(this.extensions);return Object.fromEntries(e.filter(n=>!!oe(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:to(n.name,this.schema)},s=oe(n,"addMarkView",o);if(!s)return[];const i=(a,l,c)=>{const u=nu(a,r);return s()({mark:a,view:l,inline:c,editor:t,extension:n,HTMLAttributes:u,updateAttributes:f=>{j4(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:tl(e.name,this.schema)};e.type==="mark"&&((n=Ue(oe(e,"keepOnSplit",r)))==null||n)&&this.splittableMarks.push(e.name);const o=oe(e,"onBeforeCreate",r),s=oe(e,"onCreate",r),i=oe(e,"onUpdate",r),a=oe(e,"onSelectionUpdate",r),l=oe(e,"onTransaction",r),c=oe(e,"onFocus",r),u=oe(e,"onBlur",r),f=oe(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)})}};cu.resolve=Oh,cu.sort=el,cu.flatten=Ph;var A4={};Mh(A4,{ClipboardTextSerializer:()=>_1,Commands:()=>x1,Delete:()=>T1,Drop:()=>M1,Editable:()=>A1,FocusEvents:()=>N1,Keymap:()=>B1,Paste:()=>P1,Tabindex:()=>O1,TextDirection:()=>D1,focusEventsPluginKey:()=>I1});var qe=class SS extends $h{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new SS(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},_1=qe.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new wt({key:new tn("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=w1(n);return y1(r,{from:i,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:l})}}})]}}),x1=qe.create({name:"commands",addCommands(){return{...e1}}}),T1=qe.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=O$(t.before,[t,...e]);H$(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 nr){const w=h.slice(m).map(p.from,-1),v=h.slice(m).map(p.to),b=h.invert().map(w,-1),S=h.invert().map(v),k=(g=u.doc.nodeAt(w-1))==null?void 0:g.marks.some(_=>_.eq(p.mark)),E=(y=u.doc.nodeAt(v))==null?void 0:y.marks.some(_=>_.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:v},partial:!!(E||k),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()}}),M1=qe.create({name:"drop",addProseMirrorPlugins(){return[new wt({key:new tn("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),A1=qe.create({name:"editable",addProseMirrorPlugins(){return[new wt({key:new tn("editable"),props:{editable:()=>this.editor.options.editable}})]}}),I1=new tn("focusEvents"),N1=qe.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new wt({key:I1,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}}}})]}}),B1=qe.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:be.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 Qc()||a1()?s:o},addProseMirrorPlugins(){return[new wt({key:new tn("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=be.atStart(e.doc).from,c=be.atEnd(e.doc).to;if(s||!(i===l&&a===c)||!su(n.doc))return;const h=n.tr,p=Jc({state:n,transaction:h}),{commands:m}=new Gc({editor:this.editor,state:p});if(m.clearNodes(),!!h.steps.length)return h}})]}}),P1=qe.create({name:"paste",addProseMirrorPlugins(){return[new wt({key:new tn("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),O1=qe.create({name:"tabindex",addProseMirrorPlugins(){return[new wt({key:new tn("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),D1=qe.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=Li(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 wt({key:new tn("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),I4=class dl{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 dl(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 dl(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 dl(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=n.isInline,a=this.pos+r+(s?0:1);if(a<0||a>this.resolvedPos.doc.nodeSize-2)return;const l=this.resolvedPos.doc.resolve(a);if(!o&&!i&&l.depth<=this.depth)return;const c=new dl(l,this.editor,o,o||i?n:null);o&&(c.actualDepth=this.depth+1),e.push(c)}),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)}},N4=`.ProseMirror {
|
|
82
82
|
position: relative;
|
|
83
83
|
}
|
|
84
84
|
|
|
@@ -148,24 +148,24 @@ img.ProseMirror-separator {
|
|
|
148
148
|
|
|
149
149
|
.ProseMirror-focused .ProseMirror-gapcursor {
|
|
150
150
|
display: block;
|
|
151
|
-
}`;function
|
|
151
|
+
}`;function B4(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 P4=class extends w4{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:q$,createMappablePosition:J$},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=o1(n,this.options.autofocus);this.editorState=Ni.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=B4(N4,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=u1(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?[A1,_1.configure({blockSeparator:(n=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:n.blockSeparator}),x1,N1,B1,O1,M1,P1,T1,D1.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 cu(o,this)}createCommandManager(){this.commandManager=new Gc({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=Nh(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=Nh(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,i=n.transformPastedHTML,a=this.extensionManager.transformPastedHTML(i);this.editorView=new Kk(e,{...n,attributes:{role:"textbox",...n==null?void 0:n.attributes},dispatchTransaction:s,transformPastedHTML:a,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const l=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(l),this.prependClass(),this.injectCSS();const c=this.view.dom;c.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 j$(this.state,e)}isActive(e,n){const r=typeof e=="string"?e:null,o=typeof e=="string"?n:e;return K$(this.state,r,o)}getJSON(){return this.state.doc.toJSON()}getHTML(){return tu(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:n=`
|
|
152
152
|
|
|
153
|
-
`,textSerializers:r={}}=e||{};return
|
|
153
|
+
`,textSerializers:r={}}=e||{};return V$(this.state.doc,{blockSeparator:n,textSerializers:{...w1(this.schema),...r}})}get isEmpty(){return su(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 I4(n,this)}get $doc(){return this.$pos(0)}};function uu(t){return new v4({find:t.find,handler:({state:e,range:n,match:r})=>{const o=Ue(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(v1(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 O4={};Mh(O4,{createAtomBlockMarkdownSpec:()=>D4,createBlockMarkdownSpec:()=>R4,createInlineMarkdownSpec:()=>L4,parseAttributes:()=>Lh,parseIndentedBlocks:()=>V4,renderNestedMarkdownContent:()=>F4,serializeAttributes:()=>Vh});function Lh(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 Vh(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 D4(t){const{nodeName:e,name:n,parseAttributes:r=Lh,serializeAttributes:o=Vh,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(v=>!(v 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 R4(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=Lh,serializeAttributes:s=Vh,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,v=""]=y,b=o(v);let S=1;const k=w.length;let E="";const _=/^:::([\w-]*)(\s.*)?/gm,M=f.slice(k);for(_.lastIndex=0;;){const I=_.exec(M);if(I===null)break;const P=I.index,V=I[1];if(!((m=I[2])!=null&&m.endsWith(":::"))){if(V)S+=1;else if(S-=1,S===0){const Z=M.slice(0,P);E=Z.trim();const A=f.slice(0,k+P+I[0].length);let F=[];if(E)if(a==="block")for(F=p.blockTokens(Z),F.forEach(Y=>{Y.text&&(!Y.tokens||Y.tokens.length===0)&&(Y.tokens=p.inlineTokens(Y.text))});F.length>0;){const Y=F[F.length-1];if(Y.type==="paragraph"&&(!Y.text||Y.text.trim()===""))F.pop();else break}else F=p.inlineTokens(E);return{type:e,raw:A,attributes:b,content:E,tokens:F}}}}}},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
|
|
159
|
+
:::`}}}function z4(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 $4(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function L4(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=z4,serializeAttributes:s=$4,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="",v="";if(a){const[,S]=y;v=S}else{const[,S,k]=y;v=S,w=k||""}const b=o(v.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 V4(t,e,n){var r,o,s,i;const a=t.split(`
|
|
160
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
|
|
163
|
-
`,u+=1;continue}else break}if((((i=(s=
|
|
164
|
-
`,u+=1;else break}let
|
|
165
|
-
`);
|
|
162
|
+
`;const w=[y];for(u+=1;u<a.length;){const k=a[u];if(k.trim()===""){const _=a.slice(u+1).findIndex(P=>P.trim()!=="");if(_===-1)break;if((((o=(r=a[u+1+_].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:o.length)||0)>g){w.push(k),c=`${c}${k}
|
|
163
|
+
`,u+=1;continue}else break}if((((i=(s=k.match(/^(\s*)/))==null?void 0:s[1])==null?void 0:i.length)||0)>g)w.push(k),c=`${c}${k}
|
|
164
|
+
`,u+=1;else break}let v;const b=w.slice(1);if(b.length>0){const k=b.map(E=>E.slice(g+f)).join(`
|
|
165
|
+
`);k.trim()&&(e.customNestedParser?v=e.customNestedParser(k):v=n.blockTokens(k))}const S=e.createToken(m,v);l.push(S)}if(l.length!==0)return{items:l,raw:c}}function F4(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
167
|
`);l.push(f)}}),l.join(`
|
|
168
|
-
`)}function
|
|
168
|
+
`)}function j4(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 Fh=class ES extends $h{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new ES(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function du(t){return new C4({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:o})=>{const s=Ue(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(v1(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 R1(t){return d.customRef((e,n)=>({get(){return e(),t},set(r){t=r,requestAnimationFrame(()=>{requestAnimationFrame(()=>{n()})})}}))}var U4=class extends P4{constructor(t={}){return super(t),this.contentComponent=null,this.appContext=null,this.reactiveState=R1(this.view.state),this.reactiveExtensionStorage=R1(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}},W4=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 H4=Fh.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,`
|
|
169
169
|
|
|
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"})});
|
|
170
|
+
`):""}),z1=H4,$1=" ",Z4=" ",K4=Fh.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",Vi(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];if(n.length===1&&n[0].type==="image")return e.parseChildren([n[0]]);const r=e.parseInline(n);return r.length===1&&r[0].type==="text"&&(r[0].text===$1||r[0].text===Z4)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(t,e)=>{if(!t)return"";const n=Array.isArray(t.content)?t.content:[];return n.length===0?$1:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),L1=K4,Y4=Fh.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),V1=Y4,F1=(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]},q4=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,J4=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,G4=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,X4=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Q4=nl.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 F1("strong",{...Vi(this.options.HTMLAttributes,t),children:F1("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[uu({find:q4,type:this.type}),uu({find:G4,type:this.type})]},addPasteRules(){return[du({find:J4,type:this.type}),du({find:X4,type:this.type})]}}),j1=Q4,eL=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,tL=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,nL=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,rL=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,oL=nl.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",Vi(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[uu({find:eL,type:this.type}),uu({find:nL,type:this.type})]},addPasteRules(){return[du({find:tL,type:this.type}),du({find:rL,type:this.type})]}}),U1=oL,sL=nl.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",Vi(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()}}}),W1=sL,iL=qe.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")}}}),H1=iL,aL=20,Z1=(t,e=0)=>{const n=[];return!t.children.length||e>aL||Array.from(t.children).forEach(r=>{r.tagName==="SPAN"?n.push(r):r.children.length&&n.push(...Z1(r,e+1))}),n},lL=t=>{if(!t.children.length)return;const e=Z1(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}`)})},jh=nl.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&lL(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Vi(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}}}}),cL=qe.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()}}}),K1=qe.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()}}}),uL=qe.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()}}}),dL=qe.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()}}}),fL=qe.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()}}});qe.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(cL.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(K1.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(uL.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(dL.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(fL.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(jh.configure(this.options.textStyle)),t}});var Y1=K1;function hL(t={}){return new wt({view(e){return new pL(e,t)}})}class pL{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=fv(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 ot extends be{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return ot.valid(r)?new ot(r):be.near(r)}content(){return K.empty}eq(e){return e instanceof ot&&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 ot(e.resolve(n.pos))}getBookmark(){return new Uh(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!mL(e)||!gL(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&&ot.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(ot.valid(l))return l}for(;;){let i=n>0?s.firstChild:s.lastChild;if(!i){if(s.isAtom&&!s.isText&&!ae.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(ot.valid(a))return a}return null}}}ot.prototype.visible=!1,ot.findFrom=ot.findGapCursorFrom,be.jsonID("gapcursor",ot);class Uh{constructor(e){this.pos=e}map(e){return new Uh(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return ot.valid(n)?new ot(n):be.near(n)}}function q1(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function mL(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||q1(o.type))return!0;if(o.inlineContent)return!1}}return!0}function gL(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||q1(o.type))return!0;if(o.inlineContent)return!1}}return!0}function yL(){return new wt({props:{decorations:bL,createSelectionBetween(t,e,n){return e.pos==n.pos&&ot.valid(n)?new ot(n):null},handleClick:vL,handleKeyDown:wL,handleDOMEvents:{beforeinput:kL}}})}const wL=Qk({ArrowLeft:fu("horiz",-1),ArrowRight:fu("horiz",1),ArrowUp:fu("vert",-1),ArrowDown:fu("vert",1)});function fu(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 ye){if(!s.endOfTextblock(n)||a.depth==0)return!1;l=!1,a=r.doc.resolve(e>0?a.after():a.before())}let c=ot.findGapCursorFrom(a,e,l);return c?(o&&o(r.tr.setSelection(new ot(c))),!0):!1}}function vL(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!ot.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&ae.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new ot(r))),!0)}function kL(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof ot))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 K(o,0,0));return s.setSelection(ye.near(s.doc.resolve(n.pos+1))),t.dispatch(s),!1}function bL(t){if(!(t.selection instanceof ot))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",nt.create(t.doc,[on.widget(t.selection.head,e,{key:"gapcursor"})])}var hu=200,Nt=function(){};Nt.prototype.append=function(e){return e.length?(e=Nt.from(e),!this.length&&e||e.length<hu&&this.leafAppend(e)||this.length<hu&&e.leafPrepend(this)||this.appendInner(e)):this},Nt.prototype.prepend=function(e){return e.length?Nt.from(e).append(this):this},Nt.prototype.appendInner=function(e){return new SL(this,e)},Nt.prototype.slice=function(e,n){return e===void 0&&(e=0),n===void 0&&(n=this.length),e>=n?Nt.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))},Nt.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)},Nt.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)},Nt.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},Nt.from=function(e){return e instanceof Nt?e:e&&e.length?new J1(e):Nt.empty};var J1=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<=hu)return new e(this.values.concat(o.flatten()))},e.prototype.leafPrepend=function(o){if(this.length+o.length<=hu)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}(Nt);Nt.empty=new J1([]);var SL=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}(Nt);const EL=500;class rr{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 Er(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 Er(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 rr(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 Er(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>_L&&(a=CL(a,c),i-=c),new rr(a.append(s),i)}remapping(e,n){let r=new za;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 rr(this.items.append(e.map(n=>new Er(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 Er(m,g,y))}else r.push(new Er(m))},o);let c=[];for(let h=n;h<i;h++)c.push(new Er(s.maps[h]));let u=this.items.slice(0,o).append(c).append(r),f=new rr(u,a);return f.emptyItemCount()>EL&&(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 Er(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 rr(Nt.from(o.reverse()),s)}}rr.empty=new rr(Nt.empty,0);function CL(t,e){let n;return t.forEach((r,o)=>{if(r.selection&&e--==0)return n=o,!1}),t.slice(n)}class Er{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 Er(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 _L=20;function xL(t,e,n,r){let o=n.getMeta(Ds),s;if(o)return o.historyState;n.getMeta(AL)&&(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(Ds))return i.getMeta(Ds).redo?new Ho(t.done.addTransform(n,void 0,r,pu(e)),t.undone,G1(n.mapping.maps),t.prevTime,t.prevComposition):new Ho(t.done,t.undone.addTransform(n,void 0,r,pu(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||!TL(n,t.prevRanges)),c=i?Wh(t.prevRanges,n.mapping):G1(n.mapping.maps);return new Ho(t.done.addTransform(n,l?e.selection.getBookmark():void 0,r,pu(e)),rr.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),Wh(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new Ho(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),Wh(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function TL(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 G1(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 Wh(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 ML(t,e,n){let r=pu(e),o=Ds.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(Ds,{redo:n,historyState:l})}let Hh=!1,X1=null;function pu(t){let e=t.plugins;if(X1!=e){Hh=!1,X1=e;for(let n=0;n<e.length;n++)if(e[n].spec.historyPreserveItems){Hh=!0;break}}return Hh}const Ds=new tn("history"),AL=new tn("closeHistory");function IL(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new wt({key:Ds,state:{init(){return new Ho(rr.empty,rr.empty,null,0,-1)},apply(e,n,r){return xL(n,r,e,t)}},config:t,props:{handleDOMEvents:{beforeinput(e,n){let r=n.inputType,o=r=="historyUndo"?eb:r=="historyRedo"?tb:null;return!o||!e.editable?!1:(n.preventDefault(),o(e.state,e.dispatch))}}}})}function Q1(t,e){return(n,r)=>{let o=Ds.getState(n);if(!o||(t?o.undone:o.done).eventCount==0)return!1;if(r){let s=ML(o,n,t);s&&r(e?s.scrollIntoView():s)}return!0}}const eb=Q1(!1,!0),tb=Q1(!0,!0);qe.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 wt({key:new tn("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)}})]}}),qe.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[hL(this.options)]}}),qe.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new wt({key:new tn("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,s=[];if(!n||!r)return nt.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(on.node(c,c+l.nodeSize,{class:this.options.className}))}),nt.create(t,s)}}})]}}),qe.create({name:"gapCursor",addProseMirrorPlugins(){return[yL()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Ue(oe(t,"allowGapCursor",n)))!=null?e:null}}});var nb="placeholder";function NL(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}qe.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:nb,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${NL(this.options.dataAttribute)}`:`data-${nb}`;return[new wt({key:new tn("placeholder"),props:{decorations:({doc:e,selection:n})=>{const r=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:o}=n,s=[];if(!r)return null;const i=this.editor.isEmpty;return e.descendants((a,l)=>{const c=o>=l&&o<=l+a.nodeSize,u=!a.isLeaf&&su(a);if((c||!this.options.showOnlyCurrent)&&u){const f=[this.options.emptyNodeClass];i&&f.push(this.options.emptyEditorClass);const h=on.node(l,l+a.nodeSize,{class:f.join(" "),[t]:typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:a,pos:l,hasAnchor:c}):this.options.placeholder});s.push(h)}return this.options.includeChildren}),nt.create(e,s)}}})]}}),qe.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new wt({key:new tn("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||Y$(n.selection)||t.view.dragging?null:nt.create(n.doc,[on.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function rb({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(e==null?void 0:e.type)===t}qe.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new tn(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 wt({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!rb({node:i,types:r})},apply:(o,s)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return s;const i=o.doc.lastChild;return!rb({node:i,types:r})}}})]}});var BL=qe.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>eb(t,e),redo:()=>({state:t,dispatch:e})=>tb(t,e)}},addProseMirrorPlugins(){return[IL(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 Zo(t,e){const n=d.inject(Rn);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(R(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 ob(){const t=d.inject(Rn);if(!t)throw new Error("useImageCreation must be used within a WovenCanvas component");const{nextEditorTick:e}=ut();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=Wt.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);ee(f,y,T);const w=T.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,Wt.snapPosition(f,w.position);const v=crypto.randomUUID();ee(f,y,as);const b=as.write(f,y);b.identifier=v,b.uploadState=mr.Pending,ee(f,y,Qi);const S=Qi.write(f,y);return S.width=u.width,S.height=u.height,S.alt=s.name,ee(f,y,me,{id:crypto.randomUUID()}),(t==null?void 0:t.getAssetManager())&&o(y,v,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=as.write(c,s);u.uploadState=mr.Complete}catch{const c=await e(),u=as.write(c,s);u.uploadState=mr.Failed}}return{getImageDimensions:n,createImageBlock:r}}function sb(t){const e=d.inject(Rn);if(!e)throw new Error("useQuery must be used within a WovenCanvas component");const n=d.shallowRef([]),r=ie(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 v=e.subscribeComponent(f,y.name,b=>{w.value=b});g.push(v)}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 jt(t){const e=d.inject(Rn);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 PL(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 Zh(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:v,height:b}=PL(y,w,-i),S=n.value.left,k=n.value.top;return{width:v,height:b,left:p.x-v/2-S,top:p.y-b/2-k}}function ib(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 rl(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 Kh(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 ab(t){const e=Kh(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 lb(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 cb(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 hn=d.shallowRef(null),Yh=d.shallowRef(null),qh=d.shallowRef(null),Ko=d.ref(0);function ol(){const t={hasEditor:d.computed(()=>hn.value!==null),isBold:d.computed(()=>{var o;return Ko.value,((o=hn.value)==null?void 0:o.isActive("bold"))??!1}),isItalic:d.computed(()=>{var o;return Ko.value,((o=hn.value)==null?void 0:o.isActive("italic"))??!1}),isUnderline:d.computed(()=>{var o;return Ko.value,((o=hn.value)==null?void 0:o.isActive("underline"))??!1}),alignment:d.computed(()=>{Ko.value;const o=hn.value;return o?o.isActive({textAlign:"center"})?"center":o.isActive({textAlign:"right"})?"right":o.isActive({textAlign:"justify"})?"justify":"left":"left"}),color:d.computed(()=>{Ko.value;const o=hn.value;if(!o)return null;const i=o.getAttributes("textStyle").color??null;return i?ib(i):null})},e={toggleBold(){const o=hn.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=hn.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=hn.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=hn.value;s&&s.chain().selectAll().setTextAlign(o).run()},setColor(o){const s=hn.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){hn.value=o,qh.value=s,Yh.value=i,o.on("selectionUpdate",()=>{Ko.value++}),o.on("transaction",()=>{Ko.value++})}function r(){hn.value=null,qh.value=null,Yh.value=null}return{editor:hn,blockElement:Yh,textElement:qh,state:t,commands:e,updateCounter:Ko,register:n,unregister:r}}const Fn=[z1,L1,V1,jh,Y1,j1,U1,W1,H1.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:"left"})];function OL(t){return t.type==="text"&&typeof t.text=="string"}function Rs(t,e){if(OL(t)){e(t);return}if(t.content)for(const n of t.content)Rs(n,e)}function Jh(t,e){if(t.type==="paragraph"){e(t);return}if(t.content)for(const n of t.content)Jh(n,e)}function DL(t,e){var n;return((n=t.marks)==null?void 0:n.some(r=>r.type===e))??!1}function RL(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?ib(n):null}function zL(t,e){if(!t.trim())return!1;const n=Wo(t,Fn);let r=!1,o=!0,s=0;return Rs(n,i=>{s++,DL(i,e)?r=!0:o=!1}),s===0?!1:o?!0:r?null:!1}function $L(t){if(!t.trim())return"left";const e=Wo(t,Fn);let n="left";return Jh(e,r=>{var s;const o=(s=r.attrs)==null?void 0:s.textAlign;o&&(n=o)}),n}function LL(t){if(!t.trim())return null;const e=Wo(t,Fn);let n=null;return Rs(e,r=>{n===null&&(n=RL(r))}),n}function Gh(t,e){if(!t.trim())return t;const n=Wo(t,Fn);return Rs(n,r=>{const o=r.marks??[];o.findIndex(i=>i.type===e)===-1&&(r.marks=[...o,{type:e}])}),ru(n,Fn)}function Xh(t,e){if(!t.trim())return t;const n=Wo(t,Fn);return Rs(n,r=>{const o=r.marks??[];r.marks=o.filter(s=>s.type!==e)}),ru(n,Fn)}function VL(t,e){if(!t.trim())return t;const n=Wo(t,Fn);return Jh(n,r=>{r.attrs={...r.attrs,textAlign:e}}),ru(n,Fn)}function FL(t,e){if(!t.trim())return t;const n=Wo(t,Fn);return Rs(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}}]}),ru(n,Fn)}function ub(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 db(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=Zh(o,e,n);return o.remove(),a}function fb(t){const{nextEditorTick:e}=ut(),n=Zo(t,gt),r=jt(we),o=jt(_t),s=ol(),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?Wo(h.content,Fn):null;if(p){let m=!1;if(Rs(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=$L(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=LL(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=zL(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?Xh(h,"bold"):Gh(h,"bold"))},toggleItalic(){u(h=>i.isItalic.value?Xh(h,"italic"):Gh(h,"italic"))},toggleUnderline(){u(h=>i.isUnderline.value?Xh(h,"underline"):Gh(h,"underline"))},setAlignment(h){f(p=>VL(p,h))},setColor(h){f(p=>FL(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 v=ub(y);if(v){const b=db(v,r,o,h(w));g.push({entityId:y,...b})}}e(y=>{for(const w of m)p(gt.write(y,w));for(const{entityId:w,width:v,height:b,left:S,top:k}of g){const E=T.write(y,w);E.size=[v,b],E.position=[S,k]}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),v=ub(g);if(v){const b=db(v,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:v,height:b,left:S,top:k}of m){const E=gt.write(g,y);if(E.content=w,v>0&&b>0){const _=T.write(g,y);_.size=[v,b],_.position=[S,k]}}})}function f(h){const p=d.toValue(t);e(m=>{for(const g of p){const y=gt.write(m,g);y.content=h(y.content)}})}return{state:i,commands:l}}function Cr(t){const e=ol(),n=fb(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 Qh(t){const e=jt(we),n=jt(_t),r=jt(af),o=jt(Xn),{nextEditorTick:s}=ut();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=T.read(u,h),v=Math.abs(w.size[0]-g)>.5,b=Math.abs(w.size[1]-y)>.5;if(!v&&!b)return;const S=T.write(u,h);S.size=[g,y],S.position=[f.left,f.top],r.value.transformBoxId!==null&&nf.spawn(u,{transformBoxId:r.value.transformBoxId})}d.watch(()=>o.value,()=>{const u=t.containerRef.value;u&&i&&(a=Zh(u,e,n)),s(f=>{const h=jL(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(gt.read(p,m).content!==f){const y=gt.write(p,m);y.content=f}l(p,h)})}return{handleEditEnd:c}}function jL(t){const e=Xn.read(t);return e.state===_e.Dragging&&e.draggedEntity!==null&&R(t,e.draggedEntity,Ye)&&Ye.read(t,e.draggedEntity).kind===Gn.Stretch}function ep(){const t=d.inject(_f);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 UL=500,WL=1500;function hb(){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},UL)}function a(){s(),e.value=!1,t.value=null,n.value&&(o=setTimeout(()=>{n.value=!1,o=null},WL))}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 Yo(){const t=d.inject(F0);if(!t)throw new Error("useTooltipSingleton must be used within a WovenCanvas component");return t}const HL={key:1},ZL=["innerHTML"],KL=50,YL=300,mu=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 k;const r=t,o=n,s=Tt(r.entityId,gt),i=jt(we),a=jt(_t),l=ol(),{nextEditorTick:c}=ut(),u=jt(On),f=d.ref(null);e({editableTextRef:f});const h=d.ref(((k=s.value)==null?void 0:k.content)??""),p=d.shallowRef(null);function m(E,_){var P;const M=s.value;return!M||M.constrainWidth||(((P=_.clipboardData)==null?void 0:P.getData("text/plain"))??"").length>KL&&c(V=>{const Z=gt.write(V,r.entityId);Z.constrainWidth=!0;const A=T.read(V,r.entityId),F=Math.max(A.size[0],YL),Y=T.write(V,r.entityId);Y.size=[F,A.size[1]],sy.spawn(V),bi.spawn(V)}),!1}function g(){var E,_;return new U4({extensions:[z1,L1,V1,jh,Y1,j1,U1,W1,H1.configure({types:["paragraph"],alignments:["left","center","right","justify"],defaultAlignment:((E=s.value)==null?void 0:E.defaultAlignment)??"left"}),BL],content:((_=s.value)==null?void 0:_.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 P;const _=(P=u.value)==null?void 0:P.position,M=a.value;await d.nextTick(),await new Promise(V=>requestAnimationFrame(V));const I=f.value;if(_&&M&&I){const V=_[0]+M.left,Z=_[1]+M.top,A=E.view.posAtCoords({left:V,top:Z});if(A){E.chain().focus().setTextSelection(A.pos).run();return}}E.commands.focus("start")}function w(E){let _=E.getHTML();const I=_.replace(/<[^>]*>/g,"").trim().length>0;I||(_=""),h.value=_,c(P=>{var Y,ce;const V=Xt(P,r.block.tag);if(!I&&((Y=V.editOptions)!=null&&Y.removeWhenTextEmpty)){st(P,r.entityId);return}const Z=(ce=f.value)==null?void 0:ce.closest(".wov-block"),A=(Z==null?void 0:Z.firstElementChild)??f.value;if(!A){console.warn("EditableText: no element to measure");return}const F=Zh(A,i,a);o("editEnd",{content:_,...F})})}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 v=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,_)=>(d.openBlock(),d.createElementBlock("div",{ref_key:"editableTextRef",ref:f,class:"wov-editable-text",style:d.normalizeStyle(v.value),onKeydown:b,onPointerdown:S,onPointermove:S,onPointerup:S},[p.value?(d.openBlock(),d.createBlock(d.unref(W4),{key:0,editor:p.value},null,8,["editor"])):(d.openBlock(),d.createElementBlock("div",HL,[d.createElementVNode("div",{class:"tiptap ProseMirror",innerHTML:h.value},null,8,ZL)]))],36))}}),qL={class:"wov-shape-svg",viewBox:"0 0 100 100",preserveAspectRatio:"none"},JL=["d","fill","stroke","stroke-width","stroke-dasharray"],pb=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=Tt(e.entityId,Nn),r=Tt(e.entityId,cs),o=d.ref(null),s={[mt.Top]:"flex-start",[mt.Center]:"center",[mt.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===Ct.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)??Ct.Solid}),u=d.computed(()=>{var g;return Ba[((g=n.value)==null?void 0:g.kind)??"rectangle"]??Ba.rectangle}),f=d.computed(()=>{const g=l.value;switch(c.value){case Ct.Dashed:return`${g*3} ${g*3}`;case Ct.None:return"";case Ct.Solid:default:return""}}),h=d.computed(()=>{var g;return{overflow:e.edited?"visible":"hidden",alignItems:s[((g=r.value)==null?void 0:g.value)??mt.Top]}}),{nextEditorTick:p}=ut();function m(g){p(y=>{if(gt.read(y,e.entityId).content===g.content)return;const v=gt.write(y,e.entityId);v.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",qL,[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,JL)])),d.createElementVNode("div",{class:"wov-shape-content",style:d.normalizeStyle(h.value)},[d.createVNode(mu,d.mergeProps(e,{"block-element":o.value,onEditEnd:m}),null,16,["block-element"])],4)],512))}}),GL=["data-text-empty"],mb=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=Tt(e.entityId,gt),o=d.computed(()=>{var l;return(((l=r.value)==null?void 0:l.content)??"").replace(/<[^>]*>/g,"").trim().length===0}),{handleEditEnd:s}=Qh({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(mu,d.mergeProps(e,{"block-element":n.value,onEditEnd:d.unref(s)}),null,16,["block-element","onEditEnd"])],8,GL))}}),gu=Math.min,zs=Math.max,yu=Math.round,wu=Math.floor,_r=t=>({x:t,y:t}),XL={left:"right",right:"left",bottom:"top",top:"bottom"},QL={start:"end",end:"start"};function gb(t,e,n){return zs(t,gu(e,n))}function vu(t,e){return typeof t=="function"?t(e):t}function $s(t){return t.split("-")[0]}function ku(t){return t.split("-")[1]}function yb(t){return t==="x"?"y":"x"}function wb(t){return t==="y"?"height":"width"}const eV=new Set(["top","bottom"]);function qo(t){return eV.has($s(t))?"y":"x"}function vb(t){return yb(qo(t))}function tV(t,e,n){n===void 0&&(n=!1);const r=ku(t),o=vb(t),s=wb(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=bu(i)),[i,bu(i)]}function nV(t){const e=bu(t);return[tp(t),e,tp(e)]}function tp(t){return t.replace(/start|end/g,e=>QL[e])}const kb=["left","right"],bb=["right","left"],rV=["top","bottom"],oV=["bottom","top"];function sV(t,e,n){switch(t){case"top":case"bottom":return n?e?bb:kb:e?kb:bb;case"left":case"right":return e?rV:oV;default:return[]}}function iV(t,e,n,r){const o=ku(t);let s=sV($s(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map(tp)))),s}function bu(t){return t.replace(/left|right|bottom|top/g,e=>XL[e])}function aV(t){return{top:0,right:0,bottom:0,left:0,...t}}function lV(t){return typeof t!="number"?aV(t):{top:t,right:t,bottom:t,left:t}}function Su(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 Sb(t,e,n){let{reference:r,floating:o}=t;const s=qo(e),i=vb(e),a=wb(i),l=$s(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(ku(e)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}async function cV(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}=vu(e,t),m=lV(p),y=a[h?f==="floating"?"reference":"floating":f],w=Su(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})),v=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},k=Su(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:l}):v);return{top:(w.top-k.top+m.top)/S.y,bottom:(k.bottom-w.bottom+m.bottom)/S.y,left:(w.left-k.left+m.left)/S.x,right:(k.right-w.right+m.right)/S.x}}const uV=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}=Sb(c,r,l),h=r,p={},m=0;for(let y=0;y<a.length;y++){var g;const{name:w,fn:v}=a[y],{x:b,y:S,data:k,reset:E}=await v({x:u,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:{...i,detectOverflow:(g=i.detectOverflow)!=null?g:cV},elements:{reference:t,floating:e}});u=b??u,f=S??f,p={...p,[w]:{...p[w],...k}},E&&m<=50&&(m++,typeof E=="object"&&(E.placement&&(h=E.placement),E.rects&&(c=E.rects===!0?await i.getElementRects({reference:t,floating:e,strategy:o}):E.rects),{x:u,y:f}=Sb(c,h,l)),y=-1)}return{x:u,y:f,placement:h,strategy:o,middlewareData:p}},dV=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}=vu(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const w=$s(o),v=qo(a),b=$s(a)===a,S=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(b||!g?[bu(a)]:nV(a)),E=m!=="none";!h&&E&&k.push(...iV(a,g,m,S));const _=[a,...k],M=await l.detectOverflow(e,y),I=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&I.push(M[w]),f){const F=tV(o,i,S);I.push(M[F[0]],M[F[1]])}if(P=[...P,{placement:o,overflows:I}],!I.every(F=>F<=0)){var V,Z;const F=(((V=s.flip)==null?void 0:V.index)||0)+1,Y=_[F];if(Y&&(!(f==="alignment"?v!==qo(Y):!1)||P.every(j=>qo(j.placement)===v?j.overflows[0]>0:!0)))return{data:{index:F,overflows:P},reset:{placement:Y}};let ce=(Z=P.filter(se=>se.overflows[0]<=0).sort((se,j)=>se.overflows[1]-j.overflows[1])[0])==null?void 0:Z.placement;if(!ce)switch(p){case"bestFit":{var A;const se=(A=P.filter(j=>{if(E){const X=qo(j.placement);return X===v||X==="y"}return!0}).map(j=>[j.placement,j.overflows.filter(X=>X>0).reduce((X,he)=>X+he,0)]).sort((j,X)=>j[1]-X[1])[0])==null?void 0:A[0];se&&(ce=se);break}case"initialPlacement":ce=a;break}if(o!==ce)return{reset:{placement:ce}}}return{}}}},fV=new Set(["left","top"]);async function hV(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=$s(n),a=ku(n),l=qo(n)==="y",c=fV.has(i)?-1:1,u=s&&l?-1:1,f=vu(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 pV=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 hV(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}}}}},mV=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:o,platform:s}=e,{mainAxis:i=!0,crossAxis:a=!1,limiter:l={fn:w=>{let{x:v,y:b}=w;return{x:v,y:b}}},...c}=vu(t,e),u={x:n,y:r},f=await s.detectOverflow(e,c),h=qo($s(o)),p=yb(h);let m=u[p],g=u[h];if(i){const w=p==="y"?"top":"left",v=p==="y"?"bottom":"right",b=m+f[w],S=m-f[v];m=gb(b,m,S)}if(a){const w=h==="y"?"top":"left",v=h==="y"?"bottom":"right",b=g+f[w],S=g-f[v];g=gb(b,g,S)}const y=l.fn({...e,[p]:m,[h]:g});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[p]:i,[h]:a}}}}}};function Eu(){return typeof window<"u"}function Ls(t){return np(t)?(t.nodeName||"").toLowerCase():"#document"}function xn(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function xr(t){var e;return(e=(np(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function np(t){return Eu()?t instanceof Node||t instanceof xn(t).Node:!1}function or(t){return Eu()?t instanceof Element||t instanceof xn(t).Element:!1}function Tr(t){return Eu()?t instanceof HTMLElement||t instanceof xn(t).HTMLElement:!1}function Eb(t){return!Eu()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof xn(t).ShadowRoot}const gV=new Set(["inline","contents"]);function sl(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=sr(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!gV.has(o)}const yV=new Set(["table","td","th"]);function wV(t){return yV.has(Ls(t))}const vV=[":popover-open",":modal"];function Cu(t){return vV.some(e=>{try{return t.matches(e)}catch{return!1}})}const kV=["transform","translate","scale","rotate","perspective"],bV=["transform","translate","scale","rotate","perspective","filter"],SV=["paint","layout","strict","content"];function rp(t){const e=op(),n=or(t)?sr(t):t;return kV.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)||bV.some(r=>(n.willChange||"").includes(r))||SV.some(r=>(n.contain||"").includes(r))}function EV(t){let e=Jo(t);for(;Tr(e)&&!Fi(e);){if(rp(e))return e;if(Cu(e))return null;e=Jo(e)}return null}function op(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const CV=new Set(["html","body","#document"]);function Fi(t){return CV.has(Ls(t))}function sr(t){return xn(t).getComputedStyle(t)}function _u(t){return or(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Jo(t){if(Ls(t)==="html")return t;const e=t.assignedSlot||t.parentNode||Eb(t)&&t.host||xr(t);return Eb(e)?e.host:e}function Cb(t){const e=Jo(t);return Fi(e)?t.ownerDocument?t.ownerDocument.body:t.body:Tr(e)&&sl(e)?e:Cb(e)}function il(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=Cb(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=xn(o);if(s){const a=sp(i);return e.concat(i,i.visualViewport||[],sl(o)?o:[],a&&n?il(a):[])}return e.concat(o,il(o,[],n))}function sp(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function _b(t){const e=sr(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=Tr(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=yu(n)!==s||yu(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ip(t){return or(t)?t:t.contextElement}function ji(t){const e=ip(t);if(!Tr(e))return _r(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=_b(e);let i=(s?yu(n.width):n.width)/r,a=(s?yu(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const _V=_r(0);function xb(t){const e=xn(t);return!op()||!e.visualViewport?_V:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function xV(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==xn(t)?!1:e}function Vs(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=ip(t);let i=_r(1);e&&(r?or(r)&&(i=ji(r)):i=ji(t));const a=xV(s,n,r)?xb(s):_r(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=xn(s),p=r&&or(r)?xn(r):r;let m=h,g=sp(m);for(;g&&r&&p!==m;){const y=ji(g),w=g.getBoundingClientRect(),v=sr(g),b=w.left+(g.clientLeft+parseFloat(v.paddingLeft))*y.x,S=w.top+(g.clientTop+parseFloat(v.paddingTop))*y.y;l*=y.x,c*=y.y,u*=y.x,f*=y.y,l+=b,c+=S,m=xn(g),g=sp(m)}}return Su({width:u,height:f,x:l,y:c})}function xu(t,e){const n=_u(t).scrollLeft;return e?e.left+n:Vs(xr(t)).left+n}function Tb(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-xu(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function TV(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=xr(r),a=e?Cu(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=_r(1);const u=_r(0),f=Tr(r);if((f||!f&&!s)&&((Ls(r)!=="body"||sl(i))&&(l=_u(r)),Tr(r))){const p=Vs(r);c=ji(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const h=i&&!f&&!s?Tb(i,l):_r(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 MV(t){return Array.from(t.getClientRects())}function AV(t){const e=xr(t),n=_u(t),r=t.ownerDocument.body,o=zs(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=zs(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+xu(t);const a=-n.scrollTop;return sr(r).direction==="rtl"&&(i+=zs(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Mb=25;function IV(t,e){const n=xn(t),r=xr(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=op();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=xu(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<=Mb&&(s-=m)}else c<=Mb&&(s+=c);return{width:s,height:i,x:a,y:l}}const NV=new Set(["absolute","fixed"]);function BV(t,e){const n=Vs(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=Tr(t)?ji(t):_r(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 Ab(t,e,n){let r;if(e==="viewport")r=IV(t,n);else if(e==="document")r=AV(xr(t));else if(or(e))r=BV(e,n);else{const o=xb(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return Su(r)}function Ib(t,e){const n=Jo(t);return n===e||!or(n)||Fi(n)?!1:sr(n).position==="fixed"||Ib(n,e)}function PV(t,e){const n=e.get(t);if(n)return n;let r=il(t,[],!1).filter(a=>or(a)&&Ls(a)!=="body"),o=null;const s=sr(t).position==="fixed";let i=s?Jo(t):t;for(;or(i)&&!Fi(i);){const a=sr(i),l=rp(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&NV.has(o.position)||sl(i)&&!l&&Ib(t,i))?r=r.filter(u=>u!==i):o=a,i=Jo(i)}return e.set(t,r),r}function OV(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?Cu(e)?[]:PV(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const f=Ab(e,u,o);return c.top=zs(f.top,c.top),c.right=gu(f.right,c.right),c.bottom=gu(f.bottom,c.bottom),c.left=zs(f.left,c.left),c},Ab(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function DV(t){const{width:e,height:n}=_b(t);return{width:e,height:n}}function RV(t,e,n){const r=Tr(e),o=xr(e),s=n==="fixed",i=Vs(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=_r(0);function c(){l.x=xu(o)}if(r||!r&&!s)if((Ls(e)!=="body"||sl(o))&&(a=_u(e)),r){const p=Vs(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?Tb(o,a):_r(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 ap(t){return sr(t).position==="static"}function Nb(t,e){if(!Tr(t)||sr(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return xr(t)===n&&(n=n.ownerDocument.body),n}function Bb(t,e){const n=xn(t);if(Cu(t))return n;if(!Tr(t)){let o=Jo(t);for(;o&&!Fi(o);){if(or(o)&&!ap(o))return o;o=Jo(o)}return n}let r=Nb(t,e);for(;r&&wV(r)&&ap(r);)r=Nb(r,e);return r&&Fi(r)&&ap(r)&&!rp(r)?n:r||EV(t)||n}const zV=async function(t){const e=this.getOffsetParent||Bb,n=this.getDimensions,r=await n(t.floating);return{reference:RV(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function $V(t){return sr(t).direction==="rtl"}const LV={convertOffsetParentRelativeRectToViewportRelativeRect:TV,getDocumentElement:xr,getClippingRect:OV,getOffsetParent:Bb,getElementRects:zV,getClientRects:MV,getDimensions:DV,getScale:ji,isElement:or,isRTL:$V};function Pb(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function VV(t,e){let n=null,r;const o=xr(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=wu(f),g=wu(o.clientWidth-(u+h)),y=wu(o.clientHeight-(f+p)),w=wu(u),b={rootMargin:-m+"px "+-g+"px "+-y+"px "+-w+"px",threshold:zs(0,gu(1,l))||1};let S=!0;function k(E){const _=E[0].intersectionRatio;if(_!==l){if(!S)return i();_?i(!1,_):r=setTimeout(()=>{i(!1,1e-7)},1e3)}_===1&&!Pb(c,t.getBoundingClientRect())&&i(),S=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(t)}return i(!0),s}function Ob(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=ip(t),u=o||s?[...c?il(c):[],...il(e)]:[];u.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),s&&w.addEventListener("resize",n)});const f=c&&a?VV(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(w=>{let[v]=w;v&&v.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?Vs(t):null;l&&y();function y(){const w=Vs(t);g&&!Pb(g,w)&&n(),g=w,m=requestAnimationFrame(y)}return n(),()=>{var w;u.forEach(v=>{o&&v.removeEventListener("scroll",n),s&&v.removeEventListener("resize",n)}),f==null||f(),(w=p)==null||w.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const Tu=pV,Mu=mV,Au=dV,FV=(t,e,n)=>{const r=new Map,o={platform:LV,...n},s={...o.platform,_c:r};return uV(t,e,{...o,platform:s})};function jV(t){return t!=null&&typeof t=="object"&&"$el"in t}function Db(t){if(jV(t)){const e=t.$el;return np(e)&&Ls(e)==="#comment"?null:e}return t}function al(t){return typeof t=="function"?t():d.unref(t)}function Rb(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function zb(t,e){const n=Rb(t);return Math.round(e*n)/n}function Iu(t,e,n){n===void 0&&(n={});const r=n.whileElementsMounted,o=d.computed(()=>{var _;return(_=al(n.open))!=null?_:!0}),s=d.computed(()=>al(n.middleware)),i=d.computed(()=>{var _;return(_=al(n.placement))!=null?_:"bottom"}),a=d.computed(()=>{var _;return(_=al(n.strategy))!=null?_:"absolute"}),l=d.computed(()=>{var _;return(_=al(n.transform))!=null?_:!0}),c=d.computed(()=>Db(t.value)),u=d.computed(()=>Db(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 _={position:p.value,left:"0",top:"0"};if(!u.value)return _;const M=zb(u.value,f.value),I=zb(u.value,h.value);return l.value?{..._,transform:"translate("+M+"px, "+I+"px)",...Rb(u.value)>=1.5&&{willChange:"transform"}}:{position:p.value,left:M+"px",top:I+"px"}});let v;function b(){if(c.value==null||u.value==null)return;const _=o.value;FV(c.value,u.value,{middleware:s.value,placement:i.value,strategy:a.value}).then(M=>{f.value=M.x,h.value=M.y,p.value=M.strategy,m.value=M.placement,g.value=M.middlewareData,y.value=_!==!1})}function S(){typeof v=="function"&&(v(),v=void 0)}function k(){if(S(),r===void 0){b();return}if(c.value!=null&&u.value!=null){v=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],k,{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 UV=["menu-open"],jn=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($0,null),i=d.inject(L0,0),a=Math.random().toString(36).slice(2);d.provide(L0,i+1);const{show:l,hide:c}=Yo(),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}=Iu(f,h,{placement:n.placement,middleware:[Tu(n.offsetPx),Au(),Mu({padding:8})],whileElementsMounted:Ob});function m(){n.disabled||(u.value=!u.value)}function g(){u.value=!1}function y(b){var M,I,P;const S=b.target,k=(M=f.value)==null?void 0:M.contains(S),E=(I=h.value)==null?void 0:I.contains(S),_=(P=S.closest)==null?void 0:P.call(S,".wov-menu-dropdown");!k&&!E&&!_&&g()}function w(){n.title&&f.value&&!u.value&&l(n.title,f.value)}function v(){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:v},[d.renderSlot(b.$slots,"button",{isOpen:u.value})],42,UV),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))}}),WV={},HV={viewBox:"0 0 512 320",fill:"currentColor",style:{width:"7px",color:"var(--wov-gray-300)"}};function ZV(t,e){return d.openBlock(),d.createElementBlock("svg",HV,[...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 Un=ys(WV,[["render",ZV]]),KV={class:"wov-menu-button"},YV=["innerHTML"],qV=["onClick"],JV=["innerHTML"],lp=d.defineComponent({__name:"ArrowHeadButton",props:{entityIds:{},side:{}},setup(t){const e=t,{nextEditorTick:n}=ut(),r=d.shallowRef(null),o=d.computed(()=>{const a=r.value??(e.side==="start"?De.None:De.V);return _i(a)});n(a=>{let l=null;for(const c of e.entityIds){if(R(a,c,Pe)){const u=Pe.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"?De.None:De.V;return}}if(R(a,c,xe)){const u=xe.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"?De.None:De.V;return}}}r.value=l});function s(a){r.value=a,n(l=>{for(const c of e.entityIds){if(R(l,c,Pe)){const u=Pe.write(l,c);e.side==="start"?u.startArrowHead=a:u.endArrowHead=a}if(R(l,c,xe)){const u=xe.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(jn,{title:t.side==="start"?"Start Arrow Head":"End Arrow Head"},{button:d.withCtx(()=>[d.createElementVNode("div",KV,[(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,YV)),d.createVNode(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(d.unref(Cf),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,JV))],10,qV))),128))]),_:1},8,["title"]))}}),GV={class:"wov-menu-button"},XV=["onClick"],$b=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}=ut(),o=d.shallowRef(null);r(i=>{let a=null;for(const l of n.entityIds){if(R(i,l,Pe)){const c=Pe.read(i,l);if(a===null)a=c.thickness;else if(c.thickness!==a){o.value=null;return}}if(R(i,l,xe)){const c=xe.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(R(a,l,Pe)){const c=Pe.write(a,l);c.thickness=i}R(a,l,xe)&&xe.setThickness(a,l,i)}})}return(i,a)=>(d.openBlock(),d.createBlock(jn,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",GV,[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(Un,{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,XV)),64))]),_:1}))}}),QV=["value"],eF=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,QV))}}),Lb=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))}}),tF={class:"wov-color-picker"},nF={class:"wov-color-picker-area"},rF={class:"wov-color-picker-selector-gradient"},oF="linear-gradient(to bottom, red 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red 100%)",Vb=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,_;return u.value||((E=o.value)==null?void 0:E.isDragging)||((_=s.value)==null?void 0:_.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(()=>lb({h:h.value.h,s:100,v:100})),m=d.computed(()=>lb({h:h.value.h,s:h.value.s,v:h.value.v})),g=d.computed(()=>n.withOpacity?cb(h.value):m.value),y=d.computed(()=>`linear-gradient(to top, transparent 0%, ${m.value} 100%)`);function w(E){if(E){const _=ab(E);a.value={x:_.s,y:100-_.v},l.value=_.h/360*100,c.value=100-_.a/255*100}}function v(E){w(E),r("update:modelValue",n.withOpacity?cb(ab(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",k)}function S(E){if(!i.value)return;const _=i.value.getBoundingClientRect(),M=Math.max(0,Math.min(100,(E.clientX-_.left)/_.width*100)),I=Math.max(0,Math.min(100,(E.clientY-_.top)/_.height*100));a.value={x:M,y:I}}function k(){u.value=!1,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",k)}return(E,_)=>(d.openBlock(),d.createElementBlock("div",tF,[d.createVNode(eF,{modelValue:g.value,"onUpdate:modelValue":v},null,8,["modelValue"]),d.createElementVNode("div",nF,[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",rF,[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(Lb,{ref_key:"hueSliderRef",ref:o,modelValue:l.value,"onUpdate:modelValue":_[0]||(_[0]=M=>l.value=M),thumbColor:p.value,background:oF},null,8,["modelValue","thumbColor"]),t.withOpacity?(d.openBlock(),d.createBlock(Lb,{key:0,ref_key:"opacitySliderRef",ref:s,modelValue:c.value,"onUpdate:modelValue":_[1]||(_[1]=M=>c.value=M),thumbColor:m.value,background:y.value,class:"wov-color-picker-opacity"},null,8,["modelValue","thumbColor","background"])):d.createCommentVNode("",!0)])]))}}),sF={class:"wov-color-bubbles-container"},iF={key:1,class:"wov-color-bubbles"},aF=["onClick"],Nu=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 v=w.replace(/^#/,"").toLowerCase();return v.length===6?v+"ff":v};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=Kh(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=Kh(m);g&&r("change",g)}return(m,g)=>(d.openBlock(),d.createElementBlock("div",sF,[i.value?(d.openBlock(),d.createBlock(Vb,{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",iF,[(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,aF))),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)]))]))}}),lF={class:"wov-color-button"},Fb=d.defineComponent({__name:"ColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=ut(),r=Zo(()=>e.entityIds,In),o=d.computed(()=>{const c=new Set;for(const u of r.value.values())if(u){const f=rl(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=rl(c);n(f=>{for(const h of e.entityIds)In.fromHex(f,h,u)})}return(c,u)=>(d.openBlock(),d.createBlock(jn,{title:"Color"},{button:d.withCtx(()=>[d.createElementVNode("div",lF,[d.createElementVNode("div",{class:"wov-color-swatch",style:d.normalizeStyle(a.value)},null,4),d.createVNode(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Nu,{currentColor:i.value??void 0,hideHighlight:s.value,withPicker:!0,onChange:l},null,8,["currentColor","hideHighlight"])]),_:1}))}}),Ui=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}=Yo();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))}}),cp=d.defineComponent({__name:"MenuTooltip",setup(t){const{activeTooltip:e,isVisible:n}=Yo(),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}=Iu(s,o,{placement:"top",middleware:[Tu(8),Au({fallbackPlacements:["bottom"]}),Mu({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)}}),cF={class:"wov-menu-button"},uF=["onClick"],jb=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}=ut(),o=Zo(()=>n.entityIds,tr),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=tr.write(l,c);u.thickness=a}})}return(a,l)=>(d.openBlock(),d.createBlock(jn,{title:"Thickness"},{button:d.withCtx(()=>[d.createElementVNode("div",cF,[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(Un,{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,uF)),64))]),_:1}))}}),dF={class:"wov-fill-color-button"},fF={class:"wov-fill-dropdown"},hF={key:0,class:"wov-fill-mode-section"},pF=["title","onClick"],mF={viewBox:"0 0 24 24",fill:"none"},gF=["fill","fill-opacity","stroke","stroke-width","stroke-dasharray"],Ub=d.defineComponent({__name:"ShapeFillColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=ut(),r=Zo(()=>e.entityIds,Nn),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=Nn.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=rl({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=Nn.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(jn,{title:"Fill Color"},{button:d.withCtx(()=>[d.createElementVNode("div",dF,[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(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",fF,[h.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",hF,[(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",mF,[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,gF)])),d.createElementVNode("span",null,d.toDisplayString(g.label),1)],10,pF)),64))])),d.createVNode(Nu,{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}))}}),yF={class:"wov-shape-kind-button"},wF={class:"wov-shape-kind-dropdown"},vF=["onClick"],kF={viewBox:"0 0 20 20",class:"wov-shape-option-icon",fill:"none",stroke:"currentColor","stroke-width":"4"},bF=["d"],Wb=d.defineComponent({__name:"ShapeKindButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=ut(),r=Zo(()=>e.entityIds,Nn),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(Ba).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=Nn.write(c,u);f.kind=l}})}return(l,c)=>(d.openBlock(),d.createBlock(jn,{title:"Shape Type"},{button:d.withCtx(()=>[d.createElementVNode("div",yF,[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(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",wF,[(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",kF,[d.createElementVNode("path",{d:d.unref(Ba)[u.kind],transform:"translate(2, 2) scale(0.16)"},null,8,bF)])),d.createElementVNode("span",null,d.toDisplayString(u.label),1)],10,vF))),128))])]),_:1}))}}),SF={class:"wov-stroke-style-section"},EF=["title","onClick"],CF={viewBox:"0 0 24 8",fill:"none",stroke:"currentColor","stroke-width":"2"},_F=["stroke-dasharray","stroke-opacity"],xF=d.defineComponent({__name:"StrokeStyleOptions",props:{currentStyle:{},hasMultipleStyles:{type:Boolean}},emits:["change"],setup(t,{emit:e}){const n=e,r=[{kind:Ct.Solid,label:"Solid"},{kind:Ct.Dashed,label:"Dashed"},{kind:Ct.None,label:"None"}];function o(i){switch(i){case Ct.Dashed:return"6 6";case Ct.None:return"";case Ct.Solid:default:return""}}function s(i){n("change",i)}return(i,a)=>(d.openBlock(),d.createElementBlock("div",SF,[(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",CF,[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(Ct).None?.3:1},null,8,_F)])),d.createElementVNode("span",null,d.toDisplayString(l.label),1)],10,EF)),64))]))}}),TF={class:"wov-stroke-color-button"},MF={class:"wov-stroke-dropdown"},AF={key:1,class:"wov-stroke-divider"},Hb=d.defineComponent({__name:"ShapeStrokeColorButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=ut(),r=Zo(()=>e.entityIds,Nn),o=d.ref(!1),s=d.computed(()=>{const h=new Set;for(const p of r.value.values())if(p){const m=rl({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)??Ct.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=Nn.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=Nn.write(p,m);g.strokeKind=h}})}return(h,p)=>(d.openBlock(),d.createBlock(jn,{title:"Stroke Color"},{button:d.withCtx(()=>[d.createElementVNode("div",TF,[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(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",MF,[o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createBlock(xF,{key:0,currentStyle:l.value,hasMultipleStyles:c.value,onChange:f},null,8,["currentStyle","hasMultipleStyles"])),o.value?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",AF)),d.createVNode(Nu,{currentColor:a.value,hideHighlight:i.value,withPicker:!0,onChange:u,onPickerOpen:p[0]||(p[0]=m=>o.value=m)},null,8,["currentColor","hideHighlight"])])]),_:1}))}}),IF={key:0,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},NF={key:1,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},BF={key:2,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},PF={key:3,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},up=d.defineComponent({__name:"TextAlignmentButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>e.entityIds),o=[Bn.Left,Bn.Center,Bn.Right,Bn.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(Ui,{key:0,title:"Text Align",onClick:s},{default:d.withCtx(()=>[d.unref(n).alignment===d.unref(Bn).Left?(d.openBlock(),d.createElementBlock("svg",IF,[...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(Bn).Center?(d.openBlock(),d.createElementBlock("svg",NF,[...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(Bn).Right?(d.openBlock(),d.createElementBlock("svg",BF,[...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",PF,[...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)}}),dp=d.defineComponent({__name:"TextBoldButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Ui,{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 OF(t,e){return d.getCurrentScope()?(d.onScopeDispose(t,e),!0):!1}const DF=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const RF=Object.prototype.toString,zF=t=>RF.call(t)==="[object Object]",Bu=()=>{};function Pu(t){return Array.isArray(t)?t:[t]}function $F(t){return d.getCurrentInstance()}function LF(t,e=!0,n){$F()?d.onMounted(t,n):e?t():d.nextTick(t)}function VF(t,e,n){return d.watch(t,e,{...n,immediate:!0})}const Ou=DF?window:void 0;function ir(t){var e;const n=d.toValue(t);return(e=n==null?void 0:n.$el)!==null&&e!==void 0?e:n}function fp(...t){const e=(r,o,s,i)=>(r.addEventListener(o,s,i),()=>r.removeEventListener(o,s,i)),n=d.computed(()=>{const r=Pu(d.toValue(t[0])).filter(o=>o!=null);return r.every(o=>typeof o!="string")?r:void 0});return VF(()=>{var r,o;return[(r=(o=n.value)===null||o===void 0?void 0:o.map(s=>ir(s)))!==null&&r!==void 0?r:[Ou].filter(s=>s!=null),Pu(d.toValue(n.value?t[1]:t[0])),Pu(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=zF(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 FF(t,e,n={}){const{window:r=Ou,ignore:o=[],capture:s=!0,detectIframe:i=!1,controls:a=!1}=n;if(!r)return a?{stop:Bu,cancel:Bu,trigger:Bu}:Bu;let l=!0;const c=y=>d.toValue(o).some(w=>{if(typeof w=="string")return Array.from(r.document.querySelectorAll(w)).some(v=>v===y.target||y.composedPath().includes(v));{const v=ir(w);return v&&(y.target===v||y.composedPath().includes(v))}});function u(y){const w=d.toValue(y);return w&&w.$.subTree.shapeFlag===16}function f(y,w){const v=d.toValue(y),b=v.$.subTree&&v.$.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=ir(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=[fp(r,"click",y=>{p||(p=!0,setTimeout(()=>{p=!1},0),h(y))},{passive:!0,capture:s}),fp(r,"pointerdown",y=>{const w=ir(t);l=!c(y)&&!!(w&&!y.composedPath().includes(w))},{passive:!0}),i&&fp(r,"blur",y=>{setTimeout(()=>{var w;const v=ir(t);((w=r.document.activeElement)===null||w===void 0?void 0:w.tagName)==="IFRAME"&&!(v!=null&&v.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 jF(){const t=d.shallowRef(!1),e=d.getCurrentInstance();return e&&d.onMounted(()=>{t.value=!0},e),t}function UF(t){const e=jF();return d.computed(()=>(e.value,!!t()))}function WF(t,e,n={}){const{window:r=Ou,...o}=n;let s;const i=UF(()=>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=>ir(f)):[ir(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 OF(c),{isSupported:i,stop:c}}function Zb(t,e={width:0,height:0},n={}){const{window:r=Ou,box:o="content-box"}=n,s=d.computed(()=>{var f;return(f=ir(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}=WF(t,([f])=>{const h=o==="border-box"?f.borderBoxSize:o==="content-box"?f.contentBoxSize:f.devicePixelContentBoxSize;if(r&&s.value){const p=ir(t);if(p){const m=p.getBoundingClientRect();i.value=m.width,a.value=m.height}}else if(h){const p=Pu(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);LF(()=>{const f=ir(t);f&&(i.value="offsetWidth"in f?f.offsetWidth:e.width,a.value="offsetHeight"in f?f.offsetHeight:e.height)});const c=d.watch(()=>ir(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 Kb(){const t=d.inject(Rn);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 HF={class:"wov-font-family-button"},ZF={class:"wov-font-family-label"},KF={class:"wov-font-list"},YF=["onClick"],qF=["src","alt"],hp=d.defineComponent({__name:"TextFontFamilyButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>e.entityIds),o=Kb(),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(jn,{key:0,title:"Font Family"},{button:d.withCtx(()=>[d.createElementVNode("div",HF,[d.createElementVNode("span",ZF,d.toDisplayString(a.value),1),d.createVNode(Un,{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",KF,[(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,qF)):(d.openBlock(),d.createElementBlock("span",{key:1,class:"wov-font-name",style:d.normalizeStyle({fontFamily:h.name})},d.toDisplayString(h.displayName),5))],10,YF))),128))])],32)]),_:1})):d.createCommentVNode("",!0)}}),JF={class:"wov-font-size-button"},GF={class:"wov-font-size-label"},XF=["onClick"],QF={key:0,class:"wov-check-icon",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 448 512",fill:"currentColor"},e6={class:"wov-input-container"},t6=["value"],pp=d.defineComponent({__name:"TextFontSizeButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>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(jn,{key:0,title:"Font Size"},{button:d.withCtx(()=>[d.createElementVNode("div",JF,[d.createElementVNode("span",GF,d.toDisplayString(i.value),1),d.createVNode(Un,{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",QF,[...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,XF)),64)),p[3]||(p[3]=d.createElementVNode("div",{class:"wov-separator"},null,-1)),d.createElementVNode("div",e6,[d.createElementVNode("input",{class:"wov-custom-input",value:a.value,onInput:c,onKeydown:u,placeholder:"Custom size"},null,40,t6),p[2]||(p[2]=d.createElementVNode("span",{class:"wov-px-suffix"},"px",-1))])],32)]),_:1})):d.createCommentVNode("",!0)}}),mp=d.defineComponent({__name:"TextItalicButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Ui,{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)}}),gp=d.defineComponent({__name:"TextUnderlineButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>e.entityIds);return(o,s)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(Ui,{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)}}),n6={class:"wov-text-color-button"},r6={class:"wov-text-icon-container"},yp=d.defineComponent({__name:"TextColorButton",props:{entityIds:{}},setup(t){const e=t,{state:n,commands:r}=Cr(()=>e.entityIds),o=d.computed(()=>n.color??"#000000"),s=d.computed(()=>({backgroundColor:o.value}));function i(a){r.setColor(rl(a))}return(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createBlock(jn,{key:0,title:"Text Color"},{button:d.withCtx(()=>[d.createElementVNode("div",n6,[d.createElementVNode("div",r6,[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(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createVNode(Nu,{currentColor:o.value,withPicker:!0,onChange:i},null,8,["currentColor"])]),_:1})):d.createCommentVNode("",!0)}}),o6={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"},s6={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"},i6={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"},Yb=d.defineComponent({__name:"VerticalAlignButton",props:{entityIds:{}},setup(t){const e=t,{nextEditorTick:n}=ut(),{state:r}=Cr(()=>e.entityIds),o=[mt.Top,mt.Center,mt.Bottom],s=Zo(()=>e.entityIds,cs),i=d.computed(()=>{let l=null;for(const c of s.value.values()){const u=(c==null?void 0:c.value)??mt.Top;if(l===null)l=u;else if(l!==u)return null}return l});function a(){const l=i.value??mt.Top,c=o.indexOf(l),u=o[(c+1)%o.length];n(f=>{for(const h of e.entityIds){const p=cs.write(f,h);p.value=u}})}return(l,c)=>d.unref(r).showTextMenuButtons?(d.openBlock(),d.createBlock(Ui,{key:0,title:"Vertical Align",onClick:a},{default:d.withCtx(()=>[i.value===d.unref(mt).Top||i.value===null?(d.openBlock(),d.createElementBlock("svg",o6,[...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(mt).Center?(d.openBlock(),d.createElementBlock("svg",s6,[...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",i6,[...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)}}),a6={class:"wov-text-group-button"},l6={class:"wov-text-group-dropdown"},c6={class:"wov-text-group-row wov-text-group-row-full"},u6={class:"wov-text-group-row"},d6=d.defineComponent({__name:"TextButtonGroup",props:{entityIds:{},showVerticalAlign:{type:Boolean}},setup(t){const e=t,{state:n}=Cr(()=>e.entityIds),r=d.inject("containerRef"),{width:o}=Zb(r),s=d.computed(()=>o.value>0&&o.value<600),i=d.ref(new Map);return d.provide($0,i),(a,l)=>d.unref(n).showTextMenuButtons?(d.openBlock(),d.createElementBlock(d.Fragment,{key:0},[s.value?(d.openBlock(),d.createBlock(jn,{key:0,title:"Text Formatting",placement:"top"},{button:d.withCtx(()=>[d.createElementVNode("div",a6,[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(Un,{class:"wov-chevron-down"})])]),dropdown:d.withCtx(()=>[d.createElementVNode("div",l6,[d.createElementVNode("div",c6,[d.createVNode(hp,{entityIds:t.entityIds},null,8,["entityIds"]),l[1]||(l[1]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(pp,{entityIds:t.entityIds},null,8,["entityIds"])]),d.createElementVNode("div",u6,[d.createVNode(dp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(mp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(gp,{entityIds:t.entityIds},null,8,["entityIds"]),l[2]||(l[2]=d.createElementVNode("div",{class:"wov-text-group-spacer"},null,-1)),d.createVNode(yp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(up,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(Yb,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)])])]),_:1})):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createVNode(hp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(pp,{entityIds:t.entityIds},null,8,["entityIds"]),l[3]||(l[3]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(dp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(mp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(gp,{entityIds:t.entityIds},null,8,["entityIds"]),l[4]||(l[4]=d.createElementVNode("div",{divider:"",class:"wov-divider"},null,-1)),d.createVNode(yp,{entityIds:t.entityIds},null,8,["entityIds"]),d.createVNode(up,{entityIds:t.entityIds},null,8,["entityIds"]),t.showVerticalAlign?(d.openBlock(),d.createBlock(Yb,{key:0,entityIds:t.entityIds},null,8,["entityIds"])):d.createCommentVNode("",!0)],64))],64)):d.createCommentVNode("",!0)}}),qb=d.defineComponent({__name:"CanvasBackground",props:{background:{}},setup(t){const e=t,n=jt(we),r=jt(Wt),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,v,b){const S=b/2;y.beginPath(),y.arc(w,v,S,0,Math.PI*2),y.fill()}function u(y,w,v){if(!l)return null;const b=v.dotSize??2,S=y*v.subdivisionStep,k=w*v.subdivisionStep;l.width=S,l.height=k;const E=l.getContext("2d");if(!E)return null;if(E.clearRect(0,0,S,k),E.fillStyle=v.strokeColor,v.subdivisionStep===1)c(E,S/2,k/2,b);else for(let _=0;_<v.subdivisionStep;_++)for(let M=0;M<v.subdivisionStep;M++){const I=(_+.5)*(S/v.subdivisionStep),P=(M+.5)*(k/v.subdivisionStep),Z=_===0&&M===0?2*b:b;c(E,I,P,Z)}return E.createPattern(l,"repeat")}function f(y,w,v,b,S,k){y.lineWidth=k,y.beginPath(),y.moveTo(w,v),y.lineTo(b,S),y.stroke()}function h(y,w,v){if(!l)return null;const b=v.gridSize??1,S=y*v.subdivisionStep,k=w*v.subdivisionStep;l.width=S,l.height=k;const E=l.getContext("2d");if(!E)return null;if(E.clearRect(0,0,S,k),E.strokeStyle=v.strokeColor,v.subdivisionStep===1)f(E,0,0,S,0,b),f(E,0,0,0,k,b);else{const _=S/v.subdivisionStep,M=k/v.subdivisionStep;for(let I=0;I<=v.subdivisionStep;I++){const P=I*_,V=I%v.subdivisionStep===0;f(E,P,0,P,k,V?3*b:b)}for(let I=0;I<=v.subdivisionStep;I++){const P=I*M,V=I%v.subdivisionStep===0;f(E,0,P,S,P,V?3*b:b)}}return E.createPattern(l,"repeat")}function p(y){let w=r.value.colWidth,v=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,k=s.value.height,E=n.value.left,_=n.value.top,M=E+S/n.value.zoom,I=_+k/n.value.zoom;let P=w*b,V=v*b,Z=0,A=0,F=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY;for(;;){P=b*w,V=b*v,Z=Math.floor(E/P)*P,A=Math.floor(_/V)*V;const je=Math.ceil(M/P)*P,ar=Math.ceil(I/V)*V;if(Y=Math.round((je-Z)/w),F=Math.round((ar-A)/v),Math.max(Y,F)>200)w*=2,v*=2;else break}const ce=w*n.value.zoom,se=v*n.value.zoom,j=Math.round(ce),X=Math.round(se),he=u(j,X,e.background);if(!he)return;he.setTransform(new DOMMatrix().scale(ce/j,se/X));const Te=(Z-E-w/2)*n.value.zoom,Ce=(A-_-v/2)*n.value.zoom;y.save(),y.translate(Te,Ce),y.fillStyle=he,y.fillRect(0,0,S+P*n.value.zoom,k+V*n.value.zoom),y.restore()}function m(y){let w=r.value.colWidth,v=r.value.rowHeight;const b=e.background.subdivisionStep,S=s.value.width,k=s.value.height,E=n.value.left,_=n.value.top,M=E+S/n.value.zoom,I=_+k/n.value.zoom;let P=w*b,V=v*b,Z=0,A=0,F=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY;for(;;){P=b*w,V=b*v,Z=Math.floor(E/P)*P,A=Math.floor(_/V)*V;const je=Math.ceil(M/P)*P,ar=Math.ceil(I/V)*V;if(Y=Math.round((je-Z)/w),F=Math.round((ar-A)/v),Math.max(Y,F)>200)w*=2,v*=2;else break}const ce=w*n.value.zoom,se=v*n.value.zoom,j=Math.round(ce),X=Math.round(se),he=h(j,X,e.background);if(!he)return;he.setTransform(new DOMMatrix().scale(ce/j,se/X));const Te=(Z-E)*n.value.zoom,Ce=(A-_)*n.value.zoom;y.save(),y.translate(Te,Ce),y.fillStyle=he,y.fillRect(0,0,S+P*n.value.zoom,k+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:v,height:b}=s.value;v===0||b===0||(y.width=v,y.height=b,w.clearRect(0,0,v,b),w.fillStyle=e.background.color,w.fillRect(0,0,v,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 Jb(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 Gb=d.defineComponent({__name:"FloatingMenuBar",setup(t){const e=d.useSlots(),{reset:n}=Yo(),r=d.inject(V0),{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(Fb,{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(Wb,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(Ub,{entityIds:d.unref(o)},null,8,["entityIds"]),d.createVNode(Hb,{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(jb,{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($b,{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(lp,{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(lp,{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(d6,{key:0,entityIds:d.unref(o),showVerticalAlign:d.unref(s).has("verticalAlign")},null,8,["entityIds","showVerticalAlign"])):d.createCommentVNode("",!0)]),d.createVNode(cp)],32))}}),f6={class:"wov-floating-menu-inner"},Xb=d.defineComponent({__name:"FloatingMenu",setup(t){const e=d.inject(Rn),n=sb([T,xt]),r=jt(we),o=jt(_t),s=jt(Xn),i=ol(),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 k=n.value.map(E=>({tag:E.block.value.tag}));return Jb(S,k)});d.provide(V0,{selectedIds:a,commonComponents:l});const c=[0,0,0,0];function u(...S){let k=1/0,E=1/0,_=-1/0,M=-1/0,I=!1;for(const P of S){if(!P)continue;const V=P.getBoundingClientRect();V.width<=0||(I=!0,k=Math.min(k,V.left),E=Math.min(E,V.top),_=Math.max(_,V.right),M=Math.max(M,V.bottom))}return I?{x:k,y:E,left:k,top:E,right:_,bottom:M,width:_-k,height:M-E,toJSON:()=>({})}:null}const f=d.computed(()=>{if(n.value.length===0)return null;const S=r.value;if(!S)return null;let k=null;for(const E of n.value){const _=E.block.value;pt.getAabb(_.position,_.size,_.rotateZ,c),ne.translate(c,[-S.left,-S.top]),ne.scale(c,S.zoom),k===null?k=ne.clone(c):ne.union(k,c)}return k}),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 k=i.blockElement.value,E=i.textElement.value,_=u(k,E);if(_)return{getBoundingClientRect:()=>_};const M=f.value;if(!M)return null;const I=S.getBoundingClientRect();return{getBoundingClientRect(){return{x:I.left+M[0],y:I.top+M[1],width:M[2]-M[0],height:M[3]-M[1],top:I.top+M[1],left:I.left+M[0],right:I.left+M[2],bottom:I.top+M[3]}}}}),m=d.ref(null),g={name:"clampToViewport",fn({y:S,rects:k}){const M=window.innerHeight-k.floating.height-8;return{y:Math.max(8,Math.min(S,M))}}},{floatingStyles:y}=Iu(p,m,{placement:"top",middleware:[Tu(12),Au({fallbackPlacements:["bottom"]}),Mu({padding:8}),g]}),w=d.computed(()=>{const S=f.value,k=o.value;return!S||!k?!0:S[2]<0||S[0]>k.width||S[3]<0||S[1]>k.height}),v=[_e.Dragging,_e.SelectionBoxDragging],b=d.computed(()=>n.value.length>0&&!w.value&&!v.includes(s.value.state));return(S,k)=>(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",f6,[d.renderSlot(S.$slots,"default",{},()=>[d.createVNode(Gb)])])],4)):d.createCommentVNode("",!0)]),_:3}))}}),h6={key:0,class:"wov-loading-overlay"},p6={class:"wov-loading-spinner"},Qb=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",h6,[d.createElementVNode("div",p6,d.toDisplayString(e.value),1)])):d.createCommentVNode("",!0)]),_:1}))}}),m6={class:"wov-action-bar"},g6=d.defineComponent({__name:"ActionBar",setup(t){const{getEditor:e}=ut(),n=d.inject(Rn),r=d.ref(!1),o=d.ref(!1);if(n){const l=n.registerTickCallback(c=>{const{store:u}=ls(c,"editing");r.value=u.canUndo(),o.value=u.canRedo()});d.onUnmounted(l)}function s(){const l=e();l==null||l.command(Hd)}function i(){const l=e();l==null||l.command(ql)}function a(){const l=e();l==null||l.command(Qd)}return(l,c)=>(d.openBlock(),d.createElementBlock("div",m6,[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)])])]))}}),Mr=d.defineComponent({__name:"ToolbarButton",props:{name:{},tooltip:{},dragOutSnapshot:{},placementSnapshot:{},cursor:{default:"crosshair"}},setup(t){const e=t,n=d.inject(_f);if(!n)throw new Error("ToolbarButton must be used within a Toolbar component");const r=n,o=d.ref(null),{show:s,hide:i}=Yo(),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))}}),y6='<?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>',w6='<?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>',v6='<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>',Fs={Select:"select",Hand:"hand",Crosshair:"crosshair"},eS={[Fs.Select]:{makeSvg:()=>y6,hotspot:[1,0],rotationOffset:0},[Fs.Hand]:{makeSvg:()=>w6,hotspot:[12,12],rotationOffset:0},[Fs.Crosshair]:{makeSvg:()=>v6,hotspot:[12,12],rotationOffset:0}},k6={viewBox:"0 0 20 20",style:{"fill-rule":"evenodd","clip-rule":"evenodd","stroke-miterlimit":"10"}},tS=d.defineComponent({__name:"SelectTool",setup(t){const{nextEditorTick:e}=ut(),{activeTool:n}=ep();return d.watch(n,(r,o)=>{o==="select"&&e(s=>{bi.spawn(s)})}),(r,o)=>(d.openBlock(),d.createBlock(Mr,{name:"select",tooltip:"Select",cursor:d.unref(Fs).Select},{default:d.withCtx(()=>[(d.openBlock(),d.createElementBlock("svg",k6,[...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"]))}}),nS=d.defineComponent({__name:"HandTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Mr,{name:"hand",tooltip:"Hand",cursor:d.unref(Fs).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"]))}}),rS=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:Bn.Center},verticalAlign:{value:mt.Center}});return(n,r)=>(d.openBlock(),d.createBlock(Mr,{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"]))}}),oS=d.defineComponent({__name:"ShapeTool",setup(t){const e=JSON.stringify({block:{tag:"shape",size:[200,200]},shape:{kind:"rectangle",strokeKind:Ct.Solid,strokeWidth:2,strokeRed:0,strokeGreen:0,strokeBlue:0,strokeAlpha:255,fillRed:255,fillGreen:255,fillBlue:255,fillAlpha:0},text:{defaultAlignment:Bn.Center},verticalAlign:{value:mt.Center}});return(n,r)=>(d.openBlock(),d.createBlock(Mr,{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"]))}}),sS=d.defineComponent({__name:"EraserTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Mr,{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}))}}),iS=d.defineComponent({__name:"PenTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Mr,{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}))}}),aS=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(Mr,{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"]))}}),lS=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:De.None,endArrowHead:De.V},connector:{}});return(n,r)=>(d.openBlock(),d.createBlock(Mr,{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"]))}}),cS=d.defineComponent({__name:"ImageTool",setup(t){const{nextEditorTick:e}=ut(),{show:n,hide:r}=Yo(),{setTool:o}=ep(),{createImageBlock:s}=ob(),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=we.read(g),w=_t.read(g),v=y.left+w.width/y.zoom/2,b=y.top+w.height/y.zoom/2;await s(m,v,b),o("select",void 0,Fs.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))}}),b6={class:"wov-toolbar-container"},uS=d.defineComponent({__name:"Toolbar",setup(t){const e=d.useSlots(),{reset:n}=Yo(),{nextEditorTick:r}=ut(),o=d.ref(null),s=d.ref(null),i=jt(ct),a=d.computed(()=>i.value.leftMouseTool),l=[tS,nS,aS,cS,oS,lS,rS,iS,sS],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),v=d.ref(48),{width:b}=Zb(c);function S(){return h.value?Array.from(h.value.children).filter(j=>!j.classList.contains("wov-overflow-button")&&!j.classList.contains("wov-menu-tooltip")):[]}function k(){var Te;const j=S();if(j.length===0)return;g.value=j.length;const X=getComputedStyle(h.value);w.value=parseFloat(X.gap)||8;const he=((Te=p.value)==null?void 0:Te.offsetWidth)||40;v.value=he+w.value,y.value=j.map(Ce=>Ce.offsetWidth)}function E(){if(y.value.length===0)return;const he=b.value-40-20,Te=w.value,Ce=v.value;let je=0,ar=0;for(let so=0;so<y.value.length;so++){const Ks=y.value[so],Go=je>0?Ks+Te:Ks,Xo=y.value.length-so-1>0?Ce:0;if(je+Go+Xo<=he)je+=Go,ar++;else break}m.value=Math.max(1,ar)}d.watch(b,()=>{y.value.length>0&&E()}),d.onMounted(()=>{d.nextTick(()=>{k(),E()})});const _=d.computed(()=>m.value<g.value);d.watchEffect(()=>{S().forEach((X,he)=>{X.style.display=he<m.value?"":"none"})}),d.watchEffect(()=>{if(!u.value)return;Array.from(u.value.children).forEach((X,he)=>{X.style.display=he>=m.value?"":"none"})});const{floatingStyles:M}=Iu(p,u,{placement:"top",middleware:[Tu(16),Au(),Mu({padding:8})],whileElementsMounted:Ob});function I(){f.value=!f.value}function P(){f.value=!1}function V(j){const X=j.target;p.value&&!p.value.contains(X)&&u.value&&!u.value.contains(X)&&P()}d.watch(f,j=>{j?document.addEventListener("click",V,!0):document.removeEventListener("click",V,!0)}),d.watch(_,j=>{j||P()});function Z(j,X,he){s.value=X??null,r(Te=>{const Ce=ct.write(Te);Ce.leftMouseTool=j,Ce.heldSnapshot=X??"",he&&Pn.setCursor(Te,he)})}function A(j){r(X=>{const he=ct.write(X);he.leftMouseTool="drag-out",he.heldSnapshot=j})}function F(j,X){o.value=j,s.value=X??null}function Y(){o.value=null,s.value=null}function ce(){n(),o.value&&s.value&&A(s.value),o.value=null,s.value=null}const se={activeTool:a,heldTool:o,setTool:Z,dragOutTool:A,onToolPointerDown:F,onToolPointerUp:Y};return d.provide(_f,se),(j,X)=>(d.openBlock(),d.createElementBlock("div",b6,[d.createVNode(g6),d.createElementVNode("div",{ref_key:"toolsContainerRef",ref:h,class:"wov-toolbar",onMouseleave:ce},[d.unref(e).default?d.renderSlot(j.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(he,Te)=>d.createVNode(d.resolveDynamicComponent(he),{key:Te})),64)),_.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},[...X[0]||(X[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(cp)],544),d.unref(c)?(d.openBlock(),d.createBlock(d.Teleport,{key:0,to:d.unref(c)},[f.value&&_.value?(d.openBlock(),d.createElementBlock("div",{key:0,ref_key:"overflowMenuRef",ref:u,class:"wov-toolbar-overflow-menu",style:d.normalizeStyle(d.unref(M))},[d.unref(e).default?d.renderSlot(j.$slots,"default",{key:0}):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},d.renderList(l,(he,Te)=>d.createVNode(d.resolveDynamicComponent(he),{key:Te})),64))],4)):d.createCommentVNode("",!0)],8,["to"])):d.createCommentVNode("",!0)]))}}),S6=d.defineComponent({__name:"ArcArrowTool",setup(t){return(e,n)=>(d.openBlock(),d.createBlock(Mr,{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}))}}),E6={class:"wov-user-presence-avatars"},C6=["src","alt"],_6={class:"wov-user-presence-list"},x6=["src","alt"],T6={class:"wov-user-presence-name"},M6=4,dS=d.defineComponent({__name:"UserPresence",props:{users:{}},setup(t){const e=t,n=d.ref(!1),r=d.ref(null);FF(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,M6));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",E6,[(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,C6)):(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",_6,[(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,x6)):(d.openBlock(),d.createElementBlock(d.Fragment,{key:1},[d.createTextVNode(d.toDisplayString(c.initials),1)],64))],4),d.createElementVNode("span",T6,d.toDisplayString(c.name),1)]))),128))])],32)):d.createCommentVNode("",!0)],512)):d.createCommentVNode("",!0)}});async function wp(t,e){const n=await Tp(t,1,{upgrade(r){r.objectStoreNames.contains(e)||r.createObjectStore(e)}});return new A6(n,e)}var A6=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()}},I6=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([wp(`${t}-jobs`,"jobs"),wp(`${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))}}},N6="wovencanvas-assets",B6="blobs",P6=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=wp(N6,B6).then(t=>(this.store=t,t))),this.initPromise)}},fS=Zr.object({minZoom:Zr.number().default(.05),maxZoom:Zr.number().default(2.7)});fS.parse({});var ll=Eo("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)}),js=Zi({name:"pinchState"},{active:C.boolean().default(!1),prevDistance:C.float64().default(0),prevCenter:C.tuple(C.float64(),2).default([0,0])}),no=[0,0],Du=[0,0],cl=[0,0],vp=[0,0],kp=[0,0];function O6(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);$.copy(no,t),$.sub(no,e);const c=o*r,u=c*c,f=$.lengthSq(no);f>u&&$.scale(no,c/Math.sqrt(f)),$.copy(Du,t),$.sub(Du,no),$.set(cl,(n[0]+i*no[0])*s,(n[1]+i*no[1])*s);const h=[(n[0]-i*cl[0])*l,(n[1]-i*cl[1])*l],p=[Du[0]+(no[0]+cl[0])*l,Du[1]+(no[1]+cl[1])*l];return $.copy(vp,e),$.sub(vp,t),$.copy(kp,p),$.sub(kp,e),$.dot(vp,kp)>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 bp=.1,hS=.1,D6=zr({guards:{hasVelocity:({event:t})=>{if(t.type!=="pointerUp")return!1;const e=t.velocity;return Math.hypot(e[0],e[1])>hS},isGlideComplete:({context:t})=>Math.hypot(t.velocityX,t.velocityY)<hS,cameraWasMoved:({context:t,event:e})=>{const n=we.read(e.ctx);return n.left!==t.expectedLeft||n.top!==t.expectedTop},isEscapeKey:({event:t})=>t.key===dn.Escape},actions:{setDragStart:Ze({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=we.write(r);i.left-=o,i.top-=s},startGlide:Ze(({event:t})=>{const e=t,{ctx:n}=e,r=we.read(n),o=e.cameraZoom,s=-e.velocity[0]/o,i=-e.velocity[1]/o;return{velocityX:s,velocityY:i,targetX:r.left+s*bp,targetY:r.top+i*bp,expectedLeft:r.left,expectedTop:r.top}}),animateGlide:Ze(({context:t,event:e})=>{const n=e,{ctx:r,delta:o}=n,s=we.read(r),{position:i,velocity:a}=O6([s.left,s.top],[t.targetX,t.targetY],[t.velocityX,t.velocityY],bp,Number.POSITIVE_INFINITY,o),l=we.write(r);return l.left=i[0],l.top=i[1],{velocityX:a[0],velocityY:a[1],expectedLeft:i[0],expectedTop:i[1]}}),resetContext:Ze({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"}}}}}),R6=Se({phase:"input",priority:-100},t=>{const e=ll.read(t).state;if(js.read(t).active){e!=="idle"&&ll.copy(t,ll.default());return}const r=ct.getButtons(t,"hand"),s=[...jr(t,r)];e==="gliding"&&s.push(oN(t)),s.push(...sN(t,[dn.Escape])),s.length!==0&&ll.run(t,D6,s)}),z6=ie(t=>t.with(Et)),$6=Se({phase:"input",priority:-100},t=>{const e=ls(t,"controls"),n=z6.current(t),r=[];for(let m=0;m<n.length;m++){const g=n[m],y=Et.read(t,g);y.pointerType===Lr.Touch&&r.push(y.position)}if(r.length!==2){if(js.read(t).active){const g=js.write(t);g.active=!1}return}const[o,s]=r,i=$.distance(o,s),a=$.midPoint(o,s),l=js.read(t);if(!l.active){const m=js.write(t);m.prevDistance=i,m.prevCenter=a,m.active=!0;return}const c=we.read(t),u=_t.read(t);if(l.prevDistance>0&&i>0){const m=i/l.prevDistance;let g=c.zoom*m;g=Math.min(e.maxZoom,Math.max(e.minZoom,g));const y=u.width/c.zoom,w=u.height/c.zoom,v=u.width/g,b=u.height/g,S=v-y,k=b-w,E=a[0]/u.width,_=a[1]/u.height,M=we.write(t);M.left-=E*S,M.top-=_*k,M.zoom=g}const f=a[0]-l.prevCenter[0],h=a[1]-l.prevCenter[1];if(f!==0||h!==0){const m=we.write(t);m.left-=f/m.zoom,m.top-=h/m.zoom}const p=js.write(t);p.prevDistance=i,p.prevCenter=a}),L6=Se({phase:"input",priority:-100},t=>{const e=Sn.read(t);if(!ct.wheelActive(t,"scroll",e.modDown))return;const r=ky(t).find(l=>l.type==="wheel");if(!r)return;const o=we.read(t),s=o.left+r.wheelDeltaX/o.zoom,i=o.top+r.wheelDeltaY/o.zoom,a=we.write(t);a.left=s,a.top=i}),V6=Se({phase:"input",priority:-100},t=>{const e=ls(t,"controls"),n=Sn.read(t);if(!ct.wheelActive(t,"zoom",n.modDown))return;const o=ky(t).find(S=>S.type==="wheel");if(!o)return;const s=we.read(t),i=_t.read(t),a=On.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,v=s.top-y*m,b=we.write(t);b.left=w,b.top=v,b.zoom=l});function F6(t={}){return{name:"controls",resources:fS.parse(t),singletons:[ll,js],systems:[V6,L6,R6,$6]}}var j6=(t={})=>F6(t);const U6={class:"wov-selection-box"},W6=d.defineComponent({__name:"SelectionBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",U6))}}),H6={class:"wov-transform-box"},Z6=d.defineComponent({__name:"TransformBox",setup(t){return(e,n)=>(d.openBlock(),d.createElementBlock("div",H6))}}),K6={},Y6={class:"wov-transform-handle"};function q6(t,e){return d.openBlock(),d.createElementBlock("div",Y6)}const J6=ys(K6,[["render",q6]]),G6=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=Tt(e.entityId,In),r=Tt(e.entityId,cs),o=d.ref(null),s={[mt.Top]:"flex-start",[mt.Center]:"center",[mt.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)??mt.Top]}}),{handleEditEnd:a}=Qh({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(mu,d.mergeProps(e,{"block-element":o.value,onEditEnd:d.unref(a)}),null,16,["block-element","onEditEnd"])],4))}}),Ru=Zi({name:"blockPlacementState"},{editedCheckpoint:C.string().default("").max(36)}),pS=ie(t=>t.with($r));function X6(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 Q6(t,e,n){const r=Xt(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??Zn.genNext(t),l=Bt(t);"synced"in e||ee(t,l,me,{id:crypto.randomUUID()});const c=Object.assign({},e.block,{position:[s,i],size:o,rank:a});ee(t,l,T,c);for(const f of r.components)if(!(f.name in e))ee(t,l,f);else{const h=e[f.name];ee(t,l,f,h)}const{sessionId:u}=Je(t);return ee(t,l,Rt,{sessionId:u}),l}function mS(t,e,n,r,o){const s=Q6(t,e,n),i=T.read(t,s);if(ay(t,e.block.tag)&&(ee(t,s,Ca,{}),o==="placement")){const{store:u}=ls(t,"editing"),f=u.createCheckpoint();if(f){const h=Ru.write(t);h.editedCheckpoint=f}}const a=Xn.write(t);a.state=o==="dragOut"?_e.Dragging:_e.Pointing,a.dragStart=n,a.draggedEntity=s,a.draggedEntityStart=i.position,a.pointingStartClient=r,a.pointingStartWorld=n,a.isCloning=!1;const l=ct.write(t);l.leftMouseTool="select",l.heldSnapshot="";const c=Pn.write(t);c.cursorKind="select",c.rotation=0}function e5(t){const e=Ru.read(t);if(e.editedCheckpoint){const n=e.editedCheckpoint;Ru.write(t).editedCheckpoint="";const{store:r}=ls(t,"editing");r.onSettled(()=>r.squashToCheckpoint(n),{frames:5})}}const t5=Se({phase:"capture"},t=>{pS.removed(t).length>0&&pS.current(t).length===0&&e5(t);const e=ct.read(t);if(!e.heldSnapshot)return;const n=jr(t,[bn.Left]);if(n.length===0)return;const r=X6(e.heldSnapshot);if(!r)return;if(e.leftMouseTool==="drag-out"){const s=n.find(i=>i.type==="pointerMove"&&!i.obscured);if(!s)return;mS(t,r,s.worldPosition,s.screenPosition,"dragOut")}else{const s=n.find(i=>i.type==="pointerDown"&&!i.obscured);if(!s)return;mS(t,r,s.worldPosition,s.screenPosition,"placement")}}),n5=Se({phase:"update"},t=>{const{store:e}=ls(t,"editing");fe(t,Hd,()=>{e.canUndo()&&(t0(t),e.undo())}),fe(t,ql,()=>{e.canRedo()&&(t0(t),e.redo())})}),r5=[{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 gS(t){return{name:"editing",resources:{store:t.store},singletons:[Ru],systems:[t5,n5],cursors:eS,fonts:r5,keybinds:[{command:Hd.name,key:dn.Z,mod:!0},{command:ql.name,key:dn.Y,mod:!0},{command:ql.name,key:dn.Z,mod:!0,shift:!0}]}}const o5=d.defineComponent({__name:"FileDropZone",props:{maxSize:{default:400}},setup(t){const e=t,{nextEditorTick:n}=ut(),{createImageBlock:r}=ob(),o=d.ref(!1);let s=0;const i=d.inject("containerRef");function a(v){var b;(b=v.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 v=i==null?void 0:i.value;v&&(v.addEventListener("dragenter",a),v.addEventListener("dragleave",l),v.addEventListener("drop",c))}),d.onUnmounted(()=>{const v=i==null?void 0:i.value;v&&(v.removeEventListener("dragenter",a),v.removeEventListener("dragleave",l),v.removeEventListener("drop",c))});function u(v){v.preventDefault(),v.dataTransfer&&(v.dataTransfer.dropEffect="copy")}function f(v){v.preventDefault()}function h(v){v.preventDefault()}async function p(v){if(v.preventDefault(),!v.dataTransfer)return;const b=v.clientX,S=v.clientY,k=Array.from(v.dataTransfer.files).filter(_=>_.type.startsWith("image/"));if(k.length>0){for(const _ of k)await y(_,b,S);return}const E=m(v.dataTransfer);E&&await w(E,b,S)}function m(v){const b=v.getData("text/uri-list");if(b){const _=b.split(`
|
|
171
|
+
`).filter(M=>!M.startsWith("#")).find(M=>g(M));if(_)return _}const S=v.getData("text/html");if(S){const E=S.match(/<img[^>]+src=["']([^"']+)["']/i);if(E!=null&&E[1])return E[1]}const k=v.getData("text/plain");return k&&g(k)?k:null}function g(v){try{const S=new URL(v).pathname.toLowerCase();return/\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i.test(S)||v.startsWith("data:image/"),!0}catch{return!1}}async function y(v,b,S){const k=await n(),E=we.read(k),_=_t.read(k),M=E.left+(b-_.left)/E.zoom,I=E.top+(S-_.top)/E.zoom;await r(v,M,I,{maxSize:e.maxSize})}async function w(v,b,S){try{const k=await fetch(v);if(!k.ok){console.warn("Failed to fetch image from URL:",v);return}const E=await k.blob();if(!E.type.startsWith("image/")){console.warn("URL did not return an image:",v);return}const M=new URL(v).pathname.split("/").pop()||"image",I=new File([E],M,{type:E.type});await y(I,b,S)}catch(k){console.warn("Failed to load image from URL:",v,k)}}return(v,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))}}),s5={class:"wov-user-cursors"},i5={class:"wov-cursor-svg",viewBox:"0 0 4.35 4.75",width:"20",height:"20"},a5=["fill"],l5="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",c5=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",s5,[(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",i5,[d.createElementVNode("path",{fill:s.color,stroke:"#fff","stroke-miterlimit":"10","stroke-width":".25",d:l5},null,8,a5)])),d.createElementVNode("span",{class:"wov-cursor-label",style:d.normalizeStyle({backgroundColor:s.color})},d.toDisplayString(s.name),5)],4))),128))]))}}),u5={key:0,class:"wov-offline-indicator"},d5=d.defineComponent({__name:"OfflineIndicator",props:{isOnline:{type:Boolean}},setup(t){return(e,n)=>t.isOnline?d.createCommentVNode("",!0):(d.openBlock(),d.createElementBlock("div",u5,"Working Offline"))}}),f5={key:0,class:"wov-version-mismatch-overlay"},h5=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",f5,[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)}}),p5=d.defineComponent({__name:"BackToContentButton",setup(t){const{nextEditorTick:e}=ut(),n=jt(we),r=ie(l=>l.with(me,T,Ve)),o=d.ref(0),s=d.inject(Rn);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 _=Ve.read(l,E);u=Math.min(u,_.value[0]),f=Math.min(f,_.value[1]),h=Math.max(h,_.value[2]),p=Math.max(p,_.value[3])}const m=_t.read(l),g=we.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,v=(f+p)/2,b=w-m.width/y/2,S=v-m.height/y/2,k=we.write(l);k.left=b,k.top=S,k.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)}}),m5=["data-entity-id","data-selected","data-held-by-other","data-hovered"],g5=d.defineComponent({__name:"WovenCanvas",props:{store:{},editor:{},background:{},assetProvider:{},pluginOptions:{},controls:{}},emits:["ready"],setup(t,{emit:e}){var yS;const n=ie(B=>B.tracking(T)),r=ie(B=>B.with(T).tracking(Ke)),o=ie(B=>B.with(T).tracking(xt)),s=ie(B=>B.with(T).tracking(Rt)),i=ie(B=>B.with(T).tracking(bo)),a=ie(B=>B.with(T).tracking($r)),l=ie(B=>B.with(T).tracking(lt)),c=ie(B=>B.tracking(Fr)),u=t,f=e,h=d.ref(null),p=d.shallowRef(null),m=ey.parse(((yS=u.editor)==null?void 0:yS.user)??{}),g=new Set,y=new Map,w=d.shallowRef([]),v=new Map,b=new Map,S=new Set,k=new Map,E=d.shallowRef([]),_=d.ref(!0),M=d.ref(!1),I=d.ref(!0),P=d.shallowRef(we.default());function V(B,ke,W){let le=v.get(B);le||(le=new Map,v.set(B,le));let Q=le.get(ke);return Q||(Q=new Set,le.set(ke,Q)),Q.add(W),()=>{Q.delete(W),Q.size===0&&(le.delete(ke),le.size===0&&v.delete(B))}}function Z(B,ke,W,le=!1){const Q=v.get(ke);if(!Q)return;const U=Q.get(W.name);if(!U||U.size===0)return;let ft=null;le||(ft=W.snapshot(B,ke));for(const lr of U)lr(ft)}function A(B,ke){let W=b.get(B);return W||(W=new Set,b.set(B,W)),W.add(ke),()=>{W.delete(ke),W.size===0&&b.delete(B)}}function F(B,ke){const W=b.get(ke.name);if(!W||W.size===0)return;const le=ke.snapshot(B);for(const Q of W)Q(le)}function Y(B){return S.add(B),()=>{S.delete(B)}}function ce(){return m.sessionId}function se(B){return y.get(B)??null}const j={hasEntity:B=>g.has(B),getEditor:()=>p.value,getAssetManager:()=>je,getSessionId:ce,getUserBySessionId:se,subscribeComponent:V,subscribeSingleton:A,registerTickCallback:Y};d.provide(Rn,j),d.provide("containerRef",h);const X=hb();d.provide(F0,X);let he=0,Te=null,Ce=null,je=null;async function ar(){!p.value||!Ce||(p.value.nextTick(B=>{Ks(B),Go(B);for(const ke of S)ke(B);Ce&&Ce.sync(B)}),await p.value.tick(),Te=requestAnimationFrame(ar))}let so=null;d.onMounted(async()=>{var lr,pn;if(!h.value)return;so=()=>{var Ys;(Ys=h.value)==null||Ys.scrollTo(0,0)},h.value.addEventListener("scroll",so);const B=u.store??{},ke={...B};B.websocket&&(ke.websocket={...B.websocket,onVersionMismatch:Ys=>{var io,ul;M.value=!0,(ul=(io=B.websocket)==null?void 0:io.onVersionMismatch)==null||ul.call(io,Ys)},onConnectivityChange:Ys=>{var io,ul;_.value=Ys,(ul=(io=B.websocket)==null?void 0:io.onConnectivityChange)==null||ul.call(io,Ys)}}),Ce=new nm(ke);const W=[],le=u.pluginOptions;(le==null?void 0:le.controls)!==!1&&W.push(j6((le==null?void 0:le.controls)??{})),(le==null?void 0:le.selection)!==!1&&W.push(uP((le==null?void 0:le.selection)||void 0)),(le==null?void 0:le.eraser)!==!1&&W.push(WO((le==null?void 0:le.eraser)||void 0)),(le==null?void 0:le.pen)!==!1&&W.push(BD()),(le==null?void 0:le.arrows)!==!1&&W.push(oO((le==null?void 0:le.arrows)||void 0)),W.push(gS({store:Ce})),(lr=u.editor)!=null&&lr.plugins&&W.push(...u.editor.plugins);const Q={...u.editor,user:m,plugins:W,controls:u.controls},U=new tN(h.value,Q);await U.initialize(),await Ce.initialize({components:U.components,singletons:U.singletons});const ft=((pn=B.persistence)==null?void 0:pn.documentId)??"default";je=new I6({provider:u.assetProvider??new P6,documentId:ft}),await je.init(),await je.resumePendingUploads(),p.value=U,Te=requestAnimationFrame(ar),I.value=!1,f("ready",U,Ce)}),d.onUnmounted(()=>{var B;Te!==null&&cancelAnimationFrame(Te),je==null||je.close(),Ce==null||Ce.close(),(B=p.value)==null||B.dispose()});function Ks(B){const{events:ke,newIndex:W}=B.eventBuffer.readEvents(he);if(he=W,ke.length===0)return;const{componentsById:le,singletonsById:Q}=Je(B);for(const{entityId:U,eventType:ft,componentId:lr}of ke){if(U===Js){if(ft===Le.CHANGED){const pn=Q.get(lr);pn&&F(B,pn)}continue}if(ft===Le.ADDED)g.add(U);else if(ft===Le.REMOVED)g.delete(U),v.delete(U);else if(ft===Le.COMPONENT_ADDED){g.add(U);const pn=le.get(lr);pn&&Z(B,U,pn)}else if(ft===Le.COMPONENT_REMOVED){const pn=le.get(lr);pn&&Z(B,U,pn,!0)}else if(ft===Le.CHANGED){const pn=le.get(lr);pn&&Z(B,U,pn)}}}function Go(B){var le;let ke=!1;for(const Q of n.added(B)){const U=T.snapshot(B,Q),ft=(le=p.value)==null?void 0:le.blockDefs[U.tag],lr=(ft==null?void 0:ft.stratum)??"content";k.set(Q,d.ref({entityId:Q,block:U,stratum:lr,selected:!1,held:null,hovered:!1,edited:!1,opacity:null,connector:null})),ke=!0}for(const Q of n.removed(B))k.delete(Q),ke=!0;for(const Q of n.changed(B)){const U=k.get(Q);if(U){const ft=T.snapshot(B,Q);U.value.block.rank!==ft.rank&&(ke=!0),U.value.block=ft}}let W=!1;for(const Q of c.addedOrChanged(B)){const U=Fr.snapshot(B,Q);y.set(U.sessionId,U),W=!0}for(const Q of c.removed(B)){const U=Fr.read(B,Q);y.delete(U.sessionId),W=!0}W&&(w.value=Array.from(y.values()));for(const Q of o.added(B)){const U=k.get(Q);U&&!U.value.selected&&(U.value.selected=!0)}for(const Q of o.removed(B)){const U=k.get(Q);U&&U.value.selected&&(U.value.selected=!1)}for(const Q of s.addedOrChanged(B)){const U=k.get(Q);U&&(U.value.held=Rt.snapshot(B,Q))}for(const Q of s.removed(B)){const U=k.get(Q);U&&U.value.held!==null&&(U.value.held=null)}for(const Q of i.added(B)){const U=k.get(Q);U&&!U.value.hovered&&(U.value.hovered=!0)}for(const Q of i.removed(B)){const U=k.get(Q);U&&U.value.hovered&&(U.value.hovered=!1)}for(const Q of a.added(B)){const U=k.get(Q);U&&!U.value.edited&&(U.value.edited=!0)}for(const Q of a.removed(B)){const U=k.get(Q);U&&U.value.edited&&(U.value.edited=!1)}for(const Q of l.addedOrChanged(B)){const U=k.get(Q);U&&(U.value.opacity=lt.snapshot(B,Q))}for(const Q of l.removed(B)){const U=k.get(Q);U&&U.value.opacity!==null&&(U.value.opacity=null)}for(const Q of r.addedOrChanged(B)){const U=k.get(Q);U&&(U.value.connector=Ke.snapshot(B,Q))}for(const Q of r.removed(B)){const U=k.get(Q);U&&U.value.connector!==null&&(U.value.connector=null)}if(ke){const Q=Array.from(k.values());Q.sort((U,ft)=>U.value.block.rank>ft.value.block.rank?1:-1),E.value=Q}}A(we.name,B=>{B&&(P.value=B)});function zu(B){const ke=B.rotateZ!==0,W=B.flip[0],le=B.flip[1];if(!ke&&!W&&!le)return;const Q=[];return ke&&Q.push(`rotate(${B.rotateZ}rad)`),W&&Q.push("scaleX(-1)"),le&&Q.push("scaleY(-1)"),Q.join(" ")}function Wi(B){const{held:ke}=B;if(!ke||!ke.sessionId||ke.sessionId===m.sessionId)return null;const W=se(ke.sessionId);return(W==null?void 0:W.color)??null}function Xo(B){const{block:ke,stratum:W,opacity:le}=B,Q=Wi(B),U=le!==null?le.value/255:1;return{position:"absolute",left:`${ke.position[0]}px`,top:`${ke.position[1]}px`,width:`${ke.size[0]}px`,height:`${ke.size[1]}px`,zIndex:Ld[W]*1e3,transform:zu(ke),opacity:U,pointerEvents:"none",userSelect:"none","--wov-held-by-color":Q??void 0,transition:U===1?"opacity 0ms 32ms":void 0}}return(B,ke)=>(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(B.$slots,"background",{key:0,background:t.background},()=>[d.createVNode(qb,{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(${P.value.zoom}) translate(${-P.value.left}px, ${-P.value.top}px)`,"--wov-zoom":P.value.zoom})},[(d.openBlock(!0),d.createElementBlock(d.Fragment,null,d.renderList(E.value,W=>(d.openBlock(),d.createElementBlock("div",{key:W.value.entityId,"data-entity-id":W.value.entityId,style:d.normalizeStyle(Xo(W.value)),"data-selected":W.value.selected||void 0,"data-held-by-other":Wi(W.value)!==null||void 0,"data-hovered":W.value.hovered||void 0,class:"wov-block"},[d.renderSlot(B.$slots,`block:${W.value.block.tag}`,d.mergeProps({ref_for:!0},W.value),()=>[W.value.block.tag==="selection-box"?(d.openBlock(),d.createBlock(W6,d.mergeProps({key:0,ref_for:!0},W.value),null,16)):W.value.block.tag==="transform-box"?(d.openBlock(),d.createBlock(Z6,d.mergeProps({key:1,ref_for:!0},W.value),null,16)):W.value.block.tag==="transform-handle"?(d.openBlock(),d.createBlock(J6,d.mergeProps({key:2,ref_for:!0},W.value),null,16)):W.value.block.tag==="arrow-handle"?(d.openBlock(),d.createBlock(U0,d.mergeProps({key:3,ref_for:!0},W.value),null,16)):W.value.block.tag==="arrow-terminal"?(d.openBlock(),d.createBlock(W0,d.mergeProps({key:4,ref_for:!0},W.value),null,16)):W.value.block.tag==="sticky-note"?(d.openBlock(),d.createBlock(G6,d.mergeProps({key:5,ref_for:!0},W.value),null,16)):W.value.block.tag==="eraser"?(d.openBlock(),d.createBlock(pw,d.mergeProps({key:6,ref_for:!0},W.value),null,16)):W.value.block.tag==="pen-stroke"?(d.openBlock(),d.createBlock(xw,d.mergeProps({key:7,ref_for:!0},W.value),null,16)):W.value.block.tag==="arc-arrow"?(d.openBlock(),d.createBlock(j0,d.mergeProps({key:8,ref_for:!0},W.value),null,16)):W.value.block.tag==="elbow-arrow"?(d.openBlock(),d.createBlock(H0,d.mergeProps({key:9,ref_for:!0},W.value),null,16)):W.value.block.tag==="text"?(d.openBlock(),d.createBlock(mb,d.mergeProps({key:10,ref_for:!0},W.value),null,16)):W.value.block.tag==="image"?(d.openBlock(),d.createBlock(mw,d.mergeProps({key:11,ref_for:!0},W.value),null,16)):W.value.block.tag==="shape"?(d.openBlock(),d.createBlock(pb,d.mergeProps({key:12,ref_for:!0},W.value),null,16)):d.createCommentVNode("",!0)])],12,m5))),128))],4),p.value?d.renderSlot(B.$slots,"user-cursors",{key:1,users:w.value,currentSessionId:d.unref(m).sessionId,camera:P.value},()=>[d.createVNode(c5,{users:w.value,"current-session-id":d.unref(m).sessionId,camera:P.value},null,8,["users","current-session-id","camera"])]):d.createCommentVNode("",!0),p.value?(d.openBlock(),d.createBlock(Xb,{key:2},{default:d.withCtx(W=>[d.renderSlot(B.$slots,"floating-menu",d.normalizeProps(d.guardReactiveProps(W)))]),_:3})):d.createCommentVNode("",!0),p.value?d.renderSlot(B.$slots,"user-presence",{key:3,users:w.value},()=>[d.createVNode(dS,{users:w.value},null,8,["users"])]):d.createCommentVNode("",!0),p.value?d.renderSlot(B.$slots,"toolbar",{key:4},()=>[d.createVNode(uS)]):d.createCommentVNode("",!0),p.value?d.renderSlot(B.$slots,"default",{key:5}):d.createCommentVNode("",!0),d.renderSlot(B.$slots,"offline-indicator",{isOnline:_.value},()=>[d.createVNode(d5,{"is-online":_.value},null,8,["is-online"])]),d.renderSlot(B.$slots,"version-mismatch",{versionMismatch:M.value},()=>[d.createVNode(h5,{"version-mismatch":M.value},null,8,["version-mismatch"])]),d.renderSlot(B.$slots,"back-to-content",{},()=>[d.createVNode(p5)]),d.renderSlot(B.$slots,"loading",{isLoading:I.value},()=>[d.createVNode(Qb,{"is-loading":I.value},null,8,["is-loading"])]),p.value?d.renderSlot(B.$slots,"file-drop-zone",{key:6},()=>[d.createVNode(o5)]):d.createCommentVNode("",!0)],512))}});L.ARROW_HEADS=Cf,L.ArcArrow=j0,L.ArcArrowTool=S6,L.ArrowHandle=U0,L.ArrowHead=Kr,L.ArrowHeadButton=lp,L.ArrowTerminal=W0,L.ArrowThicknessButton=$b,L.CURSORS=eS,L.CanvasBackground=qb,L.CanvasComponentDef=qt,L.CanvasSingletonDef=vt,L.CanvasStore=nm,L.ColorButton=Fb,L.ColorPicker=Vb,L.CursorKind=Fs,L.EditableText=mu,L.EditingPlugin=gS,L.ElbowArrow=H0,L.ElbowArrowTool=lS,L.Eraser=pw,L.EraserTool=sS,L.FloatingMenu=Xb,L.FloatingMenuBar=Gb,L.HandTool=nS,L.IconChevronDown=Un,L.ImageBlock=mw,L.ImageTool=cS,L.LoadingOverlay=Qb,L.MenuButton=Ui,L.MenuDropdown=jn,L.MenuTooltip=cp,L.PenStroke=xw,L.PenStrokeThicknessButton=jb,L.PenTool=iS,L.SHAPES=Ba,L.SelectTool=tS,L.Shape=Nn,L.ShapeBlock=pb,L.ShapeFillColorButton=Ub,L.ShapeKindButton=Wb,L.ShapeStrokeColorButton=Hb,L.ShapeTool=oS,L.StickyNoteTool=rS,L.StrokeKind=Ct,L.Synced=me,L.TextAlignment=Bn,L.TextAlignmentButton=up,L.TextBlock=mb,L.TextBoldButton=dp,L.TextColorButton=yp,L.TextFontFamilyButton=hp,L.TextFontSizeButton=pp,L.TextItalicButton=mp,L.TextTool=aS,L.TextUnderlineButton=gp,L.Toolbar=uS,L.ToolbarButton=Mr,L.User=Fr,L.UserPresence=dS,L.WovenCanvas=g5,L.computeCommonComponents=Jb,L.createTooltipContext=hb,L.defineCanvasComponent=Qe,L.defineCanvasSingleton=Zi,L.getArrowHead=_i,L.useComponent=Tt,L.useComponents=Zo,L.useEditorContext=ut,L.useFonts=Kb,L.useQuery=sb,L.useSingleton=jt,L.useTextBatchController=fb,L.useTextEditorController=ol,L.useTextFormatting=Cr,L.useTextStretchBehavior=Qh,L.useToolbar=ep,L.useTooltipSingleton=Yo,Object.defineProperty(L,Symbol.toStringTag,{value:"Module"})});
|